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