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