Skip to main content

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