[go: up one dir, main page]

uuid/
lib.rs

1// Copyright 2013-2014 The Rust Project Developers.
2// Copyright 2018 The Uuid Project Developers.
3//
4// See the COPYRIGHT file at the top-level directory of this distribution.
5//
6// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9// option. This file may not be copied, modified, or distributed
10// except according to those terms.
11
12//! Generate and parse universally unique identifiers (UUIDs).
13//!
14//! Here's an example of a UUID:
15//!
16//! ```text
17//! 67e55044-10b1-426f-9247-bb680e5fe0c8
18//! ```
19//!
20//! A UUID is a unique 128-bit value, stored as 16 octets, and regularly
21//! formatted as a hex string in five groups. UUIDs are used to assign unique
22//! identifiers to entities without requiring a central allocating authority.
23//!
24//! They are particularly useful in distributed systems, though can be used in
25//! disparate areas, such as databases and network protocols.  Typically a UUID
26//! is displayed in a readable string form as a sequence of hexadecimal digits,
27//! separated into groups by hyphens.
28//!
29//! The uniqueness property is not strictly guaranteed, however for all
30//! practical purposes, it can be assumed that an unintentional collision would
31//! be extremely unlikely.
32//!
33//! UUIDs have a number of standardized encodings that are specified in [RFC 9562](https://www.ietf.org/rfc/rfc9562.html).
34//!
35//! # Getting started
36//!
37//! Add the following to your `Cargo.toml`:
38//!
39//! ```toml
40//! [dependencies.uuid]
41//! version = "1.19.0"
42//! # Lets you generate random UUIDs
43//! features = [
44//!     "v4",
45//! ]
46//! ```
47//!
48//! When you want a UUID, you can generate one:
49//!
50//! ```
51//! # fn main() {
52//! # #[cfg(feature = "v4")]
53//! # {
54//! use uuid::Uuid;
55//!
56//! let id = Uuid::new_v4();
57//! # }
58//! # }
59//! ```
60//!
61//! If you have a UUID value, you can use its string literal form inline:
62//!
63//! ```
64//! use uuid::{uuid, Uuid};
65//!
66//! const ID: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
67//! ```
68//!
69//! # Working with different UUID versions
70//!
71//! This library supports all standardized methods for generating UUIDs through individual Cargo features.
72//!
73//! By default, this crate depends on nothing but the Rust standard library and can parse and format
74//! UUIDs, but cannot generate them. Depending on the kind of UUID you'd like to work with, there
75//! are Cargo features that enable generating them:
76//!
77//! * `v1` - Version 1 UUIDs using a timestamp and monotonic counter.
78//! * `v3` - Version 3 UUIDs based on the MD5 hash of some data.
79//! * `v4` - Version 4 UUIDs with random data.
80//! * `v5` - Version 5 UUIDs based on the SHA1 hash of some data.
81//! * `v6` - Version 6 UUIDs using a timestamp and monotonic counter.
82//! * `v7` - Version 7 UUIDs using a Unix timestamp.
83//! * `v8` - Version 8 UUIDs using user-defined data.
84//!
85//! This library also includes a [`Builder`] type that can be used to help construct UUIDs of any
86//! version without any additional dependencies or features. It's a lower-level API than [`Uuid`]
87//! that can be used when you need control over implicit requirements on things like a source
88//! of randomness.
89//!
90//! ## Which UUID version should I use?
91//!
92//! If you just want to generate unique identifiers then consider version 4 (`v4`) UUIDs. If you want
93//! to use UUIDs as database keys or need to sort them then consider version 7 (`v7`) UUIDs.
94//! Other versions should generally be avoided unless there's an existing need for them.
95//!
96//! Some UUID versions supersede others. Prefer version 6 over version 1 and version 5 over version 3.
97//!
98//! # Other features
99//!
100//! Other crate features can also be useful beyond the version support:
101//!
102//! * `macro-diagnostics` - enhances the diagnostics of `uuid!` macro.
103//! * `serde` - adds the ability to serialize and deserialize a UUID using
104//!   `serde`.
105//! * `borsh` - adds the ability to serialize and deserialize a UUID using
106//!   `borsh`.
107//! * `arbitrary` - adds an `Arbitrary` trait implementation to `Uuid` for
108//!   fuzzing.
109//! * `fast-rng` - uses a faster algorithm for generating random UUIDs when available.
110//!   This feature requires more dependencies to compile, but is just as suitable for
111//!   UUIDs as the default algorithm.
112//! * `rng-rand` - forces `rand` as the backend for randomness.
113//! * `rng-getrandom` - forces `getrandom` as the backend for randomness.
114//! * `bytemuck` - adds a `Pod` trait implementation to `Uuid` for byte manipulation
115//!
116//! # Unstable features
117//!
118//! Some features are unstable. They may be incomplete or depend on other
119//! unstable libraries. These include:
120//!
121//! * `zerocopy` - adds support for zero-copy deserialization using the
122//!   `zerocopy` library.
123//!
124//! Unstable features may break between minor releases.
125//!
126//! To allow unstable features, you'll need to enable the Cargo feature as
127//! normal, but also pass an additional flag through your environment to opt-in
128//! to unstable `uuid` features:
129//!
130//! ```text
131//! RUSTFLAGS="--cfg uuid_unstable"
132//! ```
133//!
134//! # Building for other targets
135//!
136//! ## WebAssembly
137//!
138//! For WebAssembly, enable the `js` feature:
139//!
140//! ```toml
141//! [dependencies.uuid]
142//! version = "1.19.0"
143//! features = [
144//!     "v4",
145//!     "v7",
146//!     "js",
147//! ]
148//! ```
149//!
150//! ## Embedded
151//!
152//! For embedded targets without the standard library, you'll need to
153//! disable default features when building `uuid`:
154//!
155//! ```toml
156//! [dependencies.uuid]
157//! version = "1.19.0"
158//! default-features = false
159//! ```
160//!
161//! Some additional features are supported in no-std environments:
162//!
163//! * `v1`, `v3`, `v5`, `v6`, and `v8`.
164//! * `serde`.
165//!
166//! If you need to use `v4` or `v7` in a no-std environment, you'll need to
167//! produce random bytes yourself and then pass them to [`Builder::from_random_bytes`]
168//! without enabling the `v4` or `v7` features.
169//!
170//! If you're using `getrandom`, you can specify the `rng-getrandom` or `rng-rand`
171//! features of `uuid` and configure `getrandom`'s provider per its docs. `uuid`
172//! may upgrade its version of `getrandom` in minor releases.
173//!
174//! # Examples
175//!
176//! Parse a UUID given in the simple format and print it as a URN:
177//!
178//! ```
179//! # use uuid::Uuid;
180//! # fn main() -> Result<(), uuid::Error> {
181//! let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
182//!
183//! println!("{}", my_uuid.urn());
184//! # Ok(())
185//! # }
186//! ```
187//!
188//! Generate a random UUID and print it out in hexadecimal form:
189//!
190//! ```
191//! // Note that this requires the `v4` feature to be enabled.
192//! # use uuid::Uuid;
193//! # fn main() {
194//! # #[cfg(feature = "v4")] {
195//! let my_uuid = Uuid::new_v4();
196//!
197//! println!("{}", my_uuid);
198//! # }
199//! # }
200//! ```
201//!
202//! # References
203//!
204//! * [Wikipedia: Universally Unique Identifier](http://en.wikipedia.org/wiki/Universally_unique_identifier)
205//! * [RFC 9562: Universally Unique IDentifiers (UUID)](https://www.ietf.org/rfc/rfc9562.html).
206//!
207//! [`wasm-bindgen`]: https://crates.io/crates/wasm-bindgen
208
209#![no_std]
210#![deny(missing_debug_implementations, missing_docs)]
211#![allow(clippy::mixed_attributes_style)]
212#![doc(
213    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
214    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
215    html_root_url = "https://docs.rs/uuid/1.19.0"
216)]
217
218#[cfg(any(feature = "std", test))]
219#[macro_use]
220extern crate std;
221
222#[cfg(all(not(feature = "std"), not(test)))]
223#[macro_use]
224extern crate core as std;
225
226#[macro_use]
227mod macros;
228
229mod builder;
230mod error;
231mod non_nil;
232mod parser;
233
234pub mod fmt;
235pub mod timestamp;
236
237use core::hash::{Hash, Hasher};
238pub use timestamp::{context::NoContext, ClockSequence, Timestamp};
239
240#[cfg(any(feature = "v1", feature = "v6"))]
241pub use timestamp::context::Context;
242
243#[cfg(feature = "v7")]
244pub use timestamp::context::ContextV7;
245
246#[cfg(feature = "v1")]
247#[doc(hidden)]
248// Soft-deprecated (Rust doesn't support deprecating re-exports)
249// Use `Context` from the crate root instead
250pub mod v1;
251#[cfg(feature = "v3")]
252mod v3;
253#[cfg(feature = "v4")]
254mod v4;
255#[cfg(feature = "v5")]
256mod v5;
257#[cfg(feature = "v6")]
258mod v6;
259#[cfg(feature = "v7")]
260mod v7;
261#[cfg(feature = "v8")]
262mod v8;
263
264#[cfg(feature = "md5")]
265mod md5;
266#[cfg(feature = "rng")]
267mod rng;
268#[cfg(feature = "sha1")]
269mod sha1;
270
271mod external;
272
273#[doc(hidden)]
274#[cfg(feature = "macro-diagnostics")]
275pub extern crate uuid_macro_internal;
276
277#[doc(hidden)]
278pub mod __macro_support {
279    pub use crate::std::result::Result::{Err, Ok};
280}
281
282pub use crate::{builder::Builder, error::Error, non_nil::NonNilUuid};
283
284/// A 128-bit (16 byte) buffer containing the UUID.
285///
286/// # ABI
287///
288/// The `Bytes` type is always guaranteed to be have the same ABI as [`Uuid`].
289pub type Bytes = [u8; 16];
290
291/// The version of the UUID, denoting the generating algorithm.
292///
293/// # References
294///
295/// * [Version Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.2)
296#[derive(Clone, Copy, Debug, PartialEq)]
297#[non_exhaustive]
298#[repr(u8)]
299pub enum Version {
300    /// The "nil" (all zeros) UUID.
301    Nil = 0u8,
302    /// Version 1: Timestamp and node ID.
303    Mac = 1,
304    /// Version 2: DCE Security.
305    Dce = 2,
306    /// Version 3: MD5 hash.
307    Md5 = 3,
308    /// Version 4: Random.
309    Random = 4,
310    /// Version 5: SHA-1 hash.
311    Sha1 = 5,
312    /// Version 6: Sortable Timestamp and node ID.
313    SortMac = 6,
314    /// Version 7: Timestamp and random.
315    SortRand = 7,
316    /// Version 8: Custom.
317    Custom = 8,
318    /// The "max" (all ones) UUID.
319    Max = 0xff,
320}
321
322/// The reserved variants of UUIDs.
323///
324/// # References
325///
326/// * [Variant Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.1)
327#[derive(Clone, Copy, Debug, PartialEq)]
328#[non_exhaustive]
329#[repr(u8)]
330pub enum Variant {
331    /// Reserved by the NCS for backward compatibility.
332    NCS = 0u8,
333    /// As described in the RFC 9562 Specification (default).
334    /// (for backward compatibility it is not yet renamed)
335    RFC4122,
336    /// Reserved by Microsoft for backward compatibility.
337    Microsoft,
338    /// Reserved for future expansion.
339    Future,
340}
341
342/// A Universally Unique Identifier (UUID).
343///
344/// # Examples
345///
346/// Parse a UUID given in the simple format and print it as a urn:
347///
348/// ```
349/// # use uuid::Uuid;
350/// # fn main() -> Result<(), uuid::Error> {
351/// let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
352///
353/// println!("{}", my_uuid.urn());
354/// # Ok(())
355/// # }
356/// ```
357///
358/// Create a new random (V4) UUID and print it out in hexadecimal form:
359///
360/// ```
361/// // Note that this requires the `v4` feature enabled in the uuid crate.
362/// # use uuid::Uuid;
363/// # fn main() {
364/// # #[cfg(feature = "v4")] {
365/// let my_uuid = Uuid::new_v4();
366///
367/// println!("{}", my_uuid);
368/// # }
369/// # }
370/// ```
371///
372/// # Formatting
373///
374/// A UUID can be formatted in one of a few ways:
375///
376/// * [`simple`](#method.simple): `a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8`.
377/// * [`hyphenated`](#method.hyphenated):
378///   `a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8`.
379/// * [`urn`](#method.urn): `urn:uuid:A1A2A3A4-B1B2-C1C2-D1D2-D3D4D5D6D7D8`.
380/// * [`braced`](#method.braced): `{a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8}`.
381///
382/// The default representation when formatting a UUID with `Display` is
383/// hyphenated:
384///
385/// ```
386/// # use uuid::Uuid;
387/// # fn main() -> Result<(), uuid::Error> {
388/// let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
389///
390/// assert_eq!(
391///     "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8",
392///     my_uuid.to_string(),
393/// );
394/// # Ok(())
395/// # }
396/// ```
397///
398/// Other formats can be specified using adapter methods on the UUID:
399///
400/// ```
401/// # use uuid::Uuid;
402/// # fn main() -> Result<(), uuid::Error> {
403/// let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
404///
405/// assert_eq!(
406///     "urn:uuid:a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8",
407///     my_uuid.urn().to_string(),
408/// );
409/// # Ok(())
410/// # }
411/// ```
412///
413/// # Endianness
414///
415/// The specification for UUIDs encodes the integer fields that make up the
416/// value in big-endian order. This crate assumes integer inputs are already in
417/// the correct order by default, regardless of the endianness of the
418/// environment. Most methods that accept integers have a `_le` variant (such as
419/// `from_fields_le`) that assumes any integer values will need to have their
420/// bytes flipped, regardless of the endianness of the environment.
421///
422/// Most users won't need to worry about endianness unless they need to operate
423/// on individual fields (such as when converting between Microsoft GUIDs). The
424/// important things to remember are:
425///
426/// - The endianness is in terms of the fields of the UUID, not the environment.
427/// - The endianness is assumed to be big-endian when there's no `_le` suffix
428///   somewhere.
429/// - Byte-flipping in `_le` methods applies to each integer.
430/// - Endianness roundtrips, so if you create a UUID with `from_fields_le`
431///   you'll get the same values back out with `to_fields_le`.
432///
433/// # ABI
434///
435/// The `Uuid` type is always guaranteed to be have the same ABI as [`Bytes`].
436#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
437#[repr(transparent)]
438// NOTE: Also check `NonNilUuid` when ading new derives here
439#[cfg_attr(
440    feature = "borsh",
441    derive(borsh_derive::BorshDeserialize, borsh_derive::BorshSerialize)
442)]
443#[cfg_attr(
444    feature = "bytemuck",
445    derive(bytemuck::Zeroable, bytemuck::Pod, bytemuck::TransparentWrapper)
446)]
447#[cfg_attr(
448    all(uuid_unstable, feature = "zerocopy"),
449    derive(
450        zerocopy::IntoBytes,
451        zerocopy::FromBytes,
452        zerocopy::KnownLayout,
453        zerocopy::Immutable,
454        zerocopy::Unaligned
455    )
456)]
457pub struct Uuid(Bytes);
458
459impl Uuid {
460    /// UUID namespace for Domain Name System (DNS).
461    pub const NAMESPACE_DNS: Self = Uuid([
462        0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
463        0xc8,
464    ]);
465
466    /// UUID namespace for ISO Object Identifiers (OIDs).
467    pub const NAMESPACE_OID: Self = Uuid([
468        0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
469        0xc8,
470    ]);
471
472    /// UUID namespace for Uniform Resource Locators (URLs).
473    pub const NAMESPACE_URL: Self = Uuid([
474        0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
475        0xc8,
476    ]);
477
478    /// UUID namespace for X.500 Distinguished Names (DNs).
479    pub const NAMESPACE_X500: Self = Uuid([
480        0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30,
481        0xc8,
482    ]);
483
484    /// Returns the variant of the UUID structure.
485    ///
486    /// This determines the interpretation of the structure of the UUID.
487    /// This method simply reads the value of the variant byte. It doesn't
488    /// validate the rest of the UUID as conforming to that variant.
489    ///
490    /// # Examples
491    ///
492    /// Basic usage:
493    ///
494    /// ```
495    /// # use uuid::{Uuid, Variant};
496    /// # fn main() -> Result<(), uuid::Error> {
497    /// let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?;
498    ///
499    /// assert_eq!(Variant::RFC4122, my_uuid.get_variant());
500    /// # Ok(())
501    /// # }
502    /// ```
503    ///
504    /// # References
505    ///
506    /// * [Variant Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.1)
507    pub const fn get_variant(&self) -> Variant {
508        match self.as_bytes()[8] {
509            x if x & 0x80 == 0x00 => Variant::NCS,
510            x if x & 0xc0 == 0x80 => Variant::RFC4122,
511            x if x & 0xe0 == 0xc0 => Variant::Microsoft,
512            x if x & 0xe0 == 0xe0 => Variant::Future,
513            // The above match arms are actually exhaustive
514            // We just return `Future` here because we can't
515            // use `unreachable!()` in a `const fn`
516            _ => Variant::Future,
517        }
518    }
519
520    /// Returns the version number of the UUID.
521    ///
522    /// This represents the algorithm used to generate the value.
523    /// This method is the future-proof alternative to [`Uuid::get_version`].
524    ///
525    /// # Examples
526    ///
527    /// Basic usage:
528    ///
529    /// ```
530    /// # use uuid::Uuid;
531    /// # fn main() -> Result<(), uuid::Error> {
532    /// let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?;
533    ///
534    /// assert_eq!(3, my_uuid.get_version_num());
535    /// # Ok(())
536    /// # }
537    /// ```
538    ///
539    /// # References
540    ///
541    /// * [Version Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.2)
542    pub const fn get_version_num(&self) -> usize {
543        (self.as_bytes()[6] >> 4) as usize
544    }
545
546    /// Returns the version of the UUID.
547    ///
548    /// This represents the algorithm used to generate the value.
549    /// If the version field doesn't contain a recognized version then `None`
550    /// is returned. If you're trying to read the version for a future extension
551    /// you can also use [`Uuid::get_version_num`] to unconditionally return a
552    /// number. Future extensions may start to return `Some` once they're
553    /// standardized and supported.
554    ///
555    /// # Examples
556    ///
557    /// Basic usage:
558    ///
559    /// ```
560    /// # use uuid::{Uuid, Version};
561    /// # fn main() -> Result<(), uuid::Error> {
562    /// let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?;
563    ///
564    /// assert_eq!(Some(Version::Md5), my_uuid.get_version());
565    /// # Ok(())
566    /// # }
567    /// ```
568    ///
569    /// # References
570    ///
571    /// * [Version Field in RFC 9562](https://www.ietf.org/rfc/rfc9562.html#section-4.2)
572    pub const fn get_version(&self) -> Option<Version> {
573        match self.get_version_num() {
574            0 if self.is_nil() => Some(Version::Nil),
575            1 => Some(Version::Mac),
576            2 => Some(Version::Dce),
577            3 => Some(Version::Md5),
578            4 => Some(Version::Random),
579            5 => Some(Version::Sha1),
580            6 => Some(Version::SortMac),
581            7 => Some(Version::SortRand),
582            8 => Some(Version::Custom),
583            0xf => Some(Version::Max),
584            _ => None,
585        }
586    }
587
588    /// Returns the four field values of the UUID.
589    ///
590    /// These values can be passed to the [`Uuid::from_fields`] method to get
591    /// the original `Uuid` back.
592    ///
593    /// * The first field value represents the first group of (eight) hex
594    ///   digits, taken as a big-endian `u32` value.  For V1 UUIDs, this field
595    ///   represents the low 32 bits of the timestamp.
596    /// * The second field value represents the second group of (four) hex
597    ///   digits, taken as a big-endian `u16` value.  For V1 UUIDs, this field
598    ///   represents the middle 16 bits of the timestamp.
599    /// * The third field value represents the third group of (four) hex digits,
600    ///   taken as a big-endian `u16` value.  The 4 most significant bits give
601    ///   the UUID version, and for V1 UUIDs, the last 12 bits represent the
602    ///   high 12 bits of the timestamp.
603    /// * The last field value represents the last two groups of four and twelve
604    ///   hex digits, taken in order.  The first 1-3 bits of this indicate the
605    ///   UUID variant, and for V1 UUIDs, the next 13-15 bits indicate the clock
606    ///   sequence and the last 48 bits indicate the node ID.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// # use uuid::Uuid;
612    /// # fn main() -> Result<(), uuid::Error> {
613    /// let uuid = Uuid::nil();
614    ///
615    /// assert_eq!(uuid.as_fields(), (0, 0, 0, &[0u8; 8]));
616    ///
617    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
618    ///
619    /// assert_eq!(
620    ///     uuid.as_fields(),
621    ///     (
622    ///         0xa1a2a3a4,
623    ///         0xb1b2,
624    ///         0xc1c2,
625    ///         &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8],
626    ///     )
627    /// );
628    /// # Ok(())
629    /// # }
630    /// ```
631    pub fn as_fields(&self) -> (u32, u16, u16, &[u8; 8]) {
632        let bytes = self.as_bytes();
633
634        let d1 = (bytes[0] as u32) << 24
635            | (bytes[1] as u32) << 16
636            | (bytes[2] as u32) << 8
637            | (bytes[3] as u32);
638
639        let d2 = (bytes[4] as u16) << 8 | (bytes[5] as u16);
640
641        let d3 = (bytes[6] as u16) << 8 | (bytes[7] as u16);
642
643        let d4: &[u8; 8] = bytes[8..16].try_into().unwrap();
644        (d1, d2, d3, d4)
645    }
646
647    /// Returns the four field values of the UUID in little-endian order.
648    ///
649    /// The bytes in the returned integer fields will be converted from
650    /// big-endian order. This is based on the endianness of the UUID,
651    /// rather than the target environment so bytes will be flipped on both
652    /// big and little endian machines.
653    ///
654    /// # Examples
655    ///
656    /// ```
657    /// use uuid::Uuid;
658    ///
659    /// # fn main() -> Result<(), uuid::Error> {
660    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
661    ///
662    /// assert_eq!(
663    ///     uuid.to_fields_le(),
664    ///     (
665    ///         0xa4a3a2a1,
666    ///         0xb2b1,
667    ///         0xc2c1,
668    ///         &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8],
669    ///     )
670    /// );
671    /// # Ok(())
672    /// # }
673    /// ```
674    pub fn to_fields_le(&self) -> (u32, u16, u16, &[u8; 8]) {
675        let d1 = (self.as_bytes()[0] as u32)
676            | (self.as_bytes()[1] as u32) << 8
677            | (self.as_bytes()[2] as u32) << 16
678            | (self.as_bytes()[3] as u32) << 24;
679
680        let d2 = (self.as_bytes()[4] as u16) | (self.as_bytes()[5] as u16) << 8;
681
682        let d3 = (self.as_bytes()[6] as u16) | (self.as_bytes()[7] as u16) << 8;
683
684        let d4: &[u8; 8] = self.as_bytes()[8..16].try_into().unwrap();
685        (d1, d2, d3, d4)
686    }
687
688    /// Returns a 128bit value containing the value.
689    ///
690    /// The bytes in the UUID will be packed directly into a `u128`.
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// # use uuid::Uuid;
696    /// # fn main() -> Result<(), uuid::Error> {
697    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
698    ///
699    /// assert_eq!(
700    ///     uuid.as_u128(),
701    ///     0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8,
702    /// );
703    /// # Ok(())
704    /// # }
705    /// ```
706    pub const fn as_u128(&self) -> u128 {
707        u128::from_be_bytes(*self.as_bytes())
708    }
709
710    /// Returns a 128bit little-endian value containing the value.
711    ///
712    /// The bytes in the `u128` will be flipped to convert into big-endian
713    /// order. This is based on the endianness of the UUID, rather than the
714    /// target environment so bytes will be flipped on both big and little
715    /// endian machines.
716    ///
717    /// Note that this will produce a different result than
718    /// [`Uuid::to_fields_le`], because the entire UUID is reversed, rather
719    /// than reversing the individual fields in-place.
720    ///
721    /// # Examples
722    ///
723    /// ```
724    /// # use uuid::Uuid;
725    /// # fn main() -> Result<(), uuid::Error> {
726    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
727    ///
728    /// assert_eq!(
729    ///     uuid.to_u128_le(),
730    ///     0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1,
731    /// );
732    /// # Ok(())
733    /// # }
734    /// ```
735    pub const fn to_u128_le(&self) -> u128 {
736        u128::from_le_bytes(*self.as_bytes())
737    }
738
739    /// Returns two 64bit values containing the value.
740    ///
741    /// The bytes in the UUID will be split into two `u64`.
742    /// The first u64 represents the 64 most significant bits,
743    /// the second one represents the 64 least significant.
744    ///
745    /// # Examples
746    ///
747    /// ```
748    /// # use uuid::Uuid;
749    /// # fn main() -> Result<(), uuid::Error> {
750    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
751    /// assert_eq!(
752    ///     uuid.as_u64_pair(),
753    ///     (0xa1a2a3a4b1b2c1c2, 0xd1d2d3d4d5d6d7d8),
754    /// );
755    /// # Ok(())
756    /// # }
757    /// ```
758    pub const fn as_u64_pair(&self) -> (u64, u64) {
759        let value = self.as_u128();
760        ((value >> 64) as u64, value as u64)
761    }
762
763    /// Returns a slice of 16 octets containing the value.
764    ///
765    /// This method borrows the underlying byte value of the UUID.
766    ///
767    /// # Examples
768    ///
769    /// ```
770    /// # use uuid::Uuid;
771    /// let bytes1 = [
772    ///     0xa1, 0xa2, 0xa3, 0xa4,
773    ///     0xb1, 0xb2,
774    ///     0xc1, 0xc2,
775    ///     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
776    /// ];
777    /// let uuid1 = Uuid::from_bytes_ref(&bytes1);
778    ///
779    /// let bytes2 = uuid1.as_bytes();
780    /// let uuid2 = Uuid::from_bytes_ref(bytes2);
781    ///
782    /// assert_eq!(uuid1, uuid2);
783    ///
784    /// assert!(std::ptr::eq(
785    ///     uuid2 as *const Uuid as *const u8,
786    ///     &bytes1 as *const [u8; 16] as *const u8,
787    /// ));
788    /// ```
789    #[inline]
790    pub const fn as_bytes(&self) -> &Bytes {
791        &self.0
792    }
793
794    /// Consumes self and returns the underlying byte value of the UUID.
795    ///
796    /// # Examples
797    ///
798    /// ```
799    /// # use uuid::Uuid;
800    /// let bytes = [
801    ///     0xa1, 0xa2, 0xa3, 0xa4,
802    ///     0xb1, 0xb2,
803    ///     0xc1, 0xc2,
804    ///     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
805    /// ];
806    /// let uuid = Uuid::from_bytes(bytes);
807    /// assert_eq!(bytes, uuid.into_bytes());
808    /// ```
809    #[inline]
810    pub const fn into_bytes(self) -> Bytes {
811        self.0
812    }
813
814    /// Returns the bytes of the UUID in little-endian order.
815    ///
816    /// The bytes will be flipped to convert into little-endian order. This is
817    /// based on the endianness of the UUID, rather than the target environment
818    /// so bytes will be flipped on both big and little endian machines.
819    ///
820    /// # Examples
821    ///
822    /// ```
823    /// use uuid::Uuid;
824    ///
825    /// # fn main() -> Result<(), uuid::Error> {
826    /// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
827    ///
828    /// assert_eq!(
829    ///     uuid.to_bytes_le(),
830    ///     ([
831    ///         0xa4, 0xa3, 0xa2, 0xa1, 0xb2, 0xb1, 0xc2, 0xc1, 0xd1, 0xd2,
832    ///         0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8
833    ///     ])
834    /// );
835    /// # Ok(())
836    /// # }
837    /// ```
838    pub const fn to_bytes_le(&self) -> Bytes {
839        [
840            self.0[3], self.0[2], self.0[1], self.0[0], self.0[5], self.0[4], self.0[7], self.0[6],
841            self.0[8], self.0[9], self.0[10], self.0[11], self.0[12], self.0[13], self.0[14],
842            self.0[15],
843        ]
844    }
845
846    /// Tests if the UUID is nil (all zeros).
847    pub const fn is_nil(&self) -> bool {
848        self.as_u128() == u128::MIN
849    }
850
851    /// Tests if the UUID is max (all ones).
852    pub const fn is_max(&self) -> bool {
853        self.as_u128() == u128::MAX
854    }
855
856    /// A buffer that can be used for `encode_...` calls, that is
857    /// guaranteed to be long enough for any of the format adapters.
858    ///
859    /// # Examples
860    ///
861    /// ```
862    /// # use uuid::Uuid;
863    /// let uuid = Uuid::nil();
864    ///
865    /// assert_eq!(
866    ///     uuid.simple().encode_lower(&mut Uuid::encode_buffer()),
867    ///     "00000000000000000000000000000000"
868    /// );
869    ///
870    /// assert_eq!(
871    ///     uuid.hyphenated()
872    ///         .encode_lower(&mut Uuid::encode_buffer()),
873    ///     "00000000-0000-0000-0000-000000000000"
874    /// );
875    ///
876    /// assert_eq!(
877    ///     uuid.urn().encode_lower(&mut Uuid::encode_buffer()),
878    ///     "urn:uuid:00000000-0000-0000-0000-000000000000"
879    /// );
880    /// ```
881    pub const fn encode_buffer() -> [u8; fmt::Urn::LENGTH] {
882        [0; fmt::Urn::LENGTH]
883    }
884
885    /// If the UUID is the correct version (v1, v6, or v7) this will return
886    /// the timestamp in a version-agnostic [`Timestamp`]. For other versions
887    /// this will return `None`.
888    ///
889    /// # Roundtripping
890    ///
891    /// This method is unlikely to roundtrip a timestamp in a UUID due to the way
892    /// UUIDs encode timestamps. The timestamp returned from this method will be truncated to
893    /// 100ns precision for version 1 and 6 UUIDs, and to millisecond precision for version 7 UUIDs.
894    pub const fn get_timestamp(&self) -> Option<Timestamp> {
895        match self.get_version() {
896            Some(Version::Mac) => {
897                let (ticks, counter) = timestamp::decode_gregorian_timestamp(self);
898
899                Some(Timestamp::from_gregorian(ticks, counter))
900            }
901            Some(Version::SortMac) => {
902                let (ticks, counter) = timestamp::decode_sorted_gregorian_timestamp(self);
903
904                Some(Timestamp::from_gregorian(ticks, counter))
905            }
906            Some(Version::SortRand) => {
907                let millis = timestamp::decode_unix_timestamp_millis(self);
908
909                let seconds = millis / 1000;
910                let nanos = ((millis % 1000) * 1_000_000) as u32;
911
912                Some(Timestamp::from_unix_time(seconds, nanos, 0, 0))
913            }
914            _ => None,
915        }
916    }
917
918    /// If the UUID is the correct version (v1, or v6) this will return the
919    /// node value as a 6-byte array. For other versions this will return `None`.
920    pub const fn get_node_id(&self) -> Option<[u8; 6]> {
921        match self.get_version() {
922            Some(Version::Mac) | Some(Version::SortMac) => {
923                let mut node_id = [0; 6];
924
925                node_id[0] = self.0[10];
926                node_id[1] = self.0[11];
927                node_id[2] = self.0[12];
928                node_id[3] = self.0[13];
929                node_id[4] = self.0[14];
930                node_id[5] = self.0[15];
931
932                Some(node_id)
933            }
934            _ => None,
935        }
936    }
937}
938
939impl Hash for Uuid {
940    fn hash<H: Hasher>(&self, state: &mut H) {
941        state.write(&self.0);
942    }
943}
944
945impl Default for Uuid {
946    #[inline]
947    fn default() -> Self {
948        Uuid::nil()
949    }
950}
951
952impl AsRef<Uuid> for Uuid {
953    #[inline]
954    fn as_ref(&self) -> &Uuid {
955        self
956    }
957}
958
959impl AsRef<[u8]> for Uuid {
960    #[inline]
961    fn as_ref(&self) -> &[u8] {
962        &self.0
963    }
964}
965
966#[cfg(feature = "std")]
967impl From<Uuid> for std::vec::Vec<u8> {
968    fn from(value: Uuid) -> Self {
969        value.0.to_vec()
970    }
971}
972
973#[cfg(feature = "std")]
974impl TryFrom<std::vec::Vec<u8>> for Uuid {
975    type Error = Error;
976
977    fn try_from(value: std::vec::Vec<u8>) -> Result<Self, Self::Error> {
978        Uuid::from_slice(&value)
979    }
980}
981
982#[cfg(feature = "serde")]
983pub mod serde {
984    //! Adapters for alternative `serde` formats.
985    //!
986    //! This module contains adapters you can use with [`#[serde(with)]`](https://serde.rs/field-attrs.html#with)
987    //! to change the way a [`Uuid`](../struct.Uuid.html) is serialized
988    //! and deserialized.
989
990    pub use crate::external::serde_support::{braced, compact, simple, urn};
991}
992
993#[cfg(test)]
994mod tests {
995    use super::*;
996
997    use crate::std::string::{String, ToString};
998
999    #[cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))]
1000    use wasm_bindgen_test::*;
1001
1002    macro_rules! check {
1003        ($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
1004            $buf.clear();
1005            write!($buf, $format, $target).unwrap();
1006            assert!($buf.len() == $len);
1007            assert!($buf.chars().all($cond), "{}", $buf);
1008        };
1009    }
1010
1011    pub const fn new() -> Uuid {
1012        Uuid::from_bytes([
1013            0xF9, 0x16, 0x8C, 0x5E, 0xCE, 0xB2, 0x4F, 0xAA, 0xB6, 0xBF, 0x32, 0x9B, 0xF3, 0x9F,
1014            0xA1, 0xE4,
1015        ])
1016    }
1017
1018    pub const fn new2() -> Uuid {
1019        Uuid::from_bytes([
1020            0xF9, 0x16, 0x8C, 0x5E, 0xCE, 0xB2, 0x4F, 0xAB, 0xB6, 0xBF, 0x32, 0x9B, 0xF3, 0x9F,
1021            0xA1, 0xE4,
1022        ])
1023    }
1024
1025    #[test]
1026    #[cfg_attr(
1027        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1028        wasm_bindgen_test
1029    )]
1030    fn test_uuid_compare() {
1031        let uuid1 = new();
1032        let uuid2 = new2();
1033
1034        assert_eq!(uuid1, uuid1);
1035        assert_eq!(uuid2, uuid2);
1036
1037        assert_ne!(uuid1, uuid2);
1038        assert_ne!(uuid2, uuid1);
1039    }
1040
1041    #[test]
1042    #[cfg_attr(
1043        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1044        wasm_bindgen_test
1045    )]
1046    fn test_uuid_default() {
1047        let default_uuid = Uuid::default();
1048        let nil_uuid = Uuid::nil();
1049
1050        assert_eq!(default_uuid, nil_uuid);
1051    }
1052
1053    #[test]
1054    #[cfg_attr(
1055        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1056        wasm_bindgen_test
1057    )]
1058    fn test_uuid_display() {
1059        use crate::std::fmt::Write;
1060
1061        let uuid = new();
1062        let s = uuid.to_string();
1063        let mut buffer = String::new();
1064
1065        assert_eq!(s, uuid.hyphenated().to_string());
1066
1067        check!(buffer, "{}", uuid, 36, |c| c.is_lowercase()
1068            || c.is_ascii_digit()
1069            || c == '-');
1070    }
1071
1072    #[test]
1073    #[cfg_attr(
1074        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1075        wasm_bindgen_test
1076    )]
1077    fn test_uuid_lowerhex() {
1078        use crate::std::fmt::Write;
1079
1080        let mut buffer = String::new();
1081        let uuid = new();
1082
1083        check!(buffer, "{:x}", uuid, 36, |c| c.is_lowercase()
1084            || c.is_ascii_digit()
1085            || c == '-');
1086    }
1087
1088    // noinspection RsAssertEqual
1089    #[test]
1090    #[cfg_attr(
1091        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1092        wasm_bindgen_test
1093    )]
1094    fn test_uuid_operator_eq() {
1095        let uuid1 = new();
1096        let uuid1_dup = uuid1;
1097        let uuid2 = new2();
1098
1099        assert!(uuid1 == uuid1);
1100        assert!(uuid1 == uuid1_dup);
1101        assert!(uuid1_dup == uuid1);
1102
1103        assert!(uuid1 != uuid2);
1104        assert!(uuid2 != uuid1);
1105        assert!(uuid1_dup != uuid2);
1106        assert!(uuid2 != uuid1_dup);
1107    }
1108
1109    #[test]
1110    #[cfg_attr(
1111        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1112        wasm_bindgen_test
1113    )]
1114    fn test_uuid_to_string() {
1115        use crate::std::fmt::Write;
1116
1117        let uuid = new();
1118        let s = uuid.to_string();
1119        let mut buffer = String::new();
1120
1121        assert_eq!(s.len(), 36);
1122
1123        check!(buffer, "{}", s, 36, |c| c.is_lowercase()
1124            || c.is_ascii_digit()
1125            || c == '-');
1126    }
1127
1128    #[test]
1129    #[cfg_attr(
1130        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1131        wasm_bindgen_test
1132    )]
1133    fn test_non_conforming() {
1134        let from_bytes =
1135            Uuid::from_bytes([4, 54, 67, 12, 43, 2, 2, 76, 32, 50, 87, 5, 1, 33, 43, 87]);
1136
1137        assert_eq!(from_bytes.get_version(), None);
1138    }
1139
1140    #[test]
1141    #[cfg_attr(
1142        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1143        wasm_bindgen_test
1144    )]
1145    fn test_nil() {
1146        let nil = Uuid::nil();
1147        let not_nil = new();
1148
1149        assert!(nil.is_nil());
1150        assert!(!not_nil.is_nil());
1151
1152        assert_eq!(nil.get_version(), Some(Version::Nil));
1153        assert_eq!(not_nil.get_version(), Some(Version::Random));
1154
1155        assert_eq!(
1156            nil,
1157            Builder::from_bytes([0; 16])
1158                .with_version(Version::Nil)
1159                .into_uuid()
1160        );
1161    }
1162
1163    #[test]
1164    #[cfg_attr(
1165        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1166        wasm_bindgen_test
1167    )]
1168    fn test_max() {
1169        let max = Uuid::max();
1170        let not_max = new();
1171
1172        assert!(max.is_max());
1173        assert!(!not_max.is_max());
1174
1175        assert_eq!(max.get_version(), Some(Version::Max));
1176        assert_eq!(not_max.get_version(), Some(Version::Random));
1177
1178        assert_eq!(
1179            max,
1180            Builder::from_bytes([0xff; 16])
1181                .with_version(Version::Max)
1182                .into_uuid()
1183        );
1184    }
1185
1186    #[test]
1187    #[cfg_attr(
1188        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1189        wasm_bindgen_test
1190    )]
1191    fn test_predefined_namespaces() {
1192        assert_eq!(
1193            Uuid::NAMESPACE_DNS.hyphenated().to_string(),
1194            "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
1195        );
1196        assert_eq!(
1197            Uuid::NAMESPACE_URL.hyphenated().to_string(),
1198            "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
1199        );
1200        assert_eq!(
1201            Uuid::NAMESPACE_OID.hyphenated().to_string(),
1202            "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
1203        );
1204        assert_eq!(
1205            Uuid::NAMESPACE_X500.hyphenated().to_string(),
1206            "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
1207        );
1208    }
1209
1210    #[cfg(feature = "v3")]
1211    #[test]
1212    #[cfg_attr(
1213        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1214        wasm_bindgen_test
1215    )]
1216    fn test_get_version_v3() {
1217        let uuid = Uuid::new_v3(&Uuid::NAMESPACE_DNS, "rust-lang.org".as_bytes());
1218
1219        assert_eq!(uuid.get_version().unwrap(), Version::Md5);
1220        assert_eq!(uuid.get_version_num(), 3);
1221    }
1222
1223    #[test]
1224    #[cfg_attr(
1225        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1226        wasm_bindgen_test
1227    )]
1228    fn test_get_timestamp_unsupported_version() {
1229        let uuid = new();
1230
1231        assert_ne!(Version::Mac, uuid.get_version().unwrap());
1232        assert_ne!(Version::SortMac, uuid.get_version().unwrap());
1233        assert_ne!(Version::SortRand, uuid.get_version().unwrap());
1234
1235        assert!(uuid.get_timestamp().is_none());
1236    }
1237
1238    #[test]
1239    #[cfg_attr(
1240        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1241        wasm_bindgen_test
1242    )]
1243    fn test_get_node_id_unsupported_version() {
1244        let uuid = new();
1245
1246        assert_ne!(Version::Mac, uuid.get_version().unwrap());
1247        assert_ne!(Version::SortMac, uuid.get_version().unwrap());
1248
1249        assert!(uuid.get_node_id().is_none());
1250    }
1251
1252    #[test]
1253    #[cfg_attr(
1254        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1255        wasm_bindgen_test
1256    )]
1257    fn test_get_variant() {
1258        let uuid1 = new();
1259        let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
1260        let uuid3 = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
1261        let uuid4 = Uuid::parse_str("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
1262        let uuid5 = Uuid::parse_str("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
1263        let uuid6 = Uuid::parse_str("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();
1264
1265        assert_eq!(uuid1.get_variant(), Variant::RFC4122);
1266        assert_eq!(uuid2.get_variant(), Variant::RFC4122);
1267        assert_eq!(uuid3.get_variant(), Variant::RFC4122);
1268        assert_eq!(uuid4.get_variant(), Variant::Microsoft);
1269        assert_eq!(uuid5.get_variant(), Variant::Microsoft);
1270        assert_eq!(uuid6.get_variant(), Variant::NCS);
1271    }
1272
1273    #[test]
1274    #[cfg_attr(
1275        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1276        wasm_bindgen_test
1277    )]
1278    fn test_to_simple_string() {
1279        let uuid1 = new();
1280        let s = uuid1.simple().to_string();
1281
1282        assert_eq!(s.len(), 32);
1283        assert!(s.chars().all(|c| c.is_ascii_hexdigit()));
1284    }
1285
1286    #[test]
1287    #[cfg_attr(
1288        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1289        wasm_bindgen_test
1290    )]
1291    fn test_hyphenated_string() {
1292        let uuid1 = new();
1293        let s = uuid1.hyphenated().to_string();
1294
1295        assert_eq!(36, s.len());
1296        assert!(s.chars().all(|c| c.is_ascii_hexdigit() || c == '-'));
1297    }
1298
1299    #[test]
1300    #[cfg_attr(
1301        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1302        wasm_bindgen_test
1303    )]
1304    fn test_upper_lower_hex() {
1305        use std::fmt::Write;
1306
1307        let mut buf = String::new();
1308        let u = new();
1309
1310        macro_rules! check {
1311            ($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
1312                $buf.clear();
1313                write!($buf, $format, $target).unwrap();
1314                assert_eq!($len, buf.len());
1315                assert!($buf.chars().all($cond), "{}", $buf);
1316            };
1317        }
1318
1319        check!(buf, "{:x}", u, 36, |c| c.is_lowercase()
1320            || c.is_ascii_digit()
1321            || c == '-');
1322        check!(buf, "{:X}", u, 36, |c| c.is_uppercase()
1323            || c.is_ascii_digit()
1324            || c == '-');
1325        check!(buf, "{:#x}", u, 36, |c| c.is_lowercase()
1326            || c.is_ascii_digit()
1327            || c == '-');
1328        check!(buf, "{:#X}", u, 36, |c| c.is_uppercase()
1329            || c.is_ascii_digit()
1330            || c == '-');
1331
1332        check!(buf, "{:X}", u.hyphenated(), 36, |c| c.is_uppercase()
1333            || c.is_ascii_digit()
1334            || c == '-');
1335        check!(buf, "{:X}", u.simple(), 32, |c| c.is_uppercase()
1336            || c.is_ascii_digit());
1337        check!(buf, "{:#X}", u.hyphenated(), 36, |c| c.is_uppercase()
1338            || c.is_ascii_digit()
1339            || c == '-');
1340        check!(buf, "{:#X}", u.simple(), 32, |c| c.is_uppercase()
1341            || c.is_ascii_digit());
1342
1343        check!(buf, "{:x}", u.hyphenated(), 36, |c| c.is_lowercase()
1344            || c.is_ascii_digit()
1345            || c == '-');
1346        check!(buf, "{:x}", u.simple(), 32, |c| c.is_lowercase()
1347            || c.is_ascii_digit());
1348        check!(buf, "{:#x}", u.hyphenated(), 36, |c| c.is_lowercase()
1349            || c.is_ascii_digit()
1350            || c == '-');
1351        check!(buf, "{:#x}", u.simple(), 32, |c| c.is_lowercase()
1352            || c.is_ascii_digit());
1353    }
1354
1355    #[test]
1356    #[cfg_attr(
1357        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1358        wasm_bindgen_test
1359    )]
1360    fn test_to_urn_string() {
1361        let uuid1 = new();
1362        let ss = uuid1.urn().to_string();
1363        let s = &ss[9..];
1364
1365        assert!(ss.starts_with("urn:uuid:"));
1366        assert_eq!(s.len(), 36);
1367        assert!(s.chars().all(|c| c.is_ascii_hexdigit() || c == '-'));
1368    }
1369
1370    #[test]
1371    #[cfg_attr(
1372        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1373        wasm_bindgen_test
1374    )]
1375    fn test_to_simple_string_matching() {
1376        let uuid1 = new();
1377
1378        let hs = uuid1.hyphenated().to_string();
1379        let ss = uuid1.simple().to_string();
1380
1381        let hsn = hs.chars().filter(|&c| c != '-').collect::<String>();
1382
1383        assert_eq!(hsn, ss);
1384    }
1385
1386    #[test]
1387    #[cfg_attr(
1388        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1389        wasm_bindgen_test
1390    )]
1391    fn test_string_roundtrip() {
1392        let uuid = new();
1393
1394        let hs = uuid.hyphenated().to_string();
1395        let uuid_hs = Uuid::parse_str(&hs).unwrap();
1396        assert_eq!(uuid_hs, uuid);
1397
1398        let ss = uuid.to_string();
1399        let uuid_ss = Uuid::parse_str(&ss).unwrap();
1400        assert_eq!(uuid_ss, uuid);
1401    }
1402
1403    #[test]
1404    #[cfg_attr(
1405        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1406        wasm_bindgen_test
1407    )]
1408    fn test_from_fields() {
1409        let d1: u32 = 0xa1a2a3a4;
1410        let d2: u16 = 0xb1b2;
1411        let d3: u16 = 0xc1c2;
1412        let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1413
1414        let u = Uuid::from_fields(d1, d2, d3, &d4);
1415
1416        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1417        let result = u.simple().to_string();
1418        assert_eq!(result, expected);
1419    }
1420
1421    #[test]
1422    #[cfg_attr(
1423        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1424        wasm_bindgen_test
1425    )]
1426    fn test_from_fields_le() {
1427        let d1: u32 = 0xa4a3a2a1;
1428        let d2: u16 = 0xb2b1;
1429        let d3: u16 = 0xc2c1;
1430        let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1431
1432        let u = Uuid::from_fields_le(d1, d2, d3, &d4);
1433
1434        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1435        let result = u.simple().to_string();
1436        assert_eq!(result, expected);
1437    }
1438
1439    #[test]
1440    #[cfg_attr(
1441        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1442        wasm_bindgen_test
1443    )]
1444    fn test_as_fields() {
1445        let u = new();
1446        let (d1, d2, d3, d4) = u.as_fields();
1447
1448        assert_ne!(d1, 0);
1449        assert_ne!(d2, 0);
1450        assert_ne!(d3, 0);
1451        assert_eq!(d4.len(), 8);
1452        assert!(!d4.iter().all(|&b| b == 0));
1453    }
1454
1455    #[test]
1456    #[cfg_attr(
1457        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1458        wasm_bindgen_test
1459    )]
1460    fn test_fields_roundtrip() {
1461        let d1_in: u32 = 0xa1a2a3a4;
1462        let d2_in: u16 = 0xb1b2;
1463        let d3_in: u16 = 0xc1c2;
1464        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1465
1466        let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in);
1467        let (d1_out, d2_out, d3_out, d4_out) = u.as_fields();
1468
1469        assert_eq!(d1_in, d1_out);
1470        assert_eq!(d2_in, d2_out);
1471        assert_eq!(d3_in, d3_out);
1472        assert_eq!(d4_in, d4_out);
1473    }
1474
1475    #[test]
1476    #[cfg_attr(
1477        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1478        wasm_bindgen_test
1479    )]
1480    fn test_fields_le_roundtrip() {
1481        let d1_in: u32 = 0xa4a3a2a1;
1482        let d2_in: u16 = 0xb2b1;
1483        let d3_in: u16 = 0xc2c1;
1484        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1485
1486        let u = Uuid::from_fields_le(d1_in, d2_in, d3_in, d4_in);
1487        let (d1_out, d2_out, d3_out, d4_out) = u.to_fields_le();
1488
1489        assert_eq!(d1_in, d1_out);
1490        assert_eq!(d2_in, d2_out);
1491        assert_eq!(d3_in, d3_out);
1492        assert_eq!(d4_in, d4_out);
1493    }
1494
1495    #[test]
1496    #[cfg_attr(
1497        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1498        wasm_bindgen_test
1499    )]
1500    fn test_fields_le_are_actually_le() {
1501        let d1_in: u32 = 0xa1a2a3a4;
1502        let d2_in: u16 = 0xb1b2;
1503        let d3_in: u16 = 0xc1c2;
1504        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1505
1506        let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in);
1507        let (d1_out, d2_out, d3_out, d4_out) = u.to_fields_le();
1508
1509        assert_eq!(d1_in, d1_out.swap_bytes());
1510        assert_eq!(d2_in, d2_out.swap_bytes());
1511        assert_eq!(d3_in, d3_out.swap_bytes());
1512        assert_eq!(d4_in, d4_out);
1513    }
1514
1515    #[test]
1516    #[cfg_attr(
1517        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1518        wasm_bindgen_test
1519    )]
1520    fn test_from_u128() {
1521        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1522
1523        let u = Uuid::from_u128(v_in);
1524
1525        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1526        let result = u.simple().to_string();
1527        assert_eq!(result, expected);
1528    }
1529
1530    #[test]
1531    #[cfg_attr(
1532        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1533        wasm_bindgen_test
1534    )]
1535    fn test_from_u128_le() {
1536        let v_in: u128 = 0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1;
1537
1538        let u = Uuid::from_u128_le(v_in);
1539
1540        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1541        let result = u.simple().to_string();
1542        assert_eq!(result, expected);
1543    }
1544
1545    #[test]
1546    #[cfg_attr(
1547        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1548        wasm_bindgen_test
1549    )]
1550    fn test_from_u64_pair() {
1551        let high_in: u64 = 0xa1a2a3a4b1b2c1c2;
1552        let low_in: u64 = 0xd1d2d3d4d5d6d7d8;
1553
1554        let u = Uuid::from_u64_pair(high_in, low_in);
1555
1556        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1557        let result = u.simple().to_string();
1558        assert_eq!(result, expected);
1559    }
1560
1561    #[test]
1562    #[cfg_attr(
1563        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1564        wasm_bindgen_test
1565    )]
1566    fn test_u128_roundtrip() {
1567        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1568
1569        let u = Uuid::from_u128(v_in);
1570        let v_out = u.as_u128();
1571
1572        assert_eq!(v_in, v_out);
1573    }
1574
1575    #[test]
1576    #[cfg_attr(
1577        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1578        wasm_bindgen_test
1579    )]
1580    fn test_u128_le_roundtrip() {
1581        let v_in: u128 = 0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1;
1582
1583        let u = Uuid::from_u128_le(v_in);
1584        let v_out = u.to_u128_le();
1585
1586        assert_eq!(v_in, v_out);
1587    }
1588
1589    #[test]
1590    #[cfg_attr(
1591        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1592        wasm_bindgen_test
1593    )]
1594    fn test_u64_pair_roundtrip() {
1595        let high_in: u64 = 0xa1a2a3a4b1b2c1c2;
1596        let low_in: u64 = 0xd1d2d3d4d5d6d7d8;
1597
1598        let u = Uuid::from_u64_pair(high_in, low_in);
1599        let (high_out, low_out) = u.as_u64_pair();
1600
1601        assert_eq!(high_in, high_out);
1602        assert_eq!(low_in, low_out);
1603    }
1604
1605    #[test]
1606    #[cfg_attr(
1607        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1608        wasm_bindgen_test
1609    )]
1610    fn test_u128_le_is_actually_le() {
1611        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1612
1613        let u = Uuid::from_u128(v_in);
1614        let v_out = u.to_u128_le();
1615
1616        assert_eq!(v_in, v_out.swap_bytes());
1617    }
1618
1619    #[test]
1620    #[cfg_attr(
1621        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1622        wasm_bindgen_test
1623    )]
1624    fn test_from_slice() {
1625        let b = [
1626            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1627            0xd7, 0xd8,
1628        ];
1629
1630        let u = Uuid::from_slice(&b).unwrap();
1631        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1632
1633        assert_eq!(u.simple().to_string(), expected);
1634    }
1635
1636    #[test]
1637    #[cfg_attr(
1638        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1639        wasm_bindgen_test
1640    )]
1641    fn test_from_bytes() {
1642        let b = [
1643            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1644            0xd7, 0xd8,
1645        ];
1646
1647        let u = Uuid::from_bytes(b);
1648        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1649
1650        assert_eq!(u.simple().to_string(), expected);
1651    }
1652
1653    #[test]
1654    #[cfg_attr(
1655        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1656        wasm_bindgen_test
1657    )]
1658    fn test_as_bytes() {
1659        let u = new();
1660        let ub = u.as_bytes();
1661        let ur: &[u8] = u.as_ref();
1662
1663        assert_eq!(ub.len(), 16);
1664        assert_eq!(ur.len(), 16);
1665        assert!(!ub.iter().all(|&b| b == 0));
1666        assert!(!ur.iter().all(|&b| b == 0));
1667    }
1668
1669    #[test]
1670    #[cfg(feature = "std")]
1671    #[cfg_attr(
1672        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1673        wasm_bindgen_test
1674    )]
1675    fn test_convert_vec() {
1676        let u = new();
1677        let ub: &[u8] = u.as_ref();
1678
1679        let v: std::vec::Vec<u8> = u.into();
1680
1681        assert_eq!(&v, ub);
1682
1683        let uv: Uuid = v.try_into().unwrap();
1684
1685        assert_eq!(uv, u);
1686    }
1687
1688    #[test]
1689    #[cfg_attr(
1690        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1691        wasm_bindgen_test
1692    )]
1693    fn test_bytes_roundtrip() {
1694        let b_in: crate::Bytes = [
1695            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1696            0xd7, 0xd8,
1697        ];
1698
1699        let u = Uuid::from_slice(&b_in).unwrap();
1700
1701        let b_out = u.as_bytes();
1702
1703        assert_eq!(&b_in, b_out);
1704    }
1705
1706    #[test]
1707    #[cfg_attr(
1708        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1709        wasm_bindgen_test
1710    )]
1711    fn test_bytes_le_roundtrip() {
1712        let b = [
1713            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1714            0xd7, 0xd8,
1715        ];
1716
1717        let u1 = Uuid::from_bytes(b);
1718
1719        let b_le = u1.to_bytes_le();
1720
1721        let u2 = Uuid::from_bytes_le(b_le);
1722
1723        assert_eq!(u1, u2);
1724    }
1725
1726    #[test]
1727    #[cfg_attr(
1728        all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")),
1729        wasm_bindgen_test
1730    )]
1731    fn test_iterbytes_impl_for_uuid() {
1732        let mut set = std::collections::HashSet::new();
1733        let id1 = new();
1734        let id2 = new2();
1735        set.insert(id1);
1736
1737        assert!(set.contains(&id1));
1738        assert!(!set.contains(&id2));
1739    }
1740}