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.13.2"
42//! features = [
43//!     "v4",                # Lets you generate random UUIDs
44//!     "fast-rng",          # Use a faster (but still sufficiently random) RNG
45//!     "macro-diagnostics", # Enable better diagnostics for compile-time UUIDs
46//! ]
47//! ```
48//!
49//! When you want a UUID, you can generate one:
50//!
51//! ```
52//! # fn main() {
53//! # #[cfg(feature = "v4")]
54//! # {
55//! use uuid::Uuid;
56//!
57//! let id = Uuid::new_v4();
58//! # }
59//! # }
60//! ```
61//!
62//! If you have a UUID value, you can use its string literal form inline:
63//!
64//! ```
65//! use uuid::{uuid, Uuid};
66//!
67//! const ID: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
68//! ```
69//!
70//! # Working with different UUID versions
71//!
72//! This library supports all standardized methods for generating UUIDs through individual Cargo features.
73//!
74//! By default, this crate depends on nothing but the Rust standard library and can parse and format
75//! UUIDs, but cannot generate them. Depending on the kind of UUID you'd like to work with, there
76//! are Cargo features that enable generating them:
77//!
78//! * `v1` - Version 1 UUIDs using a timestamp and monotonic counter.
79//! * `v3` - Version 3 UUIDs based on the MD5 hash of some data.
80//! * `v4` - Version 4 UUIDs with random data.
81//! * `v5` - Version 5 UUIDs based on the SHA1 hash of some data.
82//! * `v6` - Version 6 UUIDs using a timestamp and monotonic counter.
83//! * `v7` - Version 7 UUIDs using a Unix timestamp.
84//! * `v8` - Version 8 UUIDs using user-defined data.
85//!
86//! This library also includes a [`Builder`] type that can be used to help construct UUIDs of any
87//! version without any additional dependencies or features. It's a lower-level API than [`Uuid`]
88//! that can be used when you need control over implicit requirements on things like a source
89//! of randomness.
90//!
91//! ## Which UUID version should I use?
92//!
93//! If you just want to generate unique identifiers then consider version 4 (`v4`) UUIDs. If you want
94//! to use UUIDs as database keys or need to sort them then consider version 7 (`v7`) UUIDs.
95//! Other versions should generally be avoided unless there's an existing need for them.
96//!
97//! Some UUID versions supersede others. Prefer version 6 over version 1 and version 5 over version 3.
98//!
99//! # Other features
100//!
101//! Other crate features can also be useful beyond the version support:
102//!
103//! * `macro-diagnostics` - enhances the diagnostics of `uuid!` macro.
104//! * `serde` - adds the ability to serialize and deserialize a UUID using
105//!   `serde`.
106//! * `borsh` - adds the ability to serialize and deserialize a UUID using
107//!   `borsh`.
108//! * `arbitrary` - adds an `Arbitrary` trait implementation to `Uuid` for
109//!   fuzzing.
110//! * `fast-rng` - uses a faster algorithm for generating random UUIDs when available.
111//!   This feature requires more dependencies to compile, but is just as suitable for
112//!   UUIDs as the default algorithm.
113//! * `rng-rand` - forces `rand` as the backend for randomness.
114//! * `rng-getrandom` - forces `getrandom` as the backend for randomness.
115//! * `bytemuck` - adds a `Pod` trait implementation to `Uuid` for byte manipulation
116//!
117//! # Unstable features
118//!
119//! Some features are unstable. They may be incomplete or depend on other
120//! unstable libraries. These include:
121//!
122//! * `zerocopy` - adds support for zero-copy deserialization using the
123//!   `zerocopy` library.
124//!
125//! Unstable features may break between minor releases.
126//!
127//! To allow unstable features, you'll need to enable the Cargo feature as
128//! normal, but also pass an additional flag through your environment to opt-in
129//! to unstable `uuid` features:
130//!
131//! ```text
132//! RUSTFLAGS="--cfg uuid_unstable"
133//! ```
134//!
135//! # Building for other targets
136//!
137//! ## WebAssembly
138//!
139//! For WebAssembly, enable the `js` feature:
140//!
141//! ```toml
142//! [dependencies.uuid]
143//! version = "1.13.2"
144//! features = [
145//!     "v4",
146//!     "v7",
147//!     "js",
148//! ]
149//! ```
150//!
151//! ## Embedded
152//!
153//! For embedded targets without the standard library, you'll need to
154//! disable default features when building `uuid`:
155//!
156//! ```toml
157//! [dependencies.uuid]
158//! version = "1.13.2"
159//! default-features = false
160//! ```
161//!
162//! Some additional features are supported in no-std environments:
163//!
164//! * `v1`, `v3`, `v5`, `v6`, and `v8`.
165//! * `serde`.
166//!
167//! If you need to use `v4` or `v7` in a no-std environment, you'll need to
168//! produce random bytes yourself and then pass them to [`Builder::from_random_bytes`]
169//! without enabling the `v4` or `v7` features.
170//!
171//! If you're using `getrandom`, you can specify the `rng-getrandom` or `rng-rand`
172//! features of `uuid` and configure `getrandom`'s provider per its docs. `uuid`
173//! may upgrade its version of `getrandom` in minor releases.
174//!
175//! # Examples
176//!
177//! Parse a UUID given in the simple format and print it as a URN:
178//!
179//! ```
180//! # use uuid::Uuid;
181//! # fn main() -> Result<(), uuid::Error> {
182//! let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?;
183//!
184//! println!("{}", my_uuid.urn());
185//! # Ok(())
186//! # }
187//! ```
188//!
189//! Generate a random UUID and print it out in hexadecimal form:
190//!
191//! ```
192//! // Note that this requires the `v4` feature to be enabled.
193//! # use uuid::Uuid;
194//! # fn main() {
195//! # #[cfg(feature = "v4")] {
196//! let my_uuid = Uuid::new_v4();
197//!
198//! println!("{}", my_uuid);
199//! # }
200//! # }
201//! ```
202//!
203//! # References
204//!
205//! * [Wikipedia: Universally Unique Identifier](http://en.wikipedia.org/wiki/Universally_unique_identifier)
206//! * [RFC 9562: Universally Unique IDentifiers (UUID)](https://www.ietf.org/rfc/rfc9562.html).
207//!
208//! [`wasm-bindgen`]: https://crates.io/crates/wasm-bindgen
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.13.2"
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
227mod builder;
228mod error;
229mod non_nil;
230mod parser;
231
232pub mod fmt;
233pub mod timestamp;
234
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, Hash, 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 Default for Uuid {
942    #[inline]
943    fn default() -> Self {
944        Uuid::nil()
945    }
946}
947
948impl AsRef<Uuid> for Uuid {
949    #[inline]
950    fn as_ref(&self) -> &Uuid {
951        self
952    }
953}
954
955impl AsRef<[u8]> for Uuid {
956    #[inline]
957    fn as_ref(&self) -> &[u8] {
958        &self.0
959    }
960}
961
962#[cfg(feature = "std")]
963impl From<Uuid> for std::vec::Vec<u8> {
964    fn from(value: Uuid) -> Self {
965        value.0.to_vec()
966    }
967}
968
969#[cfg(feature = "std")]
970impl std::convert::TryFrom<std::vec::Vec<u8>> for Uuid {
971    type Error = Error;
972
973    fn try_from(value: std::vec::Vec<u8>) -> Result<Self, Self::Error> {
974        Uuid::from_slice(&value)
975    }
976}
977
978#[cfg(feature = "serde")]
979pub mod serde {
980    //! Adapters for alternative `serde` formats.
981    //!
982    //! This module contains adapters you can use with [`#[serde(with)]`](https://serde.rs/field-attrs.html#with)
983    //! to change the way a [`Uuid`](../struct.Uuid.html) is serialized
984    //! and deserialized.
985
986    pub use crate::external::serde_support::{braced, compact, simple, urn};
987}
988
989#[cfg(test)]
990mod tests {
991    use super::*;
992
993    use crate::std::string::{String, ToString};
994
995    #[cfg(all(
996        target_arch = "wasm32",
997        target_vendor = "unknown",
998        target_os = "unknown"
999    ))]
1000    use wasm_bindgen_test::*;
1001
1002    macro_rules! check {
1003        ($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
1004            $buf.clear();
1005            write!($buf, $format, $target).unwrap();
1006            assert!($buf.len() == $len);
1007            assert!($buf.chars().all($cond), "{}", $buf);
1008        };
1009    }
1010
1011    pub const fn new() -> Uuid {
1012        Uuid::from_bytes([
1013            0xF9, 0x16, 0x8C, 0x5E, 0xCE, 0xB2, 0x4F, 0xAA, 0xB6, 0xBF, 0x32, 0x9B, 0xF3, 0x9F,
1014            0xA1, 0xE4,
1015        ])
1016    }
1017
1018    pub const fn new2() -> Uuid {
1019        Uuid::from_bytes([
1020            0xF9, 0x16, 0x8C, 0x5E, 0xCE, 0xB2, 0x4F, 0xAB, 0xB6, 0xBF, 0x32, 0x9B, 0xF3, 0x9F,
1021            0xA1, 0xE4,
1022        ])
1023    }
1024
1025    #[test]
1026    #[cfg_attr(
1027        all(
1028            target_arch = "wasm32",
1029            target_vendor = "unknown",
1030            target_os = "unknown"
1031        ),
1032        wasm_bindgen_test
1033    )]
1034    fn test_uuid_compare() {
1035        let uuid1 = new();
1036        let uuid2 = new2();
1037
1038        assert_eq!(uuid1, uuid1);
1039        assert_eq!(uuid2, uuid2);
1040
1041        assert_ne!(uuid1, uuid2);
1042        assert_ne!(uuid2, uuid1);
1043    }
1044
1045    #[test]
1046    #[cfg_attr(
1047        all(
1048            target_arch = "wasm32",
1049            target_vendor = "unknown",
1050            target_os = "unknown"
1051        ),
1052        wasm_bindgen_test
1053    )]
1054    fn test_uuid_default() {
1055        let default_uuid = Uuid::default();
1056        let nil_uuid = Uuid::nil();
1057
1058        assert_eq!(default_uuid, nil_uuid);
1059    }
1060
1061    #[test]
1062    #[cfg_attr(
1063        all(
1064            target_arch = "wasm32",
1065            target_vendor = "unknown",
1066            target_os = "unknown"
1067        ),
1068        wasm_bindgen_test
1069    )]
1070    fn test_uuid_display() {
1071        use crate::std::fmt::Write;
1072
1073        let uuid = new();
1074        let s = uuid.to_string();
1075        let mut buffer = String::new();
1076
1077        assert_eq!(s, uuid.hyphenated().to_string());
1078
1079        check!(buffer, "{}", uuid, 36, |c| c.is_lowercase()
1080            || c.is_digit(10)
1081            || c == '-');
1082    }
1083
1084    #[test]
1085    #[cfg_attr(
1086        all(
1087            target_arch = "wasm32",
1088            target_vendor = "unknown",
1089            target_os = "unknown"
1090        ),
1091        wasm_bindgen_test
1092    )]
1093    fn test_uuid_lowerhex() {
1094        use crate::std::fmt::Write;
1095
1096        let mut buffer = String::new();
1097        let uuid = new();
1098
1099        check!(buffer, "{:x}", uuid, 36, |c| c.is_lowercase()
1100            || c.is_digit(10)
1101            || c == '-');
1102    }
1103
1104    // noinspection RsAssertEqual
1105    #[test]
1106    #[cfg_attr(
1107        all(
1108            target_arch = "wasm32",
1109            target_vendor = "unknown",
1110            target_os = "unknown"
1111        ),
1112        wasm_bindgen_test
1113    )]
1114    fn test_uuid_operator_eq() {
1115        let uuid1 = new();
1116        let uuid1_dup = uuid1.clone();
1117        let uuid2 = new2();
1118
1119        assert!(uuid1 == uuid1);
1120        assert!(uuid1 == uuid1_dup);
1121        assert!(uuid1_dup == uuid1);
1122
1123        assert!(uuid1 != uuid2);
1124        assert!(uuid2 != uuid1);
1125        assert!(uuid1_dup != uuid2);
1126        assert!(uuid2 != uuid1_dup);
1127    }
1128
1129    #[test]
1130    #[cfg_attr(
1131        all(
1132            target_arch = "wasm32",
1133            target_vendor = "unknown",
1134            target_os = "unknown"
1135        ),
1136        wasm_bindgen_test
1137    )]
1138    fn test_uuid_to_string() {
1139        use crate::std::fmt::Write;
1140
1141        let uuid = new();
1142        let s = uuid.to_string();
1143        let mut buffer = String::new();
1144
1145        assert_eq!(s.len(), 36);
1146
1147        check!(buffer, "{}", s, 36, |c| c.is_lowercase()
1148            || c.is_digit(10)
1149            || c == '-');
1150    }
1151
1152    #[test]
1153    #[cfg_attr(
1154        all(
1155            target_arch = "wasm32",
1156            target_vendor = "unknown",
1157            target_os = "unknown"
1158        ),
1159        wasm_bindgen_test
1160    )]
1161    fn test_non_conforming() {
1162        let from_bytes =
1163            Uuid::from_bytes([4, 54, 67, 12, 43, 2, 2, 76, 32, 50, 87, 5, 1, 33, 43, 87]);
1164
1165        assert_eq!(from_bytes.get_version(), None);
1166    }
1167
1168    #[test]
1169    #[cfg_attr(
1170        all(
1171            target_arch = "wasm32",
1172            target_vendor = "unknown",
1173            target_os = "unknown"
1174        ),
1175        wasm_bindgen_test
1176    )]
1177    fn test_nil() {
1178        let nil = Uuid::nil();
1179        let not_nil = new();
1180
1181        assert!(nil.is_nil());
1182        assert!(!not_nil.is_nil());
1183
1184        assert_eq!(nil.get_version(), Some(Version::Nil));
1185        assert_eq!(not_nil.get_version(), Some(Version::Random));
1186
1187        assert_eq!(
1188            nil,
1189            Builder::from_bytes([0; 16])
1190                .with_version(Version::Nil)
1191                .into_uuid()
1192        );
1193    }
1194
1195    #[test]
1196    #[cfg_attr(
1197        all(
1198            target_arch = "wasm32",
1199            target_vendor = "unknown",
1200            target_os = "unknown"
1201        ),
1202        wasm_bindgen_test
1203    )]
1204    fn test_max() {
1205        let max = Uuid::max();
1206        let not_max = new();
1207
1208        assert!(max.is_max());
1209        assert!(!not_max.is_max());
1210
1211        assert_eq!(max.get_version(), Some(Version::Max));
1212        assert_eq!(not_max.get_version(), Some(Version::Random));
1213
1214        assert_eq!(
1215            max,
1216            Builder::from_bytes([0xff; 16])
1217                .with_version(Version::Max)
1218                .into_uuid()
1219        );
1220    }
1221
1222    #[test]
1223    #[cfg_attr(
1224        all(
1225            target_arch = "wasm32",
1226            target_vendor = "unknown",
1227            target_os = "unknown"
1228        ),
1229        wasm_bindgen_test
1230    )]
1231    fn test_predefined_namespaces() {
1232        assert_eq!(
1233            Uuid::NAMESPACE_DNS.hyphenated().to_string(),
1234            "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
1235        );
1236        assert_eq!(
1237            Uuid::NAMESPACE_URL.hyphenated().to_string(),
1238            "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
1239        );
1240        assert_eq!(
1241            Uuid::NAMESPACE_OID.hyphenated().to_string(),
1242            "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
1243        );
1244        assert_eq!(
1245            Uuid::NAMESPACE_X500.hyphenated().to_string(),
1246            "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
1247        );
1248    }
1249
1250    #[cfg(feature = "v3")]
1251    #[test]
1252    #[cfg_attr(
1253        all(
1254            target_arch = "wasm32",
1255            target_vendor = "unknown",
1256            target_os = "unknown"
1257        ),
1258        wasm_bindgen_test
1259    )]
1260    fn test_get_version_v3() {
1261        let uuid = Uuid::new_v3(&Uuid::NAMESPACE_DNS, "rust-lang.org".as_bytes());
1262
1263        assert_eq!(uuid.get_version().unwrap(), Version::Md5);
1264        assert_eq!(uuid.get_version_num(), 3);
1265    }
1266
1267    #[test]
1268    #[cfg_attr(
1269        all(
1270            target_arch = "wasm32",
1271            target_vendor = "unknown",
1272            target_os = "unknown"
1273        ),
1274        wasm_bindgen_test
1275    )]
1276    fn test_get_timestamp_unsupported_version() {
1277        let uuid = new();
1278
1279        assert_ne!(Version::Mac, uuid.get_version().unwrap());
1280        assert_ne!(Version::SortMac, uuid.get_version().unwrap());
1281        assert_ne!(Version::SortRand, uuid.get_version().unwrap());
1282
1283        assert!(uuid.get_timestamp().is_none());
1284    }
1285
1286    #[test]
1287    #[cfg_attr(
1288        all(
1289            target_arch = "wasm32",
1290            target_vendor = "unknown",
1291            target_os = "unknown"
1292        ),
1293        wasm_bindgen_test
1294    )]
1295    fn test_get_node_id_unsupported_version() {
1296        let uuid = new();
1297
1298        assert_ne!(Version::Mac, uuid.get_version().unwrap());
1299        assert_ne!(Version::SortMac, uuid.get_version().unwrap());
1300
1301        assert!(uuid.get_node_id().is_none());
1302    }
1303
1304    #[test]
1305    #[cfg_attr(
1306        all(
1307            target_arch = "wasm32",
1308            target_vendor = "unknown",
1309            target_os = "unknown"
1310        ),
1311        wasm_bindgen_test
1312    )]
1313    fn test_get_variant() {
1314        let uuid1 = new();
1315        let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
1316        let uuid3 = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
1317        let uuid4 = Uuid::parse_str("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
1318        let uuid5 = Uuid::parse_str("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
1319        let uuid6 = Uuid::parse_str("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();
1320
1321        assert_eq!(uuid1.get_variant(), Variant::RFC4122);
1322        assert_eq!(uuid2.get_variant(), Variant::RFC4122);
1323        assert_eq!(uuid3.get_variant(), Variant::RFC4122);
1324        assert_eq!(uuid4.get_variant(), Variant::Microsoft);
1325        assert_eq!(uuid5.get_variant(), Variant::Microsoft);
1326        assert_eq!(uuid6.get_variant(), Variant::NCS);
1327    }
1328
1329    #[test]
1330    #[cfg_attr(
1331        all(
1332            target_arch = "wasm32",
1333            target_vendor = "unknown",
1334            target_os = "unknown"
1335        ),
1336        wasm_bindgen_test
1337    )]
1338    fn test_to_simple_string() {
1339        let uuid1 = new();
1340        let s = uuid1.simple().to_string();
1341
1342        assert_eq!(s.len(), 32);
1343        assert!(s.chars().all(|c| c.is_digit(16)));
1344    }
1345
1346    #[test]
1347    #[cfg_attr(
1348        all(
1349            target_arch = "wasm32",
1350            target_vendor = "unknown",
1351            target_os = "unknown"
1352        ),
1353        wasm_bindgen_test
1354    )]
1355    fn test_hyphenated_string() {
1356        let uuid1 = new();
1357        let s = uuid1.hyphenated().to_string();
1358
1359        assert_eq!(36, s.len());
1360        assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
1361    }
1362
1363    #[test]
1364    #[cfg_attr(
1365        all(
1366            target_arch = "wasm32",
1367            target_vendor = "unknown",
1368            target_os = "unknown"
1369        ),
1370        wasm_bindgen_test
1371    )]
1372    fn test_upper_lower_hex() {
1373        use std::fmt::Write;
1374
1375        let mut buf = String::new();
1376        let u = new();
1377
1378        macro_rules! check {
1379            ($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
1380                $buf.clear();
1381                write!($buf, $format, $target).unwrap();
1382                assert_eq!($len, buf.len());
1383                assert!($buf.chars().all($cond), "{}", $buf);
1384            };
1385        }
1386
1387        check!(buf, "{:x}", u, 36, |c| c.is_lowercase()
1388            || c.is_digit(10)
1389            || c == '-');
1390        check!(buf, "{:X}", u, 36, |c| c.is_uppercase()
1391            || c.is_digit(10)
1392            || c == '-');
1393        check!(buf, "{:#x}", u, 36, |c| c.is_lowercase()
1394            || c.is_digit(10)
1395            || c == '-');
1396        check!(buf, "{:#X}", u, 36, |c| c.is_uppercase()
1397            || c.is_digit(10)
1398            || c == '-');
1399
1400        check!(buf, "{:X}", u.hyphenated(), 36, |c| c.is_uppercase()
1401            || c.is_digit(10)
1402            || c == '-');
1403        check!(buf, "{:X}", u.simple(), 32, |c| c.is_uppercase()
1404            || c.is_digit(10));
1405        check!(buf, "{:#X}", u.hyphenated(), 36, |c| c.is_uppercase()
1406            || c.is_digit(10)
1407            || c == '-');
1408        check!(buf, "{:#X}", u.simple(), 32, |c| c.is_uppercase()
1409            || c.is_digit(10));
1410
1411        check!(buf, "{:x}", u.hyphenated(), 36, |c| c.is_lowercase()
1412            || c.is_digit(10)
1413            || c == '-');
1414        check!(buf, "{:x}", u.simple(), 32, |c| c.is_lowercase()
1415            || c.is_digit(10));
1416        check!(buf, "{:#x}", u.hyphenated(), 36, |c| c.is_lowercase()
1417            || c.is_digit(10)
1418            || c == '-');
1419        check!(buf, "{:#x}", u.simple(), 32, |c| c.is_lowercase()
1420            || c.is_digit(10));
1421    }
1422
1423    #[test]
1424    #[cfg_attr(
1425        all(
1426            target_arch = "wasm32",
1427            target_vendor = "unknown",
1428            target_os = "unknown"
1429        ),
1430        wasm_bindgen_test
1431    )]
1432    fn test_to_urn_string() {
1433        let uuid1 = new();
1434        let ss = uuid1.urn().to_string();
1435        let s = &ss[9..];
1436
1437        assert!(ss.starts_with("urn:uuid:"));
1438        assert_eq!(s.len(), 36);
1439        assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
1440    }
1441
1442    #[test]
1443    #[cfg_attr(
1444        all(
1445            target_arch = "wasm32",
1446            target_vendor = "unknown",
1447            target_os = "unknown"
1448        ),
1449        wasm_bindgen_test
1450    )]
1451    fn test_to_simple_string_matching() {
1452        let uuid1 = new();
1453
1454        let hs = uuid1.hyphenated().to_string();
1455        let ss = uuid1.simple().to_string();
1456
1457        let hsn = hs.chars().filter(|&c| c != '-').collect::<String>();
1458
1459        assert_eq!(hsn, ss);
1460    }
1461
1462    #[test]
1463    #[cfg_attr(
1464        all(
1465            target_arch = "wasm32",
1466            target_vendor = "unknown",
1467            target_os = "unknown"
1468        ),
1469        wasm_bindgen_test
1470    )]
1471    fn test_string_roundtrip() {
1472        let uuid = new();
1473
1474        let hs = uuid.hyphenated().to_string();
1475        let uuid_hs = Uuid::parse_str(&hs).unwrap();
1476        assert_eq!(uuid_hs, uuid);
1477
1478        let ss = uuid.to_string();
1479        let uuid_ss = Uuid::parse_str(&ss).unwrap();
1480        assert_eq!(uuid_ss, uuid);
1481    }
1482
1483    #[test]
1484    #[cfg_attr(
1485        all(
1486            target_arch = "wasm32",
1487            target_vendor = "unknown",
1488            target_os = "unknown"
1489        ),
1490        wasm_bindgen_test
1491    )]
1492    fn test_from_fields() {
1493        let d1: u32 = 0xa1a2a3a4;
1494        let d2: u16 = 0xb1b2;
1495        let d3: u16 = 0xc1c2;
1496        let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1497
1498        let u = Uuid::from_fields(d1, d2, d3, &d4);
1499
1500        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1501        let result = u.simple().to_string();
1502        assert_eq!(result, expected);
1503    }
1504
1505    #[test]
1506    #[cfg_attr(
1507        all(
1508            target_arch = "wasm32",
1509            target_vendor = "unknown",
1510            target_os = "unknown"
1511        ),
1512        wasm_bindgen_test
1513    )]
1514    fn test_from_fields_le() {
1515        let d1: u32 = 0xa4a3a2a1;
1516        let d2: u16 = 0xb2b1;
1517        let d3: u16 = 0xc2c1;
1518        let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1519
1520        let u = Uuid::from_fields_le(d1, d2, d3, &d4);
1521
1522        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1523        let result = u.simple().to_string();
1524        assert_eq!(result, expected);
1525    }
1526
1527    #[test]
1528    #[cfg_attr(
1529        all(
1530            target_arch = "wasm32",
1531            target_vendor = "unknown",
1532            target_os = "unknown"
1533        ),
1534        wasm_bindgen_test
1535    )]
1536    fn test_as_fields() {
1537        let u = new();
1538        let (d1, d2, d3, d4) = u.as_fields();
1539
1540        assert_ne!(d1, 0);
1541        assert_ne!(d2, 0);
1542        assert_ne!(d3, 0);
1543        assert_eq!(d4.len(), 8);
1544        assert!(!d4.iter().all(|&b| b == 0));
1545    }
1546
1547    #[test]
1548    #[cfg_attr(
1549        all(
1550            target_arch = "wasm32",
1551            target_vendor = "unknown",
1552            target_os = "unknown"
1553        ),
1554        wasm_bindgen_test
1555    )]
1556    fn test_fields_roundtrip() {
1557        let d1_in: u32 = 0xa1a2a3a4;
1558        let d2_in: u16 = 0xb1b2;
1559        let d3_in: u16 = 0xc1c2;
1560        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1561
1562        let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in);
1563        let (d1_out, d2_out, d3_out, d4_out) = u.as_fields();
1564
1565        assert_eq!(d1_in, d1_out);
1566        assert_eq!(d2_in, d2_out);
1567        assert_eq!(d3_in, d3_out);
1568        assert_eq!(d4_in, d4_out);
1569    }
1570
1571    #[test]
1572    #[cfg_attr(
1573        all(
1574            target_arch = "wasm32",
1575            target_vendor = "unknown",
1576            target_os = "unknown"
1577        ),
1578        wasm_bindgen_test
1579    )]
1580    fn test_fields_le_roundtrip() {
1581        let d1_in: u32 = 0xa4a3a2a1;
1582        let d2_in: u16 = 0xb2b1;
1583        let d3_in: u16 = 0xc2c1;
1584        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1585
1586        let u = Uuid::from_fields_le(d1_in, d2_in, d3_in, d4_in);
1587        let (d1_out, d2_out, d3_out, d4_out) = u.to_fields_le();
1588
1589        assert_eq!(d1_in, d1_out);
1590        assert_eq!(d2_in, d2_out);
1591        assert_eq!(d3_in, d3_out);
1592        assert_eq!(d4_in, d4_out);
1593    }
1594
1595    #[test]
1596    #[cfg_attr(
1597        all(
1598            target_arch = "wasm32",
1599            target_vendor = "unknown",
1600            target_os = "unknown"
1601        ),
1602        wasm_bindgen_test
1603    )]
1604    fn test_fields_le_are_actually_le() {
1605        let d1_in: u32 = 0xa1a2a3a4;
1606        let d2_in: u16 = 0xb1b2;
1607        let d3_in: u16 = 0xc1c2;
1608        let d4_in = &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];
1609
1610        let u = Uuid::from_fields(d1_in, d2_in, d3_in, d4_in);
1611        let (d1_out, d2_out, d3_out, d4_out) = u.to_fields_le();
1612
1613        assert_eq!(d1_in, d1_out.swap_bytes());
1614        assert_eq!(d2_in, d2_out.swap_bytes());
1615        assert_eq!(d3_in, d3_out.swap_bytes());
1616        assert_eq!(d4_in, d4_out);
1617    }
1618
1619    #[test]
1620    #[cfg_attr(
1621        all(
1622            target_arch = "wasm32",
1623            target_vendor = "unknown",
1624            target_os = "unknown"
1625        ),
1626        wasm_bindgen_test
1627    )]
1628    fn test_from_u128() {
1629        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1630
1631        let u = Uuid::from_u128(v_in);
1632
1633        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1634        let result = u.simple().to_string();
1635        assert_eq!(result, expected);
1636    }
1637
1638    #[test]
1639    #[cfg_attr(
1640        all(
1641            target_arch = "wasm32",
1642            target_vendor = "unknown",
1643            target_os = "unknown"
1644        ),
1645        wasm_bindgen_test
1646    )]
1647    fn test_from_u128_le() {
1648        let v_in: u128 = 0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1;
1649
1650        let u = Uuid::from_u128_le(v_in);
1651
1652        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1653        let result = u.simple().to_string();
1654        assert_eq!(result, expected);
1655    }
1656
1657    #[test]
1658    #[cfg_attr(
1659        all(
1660            target_arch = "wasm32",
1661            target_vendor = "unknown",
1662            target_os = "unknown"
1663        ),
1664        wasm_bindgen_test
1665    )]
1666    fn test_from_u64_pair() {
1667        let high_in: u64 = 0xa1a2a3a4b1b2c1c2;
1668        let low_in: u64 = 0xd1d2d3d4d5d6d7d8;
1669
1670        let u = Uuid::from_u64_pair(high_in, low_in);
1671
1672        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1673        let result = u.simple().to_string();
1674        assert_eq!(result, expected);
1675    }
1676
1677    #[test]
1678    #[cfg_attr(
1679        all(
1680            target_arch = "wasm32",
1681            target_vendor = "unknown",
1682            target_os = "unknown"
1683        ),
1684        wasm_bindgen_test
1685    )]
1686    fn test_u128_roundtrip() {
1687        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1688
1689        let u = Uuid::from_u128(v_in);
1690        let v_out = u.as_u128();
1691
1692        assert_eq!(v_in, v_out);
1693    }
1694
1695    #[test]
1696    #[cfg_attr(
1697        all(
1698            target_arch = "wasm32",
1699            target_vendor = "unknown",
1700            target_os = "unknown"
1701        ),
1702        wasm_bindgen_test
1703    )]
1704    fn test_u128_le_roundtrip() {
1705        let v_in: u128 = 0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1;
1706
1707        let u = Uuid::from_u128_le(v_in);
1708        let v_out = u.to_u128_le();
1709
1710        assert_eq!(v_in, v_out);
1711    }
1712
1713    #[test]
1714    #[cfg_attr(
1715        all(
1716            target_arch = "wasm32",
1717            target_vendor = "unknown",
1718            target_os = "unknown"
1719        ),
1720        wasm_bindgen_test
1721    )]
1722    fn test_u64_pair_roundtrip() {
1723        let high_in: u64 = 0xa1a2a3a4b1b2c1c2;
1724        let low_in: u64 = 0xd1d2d3d4d5d6d7d8;
1725
1726        let u = Uuid::from_u64_pair(high_in, low_in);
1727        let (high_out, low_out) = u.as_u64_pair();
1728
1729        assert_eq!(high_in, high_out);
1730        assert_eq!(low_in, low_out);
1731    }
1732
1733    #[test]
1734    #[cfg_attr(
1735        all(
1736            target_arch = "wasm32",
1737            target_vendor = "unknown",
1738            target_os = "unknown"
1739        ),
1740        wasm_bindgen_test
1741    )]
1742    fn test_u128_le_is_actually_le() {
1743        let v_in: u128 = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8;
1744
1745        let u = Uuid::from_u128(v_in);
1746        let v_out = u.to_u128_le();
1747
1748        assert_eq!(v_in, v_out.swap_bytes());
1749    }
1750
1751    #[test]
1752    #[cfg_attr(
1753        all(
1754            target_arch = "wasm32",
1755            target_vendor = "unknown",
1756            target_os = "unknown"
1757        ),
1758        wasm_bindgen_test
1759    )]
1760    fn test_from_slice() {
1761        let b = [
1762            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1763            0xd7, 0xd8,
1764        ];
1765
1766        let u = Uuid::from_slice(&b).unwrap();
1767        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1768
1769        assert_eq!(u.simple().to_string(), expected);
1770    }
1771
1772    #[test]
1773    #[cfg_attr(
1774        all(
1775            target_arch = "wasm32",
1776            target_vendor = "unknown",
1777            target_os = "unknown"
1778        ),
1779        wasm_bindgen_test
1780    )]
1781    fn test_from_bytes() {
1782        let b = [
1783            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1784            0xd7, 0xd8,
1785        ];
1786
1787        let u = Uuid::from_bytes(b);
1788        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
1789
1790        assert_eq!(u.simple().to_string(), expected);
1791    }
1792
1793    #[test]
1794    #[cfg_attr(
1795        all(
1796            target_arch = "wasm32",
1797            target_vendor = "unknown",
1798            target_os = "unknown"
1799        ),
1800        wasm_bindgen_test
1801    )]
1802    fn test_as_bytes() {
1803        let u = new();
1804        let ub = u.as_bytes();
1805        let ur: &[u8] = u.as_ref();
1806
1807        assert_eq!(ub.len(), 16);
1808        assert_eq!(ur.len(), 16);
1809        assert!(!ub.iter().all(|&b| b == 0));
1810        assert!(!ur.iter().all(|&b| b == 0));
1811    }
1812
1813    #[test]
1814    #[cfg(feature = "std")]
1815    #[cfg_attr(
1816        all(
1817            target_arch = "wasm32",
1818            target_vendor = "unknown",
1819            target_os = "unknown"
1820        ),
1821        wasm_bindgen_test
1822    )]
1823    fn test_convert_vec() {
1824        use crate::std::{convert::TryInto, vec::Vec};
1825
1826        let u = new();
1827        let ub: &[u8] = u.as_ref();
1828
1829        let v: Vec<u8> = u.into();
1830
1831        assert_eq!(&v, ub);
1832
1833        let uv: Uuid = v.try_into().unwrap();
1834
1835        assert_eq!(uv, u);
1836    }
1837
1838    #[test]
1839    #[cfg_attr(
1840        all(
1841            target_arch = "wasm32",
1842            target_vendor = "unknown",
1843            target_os = "unknown"
1844        ),
1845        wasm_bindgen_test
1846    )]
1847    fn test_bytes_roundtrip() {
1848        let b_in: crate::Bytes = [
1849            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1850            0xd7, 0xd8,
1851        ];
1852
1853        let u = Uuid::from_slice(&b_in).unwrap();
1854
1855        let b_out = u.as_bytes();
1856
1857        assert_eq!(&b_in, b_out);
1858    }
1859
1860    #[test]
1861    #[cfg_attr(
1862        all(
1863            target_arch = "wasm32",
1864            target_vendor = "unknown",
1865            target_os = "unknown"
1866        ),
1867        wasm_bindgen_test
1868    )]
1869    fn test_bytes_le_roundtrip() {
1870        let b = [
1871            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
1872            0xd7, 0xd8,
1873        ];
1874
1875        let u1 = Uuid::from_bytes(b);
1876
1877        let b_le = u1.to_bytes_le();
1878
1879        let u2 = Uuid::from_bytes_le(b_le);
1880
1881        assert_eq!(u1, u2);
1882    }
1883
1884    #[test]
1885    #[cfg_attr(
1886        all(
1887            target_arch = "wasm32",
1888            target_vendor = "unknown",
1889            target_os = "unknown"
1890        ),
1891        wasm_bindgen_test
1892    )]
1893    fn test_iterbytes_impl_for_uuid() {
1894        let mut set = std::collections::HashSet::new();
1895        let id1 = new();
1896        let id2 = new2();
1897        set.insert(id1.clone());
1898
1899        assert!(set.contains(&id1));
1900        assert!(!set.contains(&id2));
1901    }
1902}