uguid-2.2.1/.cargo_vcs_info.json0000644000000001430000000000100121510ustar { "git": { "sha1": "02d38c2da469aa01519f094d2fd23dffde451761" }, "path_in_vcs": "uguid" }uguid-2.2.1/CHANGELOG.md000064400000000000000000000063401046102023000125570ustar 00000000000000# 2.2.1 * MSRV increased to 1.81. * The `Error` trait is now unconditionally implemented for `GuidFromStrError`. # 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` impl for `GuidFromStrError`. uguid-2.2.1/Cargo.lock0000644000000203420000000000100101270ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bytemuck" version = "1.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" dependencies = [ "bytemuck_derive", ] [[package]] name = "bytemuck_derive" version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "glob" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "hashbrown" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" [[package]] name = "indexmap" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3954d50fe15b02142bf25d3b8bdadb634ec3948f103d04ffe3031bc8fe9d7058" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "itoa", "memchr", "ryu", "serde", ] [[package]] name = "serde_spanned" version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" dependencies = [ "serde", ] [[package]] name = "serde_test" version = "1.0.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f901ee573cab6b3060453d2d5f0bae4e6d628c23c0a962ff9b5f1d7c8d4f1ed" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target-triple" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ac9aa371f599d22256307c24a9d748c041e548cbf599f35d890f9d365361790" [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "toml" version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" dependencies = [ "serde", "serde_spanned", "toml_datetime", "toml_edit", ] [[package]] name = "toml_datetime" version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" dependencies = [ "serde", ] [[package]] name = "toml_edit" version = "0.22.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "winnow", ] [[package]] name = "trybuild" version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ae08be68c056db96f0e6c6dd820727cca756ced9e1f4cc7fdd20e2a55e23898" dependencies = [ "glob", "serde", "serde_derive", "serde_json", "target-triple", "termcolor", "toml", ] [[package]] name = "uguid" version = "2.2.1" dependencies = [ "bytemuck", "serde", "serde_test", "trybuild", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36" dependencies = [ "memchr", ] uguid-2.2.1/Cargo.toml0000644000000032710000000000100101540ustar # 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.81" name = "uguid" version = "2.2.1" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false 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", ] [features] bytemuck = ["dep:bytemuck"] serde = ["dep:serde"] std = [] [lib] name = "uguid" path = "src/lib.rs" [[example]] name = "guid_info" path = "examples/guid_info.rs" [[test]] name = "test_guid" path = "tests/test_guid.rs" [[test]] name = "test_macro_error" path = "tests/test_macro_error.rs" [[test]] name = "test_serde" path = "tests/test_serde.rs" [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" uguid-2.2.1/Cargo.toml.orig000064400000000000000000000021401046102023000136270ustar 00000000000000# Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 or the MIT license # , at your # option. This file may not be copied, modified, or distributed # except according to those terms. [package] name = "uguid" version = "2.2.1" 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"] uguid-2.2.1/LICENSE-APACHE000064400000000000000000000261361046102023000126770ustar 00000000000000 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. uguid-2.2.1/LICENSE-MIT000064400000000000000000000020321046102023000123740ustar 00000000000000Copyright 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. uguid-2.2.1/README.md000064400000000000000000000017521046102023000122270ustar 00000000000000# `uguid` [![Crates.io](https://img.shields.io/crates/v/uguid)](https://crates.io/crates/uguid) [![Docs.rs](https://docs.rs/uguid/badge.svg)](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`: Currently has no effect. ## Minimum Supported Rust Version (MSRV) The current MSRV is 1.81. ## 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. uguid-2.2.1/examples/guid_info.rs000064400000000000000000000044031046102023000150730ustar 00000000000000// Copyright 2023> Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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 the 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::() { 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"); } } uguid-2.2.1/src/error.rs000064400000000000000000000031231046102023000132300ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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`]. /// /// [`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}", ) } } } } impl core::error::Error for GuidFromStrError {} uguid-2.2.1/src/guid.rs000064400000000000000000000353661046102023000130450ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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 { // 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::try_parse(s) } } #[cfg(feature = "serde")] impl Serialize for Guid { fn serialize(&self, serializer: S) -> Result 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 Visitor<'_> 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(self, value: &str) -> Result where E: de::Error, { Guid::try_parse(value).map_err(E::custom) } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for Guid { fn deserialize(deserializer: D) -> Result 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, } uguid-2.2.1/src/lib.rs000064400000000000000000000074361046102023000126600ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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`: Currently has no effect. //! //! # 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 //! ] //! ); //! ``` #![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}; /// 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 }}; } uguid-2.2.1/src/util.rs000064400000000000000000000054151046102023000130620ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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 { 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 { 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 { // 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); } } uguid-2.2.1/tests/test_guid.rs000064400000000000000000000130431046102023000144430ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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::(), 16); assert_eq!(mem::align_of::(), 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::() .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::(), Err(GuidFromStrError::Length)); // Wrong separator. let s = "01234567089ab-cdef-0123-456789abcdef"; assert_eq!(s.parse::(), Err(GuidFromStrError::Separator(8))); let s = "01234567-89ab0cdef-0123-456789abcdef"; assert_eq!(s.parse::(), Err(GuidFromStrError::Separator(13))); let s = "01234567-89ab-cdef00123-456789abcdef"; assert_eq!(s.parse::(), Err(GuidFromStrError::Separator(18))); let s = "01234567-89ab-cdef-01230456789abcdef"; assert_eq!(s.parse::(), Err(GuidFromStrError::Separator(23))); // Invalid hex. let s = "g1234567-89ab-cdef-0123-456789abcdef"; assert_eq!(s.parse::(), 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"); } } uguid-2.2.1/tests/test_macro_error.rs000064400000000000000000000007541046102023000160320ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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"); } uguid-2.2.1/tests/test_serde.rs000064400000000000000000000016771046102023000146270ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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::( &[Token::Str("1234")], "GUID string has wrong length (expected 36 bytes)", ); serde_test::assert_de_tokens_error::( &[Token::U64(1234)], "invalid type: integer `1234`, expected a string in the format \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\""); } uguid-2.2.1/tests/ui/guid_hex.rs000064400000000000000000000006531046102023000146700ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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"); } uguid-2.2.1/tests/ui/guid_hex.stderr000064400000000000000000000007131046102023000155440ustar 00000000000000error[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) uguid-2.2.1/tests/ui/guid_len.rs000064400000000000000000000006131046102023000146560ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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"); } uguid-2.2.1/tests/ui/guid_len.stderr000064400000000000000000000006101046102023000155320ustar 00000000000000error[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) uguid-2.2.1/tests/ui/guid_sep.rs000064400000000000000000000006531046102023000146730ustar 00000000000000// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 or the MIT license // , 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"); } uguid-2.2.1/tests/ui/guid_sep.stderr000064400000000000000000000007131046102023000155470ustar 00000000000000error[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)