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