Third-Party Import of: https://crates.io/crates/uguid
Request Document: go/android3p
For CL Reviewers: go/android3p#reviewing-a-cl
For Build Team: go/ab-third-party-imports
Generated through these steps
(in ~src/android/aosp-main-future-without-vendor repo):
1. python3 development/scripts/get_rust_pkg.py -add3prf -v -o /tmp
uguid-2.2.0
2. cp -r /tmp/uguid-2.2.0/* external/rust/crates/uguid
Test: -
Bug: 375625529
Original import of the code can be found at: https://googleplex-android.googlesource.com/platform/external/rust/crates/uguid/+/refs/heads/third-party-review.
Security Questionnaire: http://b/375625529#comment1
Change-Id: Idae92aefe32b9b88db2a8e696a0f181fea02aae0
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..868d5c4
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,101 @@
+# 2.2.0
+
+* Added `Variant` enum and `Guid::variant` method.
+* Added `Guid::from_random_bytes` constructor.
+* Added `Guid::is_zero` method.
+* Added `Guid::version` method.
+* Conversions of the `time_low` field to/from bytes now treat that field
+ as native endian rather than little endian.
+* Fix non-upper-case-globals linter warning.
+
+# 2.1.0
+
+* Bump MSRV to 1.68.
+* Add docstring for `Guid::from_str`.
+
+# 2.0.1
+
+* Fix typo in readme.
+
+# 2.0.0
+
+* Error messages from `guid!` and `aligned_guid!` have been improved by
+ marking the `parse_or_panic` method `track_caller`.
+* `AlignedGuid` has been removed.
+* `Guid` is now 4-byte aligned.
+* The fields of `Guid` are now private. It is no longer possible to
+ directly construct `Guid`; one of the constructors such as `guid!`,
+ `Guid::new`, or `Guid::from_bytes` must be used instead. New accessor
+ methods have been added for each of the internal fields.
+
+# 1.2.1
+
+* Copied the license files into each package so that the archives on
+ crates.io include them.
+
+# 1.2.0
+
+* Add `Guid::parse_or_panic` and `AlignedGuid::parse_or_panic`. These
+ have the same functionality as the corresponding `try_parse` methods,
+ except they will panic on failure. This is useful in `const` contexts
+ where the panic is used as a compilation error.
+* The `guid!` and `aligned_guid!` macros now force const evaluation of
+ the input. This was the intended behavior before, but it was not
+ implemented correctly. Any new compilation failures caused by this
+ change indicate a bug in the calling code.
+
+# 1.1.1
+
+* Change `Guid` back to `repr(C)` instead of `repr(C, align(1))`. Even
+ though the alignment of the struct is 1-byte either way, structs with
+ any alignment set are not allowed in packed structures so this was a
+ breaking change.
+
+# 1.1.0 (yanked)
+
+* Add `AlignedGuid`, which is identical to `Guid` except the struct is
+ 8-byte aligned instead of 1-byte aligned.
+* The `Guid` and `AlignedGuid` types implement `From` for each other to
+ convert between them.
+* Add `aligned_guid!` macro, which is identical to the `guid!` macro
+ except it creates an `AlignedGuid` instead of a `Guid`.
+
+This release was yanked due to accidentally changing the repr of `Guid`.
+
+# 1.0.4
+
+* Relax version requirements for `bytemuck` and `serde`.
+* Enable `doc_auto_cfg` on docs.rs.
+
+# 1.0.3
+
+* Fix license links in README, take two.
+
+# 1.0.2
+
+* Fix license links in README.
+
+# 1.0.1
+
+* Allow the MIT license to be used in addition to Apache-2.0.
+
+# 1.0.0
+
+* Make `GuidFromStrError` into an enum with three variants to allow for
+ better error messages.
+
+# 0.7.0
+
+* Add a const `Guid::from_bytes` constructor.
+* Make `Guid::to_bytes` const.
+* Remove re-export of `bytemuck` dependency.
+* Make the `bytemuck` dependency optional with the new `bytemuck` feature.
+
+# 0.6.0
+
+* Add `Guid::to_ascii_hex_lower` method. This is a const function that
+ creates a `[u8; 36]` array containing the GUID in standard
+ `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` format.
+* Add `serde` feature (disabled by default) that implements serde's
+ `Serialize` and `Deserialize` traits for the `Guid` type.
+* Remove unused `From<ParseIntError>` impl for `GuidFromStrError`.
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..1802226
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,61 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.68"
+name = "uguid"
+version = "2.2.0"
+description = "GUID (Globally Unique Identifier) no_std library"
+readme = "README.md"
+keywords = [
+ "gpt",
+ "guid",
+ "no_std",
+ "uefi",
+]
+categories = [
+ "data-structures",
+ "embedded",
+ "no-std",
+]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/google/gpt-disk-rs"
+
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = [
+ "--cfg",
+ "docsrs",
+]
+
+[dependencies.bytemuck]
+version = "1.4.0"
+features = ["derive"]
+optional = true
+default-features = false
+
+[dependencies.serde]
+version = "1.0.0"
+features = ["derive"]
+optional = true
+default-features = false
+
+[dev-dependencies.serde_test]
+version = "1.0.0"
+
+[dev-dependencies.trybuild]
+version = "1.0.80"
+
+[features]
+bytemuck = ["dep:bytemuck"]
+serde = ["dep:serde"]
+std = []
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..272f9ba
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,37 @@
+# Copyright 2022 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+# https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+# <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+# option. This file may not be copied, modified, or distributed
+# except according to those terms.
+
+[package]
+name = "uguid"
+version = "2.2.0"
+categories = ["data-structures", "embedded", "no-std"]
+description = "GUID (Globally Unique Identifier) no_std library"
+keywords = ["gpt", "guid", "no_std", "uefi"]
+
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+repository.workspace = true
+
+[dependencies]
+bytemuck = { workspace = true, features = ["derive"], optional = true }
+serde = { version = "1.0.0", default-features = false, features = ["derive"], optional = true }
+
+[dev-dependencies]
+serde_test = "1.0.0"
+trybuild = "1.0.80"
+
+[features]
+# See module docstring in src/lib.rs for details of what these features do.
+bytemuck = ["dep:bytemuck"]
+serde = ["dep:serde"]
+std = []
+
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..eff0d8a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,236 @@
+This project is dual-licensed under Apache 2.0 and MIT terms.
+
+====
+
+MIT License
+
+Copyright 2022 Google LLC
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+===
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..20edcc7
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright 2022 Google LLC
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..93b1515
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,21 @@
+name: "uguid"
+description: "GUID (Globally Unique Identifier) no_std library"
+third_party {
+ identifier {
+ type: "crates.io"
+ value: "uguid"
+ }
+ identifier {
+ type: "Archive"
+ value: "https://static.crates.io/crates/uguid/uguid-2.2.0.crate"
+ primary_source: true
+ }
+ version: "2.2.0"
+ # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same.
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2024
+ month: 11
+ day: 5
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..5a2b844
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1 @@
+include platform/prebuilts/rust:main:/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0521bb6
--- /dev/null
+++ b/README.md
@@ -0,0 +1,32 @@
+# `uguid`
+
+[](https://crates.io/crates/uguid)
+[](https://docs.rs/uguid)
+
+`no_std` library providing a GUID (Globally Unique Identifier) type, as
+used in GPT disks, UEFI, and Microsoft Windows.
+
+[GPT]: https://en.wikipedia.org/wiki/GUID_Partition_Table
+
+## Features
+
+No features are enabled by default.
+
+* `bytemuck`: Implements bytemuck's `Pod` and `Zeroable` traits for `Guid`.
+* `serde`: Implements serde's `Serialize` and `Deserialize` traits for `Guid`.
+* `std`: Provides `std::error::Error` implementation for the error type.
+
+## Minimum Supported Rust Version (MSRV)
+
+The current MSRV is 1.68.
+
+## License
+
+Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE)
+or [MIT license](LICENSE-MIT) at your option.
+
+## Disclaimer
+
+This project is not an official Google project. It is not supported by
+Google and Google specifically disclaims all warranties as to its quality,
+merchantability, or fitness for a particular purpose.
diff --git a/examples/guid_info.rs b/examples/guid_info.rs
new file mode 100644
index 0000000..56160ca
--- /dev/null
+++ b/examples/guid_info.rs
@@ -0,0 +1,82 @@
+// Copyright 2023> Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::{env, process};
+use uguid::Guid;
+
+const USAGE: &str = r#"
+usage: guid_info <guid>
+the <guid> format is "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
+where each `x` is a hex digit (any of `0-9`, `a-f`, or `A-F`).
+"#;
+
+fn format_bytes(bytes: &[u8]) -> String {
+ let mut s = String::new();
+ for (i, byte) in bytes.iter().enumerate() {
+ if i != 0 && (i % 2) == 0 {
+ s.push(' ');
+ }
+ s += &format!("{byte:02x}");
+ }
+ s
+}
+
+fn format_guid(guid: Guid) -> String {
+ format!(
+ "guid: {guid}
+ version: {version}
+ variant: {variant:?}
+ time_low: {time_low}
+ time_mid: {time_mid}
+ time_high_and_version: {time_high_and_version}
+ clock_seq_high_and_reserved: {clock_seq_high_and_reserved}
+ clock_seq_low: {clock_seq_low}
+ node: {node}",
+ version = guid.version(),
+ variant = guid.variant(),
+ time_low = format_bytes(&guid.time_low()),
+ time_mid = format_bytes(&guid.time_mid()),
+ time_high_and_version = format_bytes(&guid.time_high_and_version()),
+ clock_seq_high_and_reserved =
+ format_bytes(&[guid.clock_seq_high_and_reserved()]),
+ clock_seq_low = format_bytes(&[guid.clock_seq_low()]),
+ node = format_bytes(&guid.node())
+ )
+}
+
+fn main() {
+ let args: Vec<_> = env::args().collect();
+ if args.len() != 2 {
+ println!("{}", USAGE.trim());
+ process::exit(1);
+ }
+
+ let arg = &args[1];
+ match arg.parse::<Guid>() {
+ Ok(guid) => {
+ println!("{}", format_guid(guid));
+ }
+ Err(err) => {
+ println!("invalid input: {err}");
+ process::exit(1);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_format_bytes() {
+ assert_eq!(format_bytes(&[]), "");
+ assert_eq!(format_bytes(&[0]), "00");
+ assert_eq!(format_bytes(&[0x12, 0x34]), "1234");
+ assert_eq!(format_bytes(&[0x12, 0x34, 0x56, 0x78]), "1234 5678");
+ }
+}
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 0000000..fd50084
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,55 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::fmt::{self, Display, Formatter};
+
+/// Error type for [`Guid::try_parse`] and [`Guid::from_str`].
+///
+/// If the `std` feature is enabled, this type implements the [`Error`]
+/// trait.
+///
+/// [`Error`]: std::error::Error
+/// [`Guid::from_str`]: core::str::FromStr::from_str
+/// [`Guid::try_parse`]: crate::Guid::try_parse
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
+pub enum GuidFromStrError {
+ /// Input has the wrong length, expected 36 bytes.
+ Length,
+
+ /// Input is missing a separator (`-`) at this byte index.
+ Separator(u8),
+
+ /// Input contains invalid ASCII hex at this byte index.
+ Hex(u8),
+}
+
+impl Default for GuidFromStrError {
+ fn default() -> Self {
+ Self::Length
+ }
+}
+
+impl Display for GuidFromStrError {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Length => {
+ f.write_str("GUID string has wrong length (expected 36 bytes)")
+ }
+ Self::Separator(index) => write!(
+ f,
+ "GUID string is missing a separator (`-`) at index {index}",
+ ),
+ Self::Hex(index) => {
+ write!(
+ f,
+ "GUID string contains invalid ASCII hex at index {index}",
+ )
+ }
+ }
+ }
+}
diff --git a/src/guid.rs b/src/guid.rs
new file mode 100644
index 0000000..e1b1304
--- /dev/null
+++ b/src/guid.rs
@@ -0,0 +1,480 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use crate::util::{byte_to_ascii_hex_lower, parse_byte_from_ascii_str_at};
+use crate::GuidFromStrError;
+use core::fmt::{self, Display, Formatter};
+use core::str::{self, FromStr};
+
+#[cfg(feature = "serde")]
+use {
+ serde::de::{self, Visitor},
+ serde::{Deserialize, Deserializer, Serialize, Serializer},
+};
+
+#[cfg(feature = "bytemuck")]
+use bytemuck::{Pod, Zeroable};
+
+/// Globally-unique identifier.
+///
+/// The format is defined in [RFC 4122]. However, unlike "normal" UUIDs
+/// (such as those provided by the [`uuid`] crate), the first three
+/// fields are little-endian. See also [Appendix A] of the UEFI
+/// Specification.
+///
+/// This type is 4-byte aligned. The UEFI Specification says the GUID
+/// type should be 8-byte aligned, but most C implementations have
+/// 4-byte alignment, so we do the same here for compatibility.
+///
+/// [Appendix A]: https://uefi.org/specs/UEFI/2.10/Apx_A_GUID_and_Time_Formats.html
+/// [RFC 4122]: https://datatracker.ietf.org/doc/html/rfc4122
+/// [`uuid`]: https://docs.rs/uuid/latest/uuid
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
+#[cfg_attr(feature = "bytemuck", derive(Pod, Zeroable))]
+#[repr(C)]
+pub struct Guid {
+ // Use `u32` rather than `[u8; 4]` here so that the natural
+ // alignment of the struct is four bytes. This is better for the end
+ // user than setting `repr(align(4))` because it doesn't prevent use
+ // of the type in a `repr(packed)` struct. For more discussion, see
+ // https://github.com/rust-lang/rfcs/pull/1358#issuecomment-217582887
+ time_low: u32,
+ time_mid: [u8; 2],
+ time_high_and_version: [u8; 2],
+ clock_seq_high_and_reserved: u8,
+ clock_seq_low: u8,
+ node: [u8; 6],
+}
+
+impl Guid {
+ /// GUID with all fields set to zero.
+ pub const ZERO: Self = Self {
+ time_low: 0,
+ time_mid: [0, 0],
+ time_high_and_version: [0, 0],
+ clock_seq_high_and_reserved: 0,
+ clock_seq_low: 0,
+ node: [0; 6],
+ };
+
+ /// Create a new GUID.
+ #[must_use]
+ pub const fn new(
+ time_low: [u8; 4],
+ time_mid: [u8; 2],
+ time_high_and_version: [u8; 2],
+ clock_seq_high_and_reserved: u8,
+ clock_seq_low: u8,
+ node: [u8; 6],
+ ) -> Self {
+ Self {
+ time_low: u32::from_ne_bytes([
+ time_low[0],
+ time_low[1],
+ time_low[2],
+ time_low[3],
+ ]),
+ time_mid: [time_mid[0], time_mid[1]],
+ time_high_and_version: [
+ time_high_and_version[0],
+ time_high_and_version[1],
+ ],
+ clock_seq_high_and_reserved,
+ clock_seq_low,
+ node,
+ }
+ }
+
+ /// Create a version 4 GUID from provided random bytes.
+ ///
+ /// See [RFC 4122 section 4.4][rfc] for the definition of a version
+ /// 4 GUID.
+ ///
+ /// This constructor does not itself generate random bytes, but
+ /// instead expects the caller to provide suitably random bytes.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use uguid::{Guid, Variant};
+ ///
+ /// let guid = Guid::from_random_bytes([
+ /// 104, 192, 95, 215, 120, 33, 249, 1, 102, 21, 171, 84, 233, 204, 68, 176,
+ /// ]);
+ /// assert_eq!(guid.variant(), Variant::Rfc4122);
+ /// assert_eq!(guid.version(), 4);
+ /// ```
+ ///
+ /// [rfc]: https://datatracker.ietf.org/doc/html/rfc4122#section-4.4
+ #[must_use]
+ pub const fn from_random_bytes(mut random_bytes: [u8; 16]) -> Self {
+ // Set the variant in byte 8: set bit 7, clear bit 6.
+ random_bytes[8] &= 0b1011_1111;
+ random_bytes[8] |= 0b1000_0000;
+ // Set the version in byte 7: set the most-significant-nibble to 4.
+ random_bytes[7] &= 0b0000_1111;
+ random_bytes[7] |= 0b0100_1111;
+
+ Self::from_bytes(random_bytes)
+ }
+
+ /// True if all bits are zero, false otherwise.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use uguid::guid;
+ ///
+ /// assert!(guid!("00000000-0000-0000-0000-000000000000").is_zero());
+ /// assert!(!guid!("308bbc16-a308-47e8-8977-5e5646c5291f").is_zero());
+ /// ```
+ #[must_use]
+ pub const fn is_zero(self) -> bool {
+ let b = self.to_bytes();
+ b[0] == 0
+ && b[1] == 0
+ && b[2] == 0
+ && b[3] == 0
+ && b[4] == 0
+ && b[5] == 0
+ && b[6] == 0
+ && b[7] == 0
+ && b[8] == 0
+ && b[9] == 0
+ && b[10] == 0
+ && b[11] == 0
+ && b[12] == 0
+ && b[13] == 0
+ && b[14] == 0
+ && b[15] == 0
+ }
+
+ /// The little-endian low field of the timestamp.
+ #[must_use]
+ pub const fn time_low(self) -> [u8; 4] {
+ self.time_low.to_ne_bytes()
+ }
+
+ /// The little-endian middle field of the timestamp.
+ #[must_use]
+ pub const fn time_mid(self) -> [u8; 2] {
+ self.time_mid
+ }
+
+ /// The little-endian high field of the timestamp multiplexed with
+ /// the version number.
+ #[must_use]
+ pub const fn time_high_and_version(self) -> [u8; 2] {
+ self.time_high_and_version
+ }
+
+ /// The high field of the clock sequence multiplexed with the
+ /// variant.
+ #[must_use]
+ pub const fn clock_seq_high_and_reserved(self) -> u8 {
+ self.clock_seq_high_and_reserved
+ }
+
+ /// The low field of the clock sequence.
+ #[must_use]
+ pub const fn clock_seq_low(self) -> u8 {
+ self.clock_seq_low
+ }
+
+ /// The spatially unique node identifier.
+ #[must_use]
+ pub const fn node(self) -> [u8; 6] {
+ self.node
+ }
+
+ /// Get the GUID variant.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use uguid::{guid, Variant};
+ ///
+ /// assert_eq!(
+ /// guid!("308bbc16-a308-47e8-8977-5e5646c5291f").variant(),
+ /// Variant::Rfc4122
+ /// );
+ /// ```
+ #[must_use]
+ pub const fn variant(self) -> Variant {
+ // Get the 3 most significant bits of `clock_seq_high_and_reserved`.
+ let bits = (self.clock_seq_high_and_reserved & 0b1110_0000) >> 5;
+
+ if (bits & 0b100) == 0 {
+ Variant::ReservedNcs
+ } else if (bits & 0b010) == 0 {
+ Variant::Rfc4122
+ } else if (bits & 0b001) == 0 {
+ Variant::ReservedMicrosoft
+ } else {
+ Variant::ReservedFuture
+ }
+ }
+
+ /// Get the GUID version. This is a sub-type of the variant as
+ /// defined in [RFC4122].
+ ///
+ /// [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.3
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use uguid::guid;
+ ///
+ /// assert_eq!(guid!("308bbc16-a308-47e8-8977-5e5646c5291f").version(), 4);
+ /// ```
+ #[must_use]
+ pub const fn version(self) -> u8 {
+ (self.time_high_and_version[1] & 0b1111_0000) >> 4
+ }
+
+ /// Parse a GUID from a string.
+ ///
+ /// This is functionally the same as [`Self::from_str`], but is
+ /// exposed separately to provide a `const` method for parsing.
+ pub const fn try_parse(s: &str) -> Result<Self, GuidFromStrError> {
+ // Treat input as ASCII.
+ let s = s.as_bytes();
+
+ if s.len() != 36 {
+ return Err(GuidFromStrError::Length);
+ }
+
+ let sep = b'-';
+ if s[8] != sep {
+ return Err(GuidFromStrError::Separator(8));
+ }
+ if s[13] != sep {
+ return Err(GuidFromStrError::Separator(13));
+ }
+ if s[18] != sep {
+ return Err(GuidFromStrError::Separator(18));
+ }
+ if s[23] != sep {
+ return Err(GuidFromStrError::Separator(23));
+ }
+
+ Ok(Self::from_bytes([
+ mtry!(parse_byte_from_ascii_str_at(s, 6)),
+ mtry!(parse_byte_from_ascii_str_at(s, 4)),
+ mtry!(parse_byte_from_ascii_str_at(s, 2)),
+ mtry!(parse_byte_from_ascii_str_at(s, 0)),
+ mtry!(parse_byte_from_ascii_str_at(s, 11)),
+ mtry!(parse_byte_from_ascii_str_at(s, 9)),
+ mtry!(parse_byte_from_ascii_str_at(s, 16)),
+ mtry!(parse_byte_from_ascii_str_at(s, 14)),
+ mtry!(parse_byte_from_ascii_str_at(s, 19)),
+ mtry!(parse_byte_from_ascii_str_at(s, 21)),
+ mtry!(parse_byte_from_ascii_str_at(s, 24)),
+ mtry!(parse_byte_from_ascii_str_at(s, 26)),
+ mtry!(parse_byte_from_ascii_str_at(s, 28)),
+ mtry!(parse_byte_from_ascii_str_at(s, 30)),
+ mtry!(parse_byte_from_ascii_str_at(s, 32)),
+ mtry!(parse_byte_from_ascii_str_at(s, 34)),
+ ]))
+ }
+
+ /// Parse a GUID from a string, panicking on failure.
+ ///
+ /// The input must be in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
+ /// format, where each `x` is a hex digit (any of `0-9`, `a-f`, or
+ /// `A-F`).
+ ///
+ /// This function is marked `track_caller` so that error messages
+ /// point directly to the invalid GUID string.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if the input is not in the format shown
+ /// above. In particular, it will panic if the input is not exactly
+ /// 36 bytes long, or if the input does not have separators at the
+ /// expected positions, or if any of the remaining characters are
+ /// not valid hex digits.
+ #[must_use]
+ #[track_caller]
+ pub const fn parse_or_panic(s: &str) -> Self {
+ match Self::try_parse(s) {
+ Ok(g) => g,
+ Err(GuidFromStrError::Length) => {
+ panic!("GUID string has wrong length (expected 36 bytes)");
+ }
+ Err(GuidFromStrError::Separator(_)) => {
+ panic!("GUID string is missing one or more separators (`-`)");
+ }
+ Err(GuidFromStrError::Hex(_)) => {
+ panic!("GUID string contains one or more invalid characters");
+ }
+ }
+ }
+
+ /// Create a GUID from a 16-byte array. No changes to byte order are made.
+ #[must_use]
+ pub const fn from_bytes(bytes: [u8; 16]) -> Self {
+ Self::new(
+ [bytes[0], bytes[1], bytes[2], bytes[3]],
+ [bytes[4], bytes[5]],
+ [bytes[6], bytes[7]],
+ bytes[8],
+ bytes[9],
+ [
+ bytes[10], bytes[11], bytes[12], bytes[13], bytes[14],
+ bytes[15],
+ ],
+ )
+ }
+
+ /// Convert to a 16-byte array.
+ #[must_use]
+ pub const fn to_bytes(self) -> [u8; 16] {
+ let time_low = self.time_low();
+
+ [
+ time_low[0],
+ time_low[1],
+ time_low[2],
+ time_low[3],
+ self.time_mid[0],
+ self.time_mid[1],
+ self.time_high_and_version[0],
+ self.time_high_and_version[1],
+ self.clock_seq_high_and_reserved,
+ self.clock_seq_low,
+ self.node[0],
+ self.node[1],
+ self.node[2],
+ self.node[3],
+ self.node[4],
+ self.node[5],
+ ]
+ }
+
+ /// Convert to a lower-case hex ASCII string.
+ ///
+ /// The output is in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format.
+ #[must_use]
+ pub const fn to_ascii_hex_lower(self) -> [u8; 36] {
+ let bytes = self.to_bytes();
+
+ let mut buf = [0; 36];
+ (buf[0], buf[1]) = byte_to_ascii_hex_lower(bytes[3]);
+ (buf[2], buf[3]) = byte_to_ascii_hex_lower(bytes[2]);
+ (buf[4], buf[5]) = byte_to_ascii_hex_lower(bytes[1]);
+ (buf[6], buf[7]) = byte_to_ascii_hex_lower(bytes[0]);
+ buf[8] = b'-';
+ (buf[9], buf[10]) = byte_to_ascii_hex_lower(bytes[5]);
+ (buf[11], buf[12]) = byte_to_ascii_hex_lower(bytes[4]);
+ buf[13] = b'-';
+ (buf[14], buf[15]) = byte_to_ascii_hex_lower(bytes[7]);
+ (buf[16], buf[17]) = byte_to_ascii_hex_lower(bytes[6]);
+ buf[18] = b'-';
+ (buf[19], buf[20]) = byte_to_ascii_hex_lower(bytes[8]);
+ (buf[21], buf[22]) = byte_to_ascii_hex_lower(bytes[9]);
+ buf[23] = b'-';
+ (buf[24], buf[25]) = byte_to_ascii_hex_lower(bytes[10]);
+ (buf[26], buf[27]) = byte_to_ascii_hex_lower(bytes[11]);
+ (buf[28], buf[29]) = byte_to_ascii_hex_lower(bytes[12]);
+ (buf[30], buf[31]) = byte_to_ascii_hex_lower(bytes[13]);
+ (buf[32], buf[33]) = byte_to_ascii_hex_lower(bytes[14]);
+ (buf[34], buf[35]) = byte_to_ascii_hex_lower(bytes[15]);
+ buf
+ }
+}
+
+impl Default for Guid {
+ fn default() -> Self {
+ Self::ZERO
+ }
+}
+
+impl Display for Guid {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ let ascii = self.to_ascii_hex_lower();
+ // OK to unwrap since the ascii output is valid utf-8.
+ let s = str::from_utf8(&ascii).unwrap();
+ f.write_str(s)
+ }
+}
+
+impl FromStr for Guid {
+ type Err = GuidFromStrError;
+
+ /// Parse a GUID from a string, panicking on failure.
+ ///
+ /// The input must be in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
+ /// format, where each `x` is a hex digit (any of `0-9`, `a-f`, or
+ /// `A-F`).
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ Self::try_parse(s)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl Serialize for Guid {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let ascii = self.to_ascii_hex_lower();
+ // OK to unwrap since the ascii output is valid utf-8.
+ let s = str::from_utf8(&ascii).unwrap();
+ serializer.serialize_str(s)
+ }
+}
+
+#[cfg(feature = "serde")]
+struct DeserializerVisitor;
+
+#[cfg(feature = "serde")]
+impl<'de> Visitor<'de> for DeserializerVisitor {
+ type Value = Guid;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str(
+ "a string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"",
+ )
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ Guid::try_parse(value).map_err(E::custom)
+ }
+}
+
+#[cfg(feature = "serde")]
+impl<'de> Deserialize<'de> for Guid {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ deserializer.deserialize_str(DeserializerVisitor)
+ }
+}
+
+/// Variant or type of GUID, as defined in [RFC4122].
+///
+/// [RFC4122]: https://datatracker.ietf.org/doc/html/rfc4122#section-4.1.3
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
+pub enum Variant {
+ /// Reserved, NCS backward compatibility.
+ ReservedNcs,
+
+ /// The GUID variant described by RFC4122.
+ Rfc4122,
+
+ /// Reserved, Microsoft Corporation backward compatibility.
+ ReservedMicrosoft,
+
+ /// Reserved for future use.
+ ReservedFuture,
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..655295e
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,148 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Library providing a GUID (Globally Unique Identifier) type. The
+//! format is defined in [RFC 4122]. However, unlike "normal" UUIDs
+//! (such as those provided by the [`uuid`] crate), the first three
+//! fields are little-endian. See [Appendix A] of the UEFI
+//! Specification. This format of GUID is also used in Microsoft
+//! Windows.
+//!
+//! [Appendix A]: https://uefi.org/specs/UEFI/2.10/Apx_A_GUID_and_Time_Formats.html
+//! [RFC 4122]: https://datatracker.ietf.org/doc/html/rfc4122
+//! [`uuid`]: https://docs.rs/uuid/latest/uuid
+//!
+//! # Features
+//!
+//! No features are enabled by default.
+//!
+//! * `bytemuck`: Implements bytemuck's `Pod` and `Zeroable` traits for `Guid`.
+//! * `serde`: Implements serde's `Serialize` and `Deserialize` traits for `Guid`.
+//! * `std`: Provides `std::error::Error` implementation for the error type.
+//!
+//! # Examples
+//!
+//! Construct a GUID at compile time with the `guid!` macro:
+//!
+//! ```
+//! use uguid::guid;
+//!
+//! let guid = guid!("01234567-89ab-cdef-0123-456789abcdef");
+//! ```
+//!
+//! Parse a GUID at runtime from a string:
+//!
+//! ```
+//! use uguid::Guid;
+//!
+//! let guid: Guid = "01234567-89ab-cdef-0123-456789abcdef".parse().unwrap();
+//! ```
+//!
+//! Construct a GUID from its components or a byte array:
+//!
+//! ```
+//! use uguid::Guid;
+//!
+//! ##[rustfmt::skip]
+//! let guid1 = Guid::from_bytes([
+//! 0x01, 0x02, 0x03, 0x04,
+//! 0x05, 0x06, 0x07, 0x08,
+//! 0x09, 0x10, 0x11, 0x12,
+//! 0x13, 0x14, 0x15, 0x16,
+//! ]);
+//! let guid2 = Guid::new(
+//! [0x01, 0x02, 0x03, 0x04],
+//! [0x05, 0x06],
+//! [0x07, 0x08],
+//! 0x09,
+//! 0x10,
+//! [0x11, 0x12, 0x13, 0x14, 0x15, 0x16],
+//! );
+//! assert_eq!(guid1, guid2);
+//! ```
+//!
+//! Convert to a string or a byte array:
+//!
+//! ```
+//! use uguid::guid;
+//!
+//! let guid = guid!("01234567-89ab-cdef-0123-456789abcdef");
+//! assert_eq!(guid.to_string(), "01234567-89ab-cdef-0123-456789abcdef");
+//! assert_eq!(
+//! guid.to_bytes(),
+//! [
+//! 0x67, 0x45, 0x23, 0x01, 0xab, 0x89, 0xef, 0xcd, 0x01, 0x23, 0x45,
+//! 0x67, 0x89, 0xab, 0xcd, 0xef
+//! ]
+//! );
+//! ```
+
+#![cfg_attr(not(feature = "std"), no_std)]
+#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+#![warn(missing_copy_implementations)]
+#![warn(missing_debug_implementations)]
+#![warn(missing_docs)]
+#![warn(trivial_casts)]
+#![warn(trivial_numeric_casts)]
+#![warn(unreachable_pub)]
+#![warn(unsafe_code)]
+#![warn(clippy::pedantic)]
+#![warn(clippy::as_conversions)]
+#![allow(clippy::missing_errors_doc)]
+#![allow(clippy::module_name_repetitions)]
+
+/// Macro replacement for the `?` operator, which cannot be used in
+/// const functions.
+macro_rules! mtry {
+ ($expr:expr $(,)?) => {
+ match $expr {
+ Ok(val) => val,
+ Err(err) => {
+ return Err(err);
+ }
+ }
+ };
+}
+
+mod error;
+mod guid;
+mod util;
+
+pub use error::GuidFromStrError;
+pub use guid::{Guid, Variant};
+
+#[cfg(feature = "std")]
+impl std::error::Error for GuidFromStrError {}
+
+/// Create a [`Guid`] from a string at compile time.
+///
+/// # Examples
+///
+/// ```
+/// use uguid::{guid, Guid};
+/// assert_eq!(
+/// guid!("01234567-89ab-cdef-0123-456789abcdef"),
+/// Guid::new(
+/// [0x67, 0x45, 0x23, 0x01],
+/// [0xab, 0x89],
+/// [0xef, 0xcd],
+/// 0x01,
+/// 0x23,
+/// [0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
+/// )
+/// );
+/// ```
+#[macro_export]
+macro_rules! guid {
+ ($s:literal) => {{
+ // Create a temporary const value to force an error in the input
+ // to fail at compile time.
+ const G: $crate::Guid = $crate::Guid::parse_or_panic($s);
+ G
+ }};
+}
diff --git a/src/util.rs b/src/util.rs
new file mode 100644
index 0000000..b25c672
--- /dev/null
+++ b/src/util.rs
@@ -0,0 +1,103 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use crate::GuidFromStrError;
+
+pub(crate) const fn byte_to_ascii_hex_lower(byte: u8) -> (u8, u8) {
+ let mut l = byte & 0xf;
+ let mut h = byte >> 4;
+ if l <= 9 {
+ l += b'0';
+ } else {
+ l += b'a' - 10;
+ }
+ if h <= 9 {
+ h += b'0';
+ } else {
+ h += b'a' - 10;
+ }
+ (h, l)
+}
+
+/// Parse a hexadecimal ASCII character as a `u8`.
+const fn parse_byte_from_ascii_char(c: u8) -> Option<u8> {
+ match c {
+ b'0' => Some(0x0),
+ b'1' => Some(0x1),
+ b'2' => Some(0x2),
+ b'3' => Some(0x3),
+ b'4' => Some(0x4),
+ b'5' => Some(0x5),
+ b'6' => Some(0x6),
+ b'7' => Some(0x7),
+ b'8' => Some(0x8),
+ b'9' => Some(0x9),
+ b'a' | b'A' => Some(0xa),
+ b'b' | b'B' => Some(0xb),
+ b'c' | b'C' => Some(0xc),
+ b'd' | b'D' => Some(0xd),
+ b'e' | b'E' => Some(0xe),
+ b'f' | b'F' => Some(0xf),
+ _ => None,
+ }
+}
+
+/// Parse a pair of hexadecimal ASCII characters as a `u8`. For example,
+/// `(b'1', b'a')` is parsed as `0x1a`.
+const fn parse_byte_from_ascii_char_pair(a: u8, b: u8) -> Option<u8> {
+ let Some(a) = parse_byte_from_ascii_char(a) else {
+ return None;
+ };
+
+ let Some(b) = parse_byte_from_ascii_char(b) else {
+ return None;
+ };
+
+ Some(a << 4 | b)
+}
+
+/// Parse a pair of hexadecimal ASCII characters at position `start` as
+/// a `u8`.
+pub(crate) const fn parse_byte_from_ascii_str_at(
+ s: &[u8],
+ start: u8,
+) -> Result<u8, GuidFromStrError> {
+ // This `as` conversion is needed because this is a const
+ // function. It is always valid since `usize` is always bigger than
+ // a u8.
+ #![allow(clippy::as_conversions)]
+ let start_usize = start as usize;
+
+ if let Some(byte) =
+ parse_byte_from_ascii_char_pair(s[start_usize], s[start_usize + 1])
+ {
+ Ok(byte)
+ } else {
+ Err(GuidFromStrError::Hex(start))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_to_ascii() {
+ assert_eq!(byte_to_ascii_hex_lower(0x1f), (b'1', b'f'));
+ assert_eq!(byte_to_ascii_hex_lower(0xf1), (b'f', b'1'));
+ }
+
+ #[test]
+ fn test_parse() {
+ assert_eq!(parse_byte_from_ascii_char_pair(b'1', b'a'), Some(0x1a));
+ assert_eq!(parse_byte_from_ascii_char_pair(b'8', b'f'), Some(0x8f));
+
+ assert_eq!(parse_byte_from_ascii_char_pair(b'g', b'a'), None);
+ assert_eq!(parse_byte_from_ascii_char_pair(b'a', b'g'), None);
+ }
+}
diff --git a/tests/test_guid.rs b/tests/test_guid.rs
new file mode 100644
index 0000000..96ee160
--- /dev/null
+++ b/tests/test_guid.rs
@@ -0,0 +1,191 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use core::mem;
+use uguid::{guid, Guid, GuidFromStrError, Variant};
+
+#[test]
+fn test_guid() {
+ assert_eq!(mem::size_of::<Guid>(), 16);
+ assert_eq!(mem::align_of::<Guid>(), 4);
+
+ // Constructors.
+ let guid = Guid::new(
+ 0x01234567_u32.to_le_bytes(),
+ 0x89ab_u16.to_le_bytes(),
+ 0xcdef_u16.to_le_bytes(),
+ 0x01,
+ 0x23,
+ [0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
+ );
+ let guid2 = Guid::from_bytes([
+ 0x67, 0x45, 0x23, 0x01, 0xab, 0x89, 0xef, 0xcd, 0x01, 0x23, 0x45, 0x67,
+ 0x89, 0xab, 0xcd, 0xef,
+ ]);
+ assert_eq!(guid, guid2);
+
+ // Accessors.
+ assert_eq!(guid.time_low(), [0x67, 0x45, 0x23, 0x01]);
+ assert_eq!(guid.time_mid(), [0xab, 0x89]);
+ assert_eq!(guid.time_high_and_version(), [0xef, 0xcd]);
+ assert_eq!(guid.clock_seq_high_and_reserved(), 0x01);
+ assert_eq!(guid.clock_seq_low(), 0x23);
+ assert_eq!(guid.node(), [0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
+
+ // To byte array.
+ assert_eq!(
+ guid.to_bytes(),
+ [
+ 0x67, 0x45, 0x23, 0x01, 0xab, 0x89, 0xef, 0xcd, 0x01, 0x23, 0x45,
+ 0x67, 0x89, 0xab, 0xcd, 0xef
+ ]
+ );
+
+ // Formatting.
+ assert_eq!(
+ guid.to_ascii_hex_lower(),
+ *b"01234567-89ab-cdef-0123-456789abcdef"
+ );
+ assert_eq!(guid.to_string(), "01234567-89ab-cdef-0123-456789abcdef");
+
+ // Parsing.
+ assert_eq!(
+ "01234567-89ab-cdef-0123-456789abcdef"
+ .parse::<Guid>()
+ .unwrap(),
+ guid
+ );
+ assert_eq!(
+ Guid::try_parse("01234567-89ab-cdef-0123-456789abcdef").unwrap(),
+ guid
+ );
+
+ // Macro.
+ assert_eq!(guid!("01234567-89ab-cdef-0123-456789abcdef"), guid);
+}
+
+#[test]
+fn test_from_random_bytes() {
+ let random_bytes = [
+ 0x68, 0xc0, 0x5f, 0xd7, 0x78, 0x21, 0xf9, 0x01, 0x66, 0x15, 0xab, 0x54,
+ 0xe9, 0xcc, 0x44, 0xb0,
+ ];
+ let expected_bytes = [
+ 0x68, 0xc0, 0x5f, 0xd7, 0x78, 0x21, 0xf9, 0x4f, 0xa6, 0x15, 0xab, 0x54,
+ 0xe9, 0xcc, 0x44, 0xb0,
+ ];
+
+ let guid = Guid::from_random_bytes(random_bytes);
+ assert_eq!(guid.to_bytes(), expected_bytes);
+ assert_eq!(guid.variant(), Variant::Rfc4122);
+ assert_eq!(guid.version(), 4);
+}
+
+#[test]
+fn test_parse_or_panic_success() {
+ let _g = Guid::parse_or_panic("01234567-89ab-cdef-0123-456789abcdef");
+}
+
+#[test]
+#[should_panic]
+fn test_parse_or_panic_len() {
+ let _g = Guid::parse_or_panic("01234567-89ab-cdef-0123-456789abcdef0");
+}
+
+#[test]
+#[should_panic]
+fn test_parse_or_panic_sep() {
+ let _g = Guid::parse_or_panic("01234567089ab-cdef-0123-456789abcdef");
+}
+
+#[test]
+#[should_panic]
+fn test_parse_or_panic_hex() {
+ let _g = Guid::parse_or_panic("g1234567-89ab-cdef-0123-456789abcdef");
+}
+
+#[test]
+fn test_guid_error() {
+ // Wrong length.
+ let s = "01234567-89ab-cdef-0123-456789abcdef0";
+ assert_eq!(s.len(), 37);
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Length));
+
+ // Wrong separator.
+ let s = "01234567089ab-cdef-0123-456789abcdef";
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Separator(8)));
+ let s = "01234567-89ab0cdef-0123-456789abcdef";
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Separator(13)));
+ let s = "01234567-89ab-cdef00123-456789abcdef";
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Separator(18)));
+ let s = "01234567-89ab-cdef-01230456789abcdef";
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Separator(23)));
+
+ // Invalid hex.
+ let s = "g1234567-89ab-cdef-0123-456789abcdef";
+ assert_eq!(s.parse::<Guid>(), Err(GuidFromStrError::Hex(0)));
+
+ assert_eq!(
+ GuidFromStrError::Length.to_string(),
+ "GUID string has wrong length (expected 36 bytes)"
+ );
+ assert_eq!(
+ GuidFromStrError::Separator(8).to_string(),
+ "GUID string is missing a separator (`-`) at index 8"
+ );
+ assert_eq!(
+ GuidFromStrError::Hex(10).to_string(),
+ "GUID string contains invalid ASCII hex at index 10"
+ );
+}
+
+#[test]
+fn test_guid_variant() {
+ assert_eq!(
+ guid!("00000000-0000-0000-0000-000000000000").variant(),
+ Variant::ReservedNcs
+ );
+ assert_eq!(
+ guid!("00000000-0000-0000-8000-000000000000").variant(),
+ Variant::Rfc4122
+ );
+ assert_eq!(
+ guid!("00000000-0000-0000-c000-000000000000").variant(),
+ Variant::ReservedMicrosoft
+ );
+ assert_eq!(
+ guid!("00000000-0000-0000-e000-000000000000").variant(),
+ Variant::ReservedFuture
+ );
+}
+
+#[test]
+fn test_guid_version() {
+ assert_eq!(guid!("00000000-0000-0000-8000-000000000000").version(), 0);
+ assert_eq!(guid!("00000000-0000-1000-8000-000000000000").version(), 1);
+ assert_eq!(guid!("00000000-0000-2000-8000-000000000000").version(), 2);
+ assert_eq!(guid!("00000000-0000-4000-8000-000000000000").version(), 4);
+}
+
+#[test]
+fn test_guid_is_zero() {
+ assert!(guid!("00000000-0000-0000-0000-000000000000").is_zero());
+ assert!(!guid!("308bbc16-a308-47e8-8977-5e5646c5291f").is_zero());
+}
+
+/// Inner module that only imports the `guid!` macro.
+mod inner {
+ use uguid::guid;
+
+ /// Test that the `guid!` macro works without importing anything
+ /// else.
+ #[test]
+ fn test_guid_macro_paths() {
+ let _g = guid!("01234567-89ab-cdef-0123-456789abcdef");
+ }
+}
diff --git a/tests/test_macro_error.rs b/tests/test_macro_error.rs
new file mode 100644
index 0000000..fe3ed66
--- /dev/null
+++ b/tests/test_macro_error.rs
@@ -0,0 +1,14 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+//! Tests errors from the guid macros.
+#[test]
+fn test_compilation_errors() {
+ let t = trybuild::TestCases::new();
+ t.compile_fail("tests/ui/*.rs");
+}
diff --git a/tests/test_serde.rs b/tests/test_serde.rs
new file mode 100644
index 0000000..2cdf37d
--- /dev/null
+++ b/tests/test_serde.rs
@@ -0,0 +1,31 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![cfg(feature = "serde")]
+
+use serde_test::Token;
+use uguid::{guid, Guid};
+
+#[test]
+fn test_serde() {
+ let guid = guid!("01234567-89ab-cdef-0123-456789abcdef");
+
+ serde_test::assert_tokens(
+ &guid,
+ &[Token::Str("01234567-89ab-cdef-0123-456789abcdef")],
+ );
+
+ serde_test::assert_de_tokens_error::<Guid>(
+ &[Token::Str("1234")],
+ "GUID string has wrong length (expected 36 bytes)",
+ );
+
+ serde_test::assert_de_tokens_error::<Guid>(
+ &[Token::U64(1234)],
+ "invalid type: integer `1234`, expected a string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"");
+}
diff --git a/tests/ui/guid_hex.rs b/tests/ui/guid_hex.rs
new file mode 100644
index 0000000..03bf760
--- /dev/null
+++ b/tests/ui/guid_hex.rs
@@ -0,0 +1,13 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use uguid::guid;
+
+fn main() {
+ let _g = guid!("g1234567-89ab-cdef-0123-456789abcdef");
+}
diff --git a/tests/ui/guid_hex.stderr b/tests/ui/guid_hex.stderr
new file mode 100644
index 0000000..9d2a549
--- /dev/null
+++ b/tests/ui/guid_hex.stderr
@@ -0,0 +1,7 @@
+error[E0080]: evaluation of constant value failed
+ --> tests/ui/guid_hex.rs:12:14
+ |
+12 | let _g = guid!("g1234567-89ab-cdef-0123-456789abcdef");
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'GUID string contains one or more invalid characters', $DIR/tests/ui/guid_hex.rs:12:14
+ |
+ = note: this error originates in the macro `guid` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/tests/ui/guid_len.rs b/tests/ui/guid_len.rs
new file mode 100644
index 0000000..5916add
--- /dev/null
+++ b/tests/ui/guid_len.rs
@@ -0,0 +1,13 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use uguid::guid;
+
+fn main() {
+ let _g = guid!("1234");
+}
diff --git a/tests/ui/guid_len.stderr b/tests/ui/guid_len.stderr
new file mode 100644
index 0000000..ee271ff
--- /dev/null
+++ b/tests/ui/guid_len.stderr
@@ -0,0 +1,7 @@
+error[E0080]: evaluation of constant value failed
+ --> tests/ui/guid_len.rs:12:14
+ |
+12 | let _g = guid!("1234");
+ | ^^^^^^^^^^^^^ the evaluated program panicked at 'GUID string has wrong length (expected 36 bytes)', $DIR/tests/ui/guid_len.rs:12:14
+ |
+ = note: this error originates in the macro `guid` (in Nightly builds, run with -Z macro-backtrace for more info)
diff --git a/tests/ui/guid_sep.rs b/tests/ui/guid_sep.rs
new file mode 100644
index 0000000..8d3e541
--- /dev/null
+++ b/tests/ui/guid_sep.rs
@@ -0,0 +1,13 @@
+// Copyright 2022 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use uguid::guid;
+
+fn main() {
+ let _g = guid!("01234567089ab-cdef-0123-456789abcdef");
+}
diff --git a/tests/ui/guid_sep.stderr b/tests/ui/guid_sep.stderr
new file mode 100644
index 0000000..bffd8c0
--- /dev/null
+++ b/tests/ui/guid_sep.stderr
@@ -0,0 +1,7 @@
+error[E0080]: evaluation of constant value failed
+ --> tests/ui/guid_sep.rs:12:14
+ |
+12 | let _g = guid!("01234567089ab-cdef-0123-456789abcdef");
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'GUID string is missing one or more separators (`-`)', $DIR/tests/ui/guid_sep.rs:12:14
+ |
+ = note: this error originates in the macro `guid` (in Nightly builds, run with -Z macro-backtrace for more info)