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