Coverage Report

Created: 2026-03-31 06:24

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