Skip to main content

Uuid

Struct Uuid 

Source
pub struct Uuid(/* private fields */);
Expand description

A 128-bit UUID (RFC 9562).

Implementations§

Source§

impl Uuid

Source

pub fn new_v4() -> Uuid

Available on crate feature std only.

Generate a new version 4 (random) UUID.

§Panics

Panics if the thread-local random number generator cannot be seeded from the operating system’s entropy source. The generator is seeded once per thread and reused afterwards, so this can only happen on the first generation on a thread (or after seeding fails).

§Examples
use uuid::{Uuid, Version};

let uuid = Uuid::new_v4();
assert_eq!(uuid.version(), Version::V4);
Source

pub fn new_v7() -> Uuid

Available on crate feature std only.

Generate a new version 7 UUID with a 32-bit monotonic counter.

The 48-bit timestamp is milliseconds since the Unix epoch. A 32-bit monotonic counter occupies rand_a (12 bits) and the most-significant 20 bits of rand_b; the counter is placed immediately after the timestamp so that values sort lexicographically by creation order (RFC 9562 §6.2, Method 1).

The counter is seeded with 31 random bits each time the logical timestamp advances and incremented on repeated calls within the same millisecond, so a single thread can generate at least 2³¹ UUIDs per millisecond without repeating a value. (The most-significant bit is reserved as a rollover guard, as suggested by RFC 9562.)

§Clock rollback and counter overflow

The timestamp used is a logical clock that never moves backwards. If the system clock is read as being behind the last used timestamp, the last timestamp is kept and the counter is advanced, preserving strict monotonicity. When the counter is exhausted (fewer than 2³¹ UUIDs later) the logical timestamp is advanced by one millisecond and the counter is re-seeded; generation never blocks or spins.

Monotonicity only holds within a single thread: two threads generating UUIDs concurrently may return values out of order relative to each other.

The 128-bit layout follows RFC 9562:

bytes 0..6   unix_ts_ms (48 bits, big-endian)
byte  6      version (4 bits) | counter[31:28] (4 bits)
byte  7      counter[27:20] (8 bits)
byte  8      variant (2 bits) | counter[19:14] (6 bits)
byte  9      counter[13:6] (8 bits)
byte  10     counter[5:0] (6 bits) | random (2 bits)
bytes 11..16 random (40 bits)

The counter sits immediately after the timestamp/version/variant fields and above all random bits, so the 128-bit value sorts by creation order.

§Panics

Panics if the system clock is before the Unix epoch, or if the thread-local random number generator cannot be seeded from the operating system’s entropy source.

§Examples
use uuid::{Uuid, Version};

let uuid = Uuid::new_v7();
assert_eq!(uuid.version(), Version::V7);
Source§

impl Uuid

Source

pub fn parse(input: impl AsRef<[u8]>) -> Result<Uuid, Error>

Parse a UUID from its canonical 8-4-4-4-12 hexadecimal string form.

Accepts both lowercase and uppercase hex characters.

§Errors

Returns Error::InvalidUuid if the input is not exactly 36 bytes, contains misplaced hyphens, or has non-hexadecimal bytes.

§Examples
use uuid::Uuid;

let uuid = Uuid::parse("f47ac10b-58cc-4372-a567-0e02b2c3d479").unwrap();
assert_eq!(uuid.to_string(), "f47ac10b-58cc-4372-a567-0e02b2c3d479");
Source

pub fn to_heapless_string(&self) -> String<36>

Encode this UUID into its canonical 8-4-4-4-12 lowercase hexadecimal form without allocating.

This is a zero-allocation alternative to Uuid::to_string: the text is written into a fixed-capacity [heapless::String] with a capacity of 36 bytes, which is exactly the length of the canonical form, so it never spills and never touches the heap. Unlike a String it works in no_std environments.

§Examples
use uuid::Uuid;

let uuid = Uuid::parse("f47ac10b-58cc-4372-a567-0e02b2c3d479").unwrap();
let text = uuid.to_heapless_string();
assert_eq!(text.as_str(), "f47ac10b-58cc-4372-a567-0e02b2c3d479");
assert_eq!(text.to_string(), uuid.to_string());
Source

pub const fn from_bytes(bytes: [u8; 16]) -> Uuid

Create a UUID from a 16-byte array.

§Examples
use uuid::Uuid;

let uuid = Uuid::from_bytes([0; 16]);
assert_eq!(uuid, Uuid::nil());
Source

pub fn from_slice(bytes: &[u8]) -> Result<Uuid, Error>

Create a UUID from a byte slice of length 16.

§Errors

Returns Error::InvalidUuid if the slice is not exactly 16 bytes.

§Examples
use uuid::Uuid;

let uuid = Uuid::from_slice(&[0; 16]).unwrap();
assert_eq!(uuid, Uuid::nil());
Source

pub const fn as_bytes(&self) -> [u8; 16]

Return the 16-byte array representation.

§Examples
use uuid::Uuid;

let uuid = Uuid::nil();
assert_eq!(uuid.as_bytes(), [0; 16]);
Source

pub const fn from_u128(v: u128) -> Uuid

Create a UUID from a u128 value (big-endian).

§Examples
use uuid::Uuid;

let uuid = Uuid::from_u128(0);
assert_eq!(uuid, Uuid::nil());
Source

pub const fn as_u128(&self) -> u128

Return the UUID as a u128 value (big-endian).

§Examples
use uuid::Uuid;

let uuid = Uuid::max();
assert_eq!(uuid.as_u128(), !0);
Source

pub const fn nil() -> Uuid

The Nil UUID: all 128 bits set to zero.

§Examples
use uuid::Uuid;

assert_eq!(Uuid::nil().to_string(), "00000000-0000-0000-0000-000000000000");
Source

pub const fn max() -> Uuid

The Max UUID: all 128 bits set to one.

§Examples
use uuid::Uuid;

assert_eq!(Uuid::max().to_string(), "ffffffff-ffff-ffff-ffff-ffffffffffff");
Source

pub const fn version(&self) -> Version

Return the Version of this UUID.

§Examples
use uuid::{Uuid, Version};

assert_eq!(Uuid::nil().version(), Version::Nil);
assert_eq!(Uuid::max().version(), Version::Max);
Source

pub fn timestamp(&self) -> Option<u64>

Return the Unix millisecond timestamp embedded in a UUIDv7.

Only UUID version 7 (Unix Epoch time-based) carries a meaningful timestamp. All other versions return None.

The timestamp is a 48-bit value representing milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).

§Examples
use uuid::Uuid;

let uuid = Uuid::nil();
assert_eq!(uuid.timestamp(), None);

Trait Implementations§

Source§

impl Clone for Uuid

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Uuid

Source§

impl Debug for Uuid

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Uuid

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Uuid

Available on crate feature serde only.
Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Uuid, D::Error>

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Uuid

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the UUID as a lowercase 8-4-4-4-12 hyphenated string.

§Examples
let uuid = uuid::Uuid::nil();
assert_eq!(uuid.to_string(), "00000000-0000-0000-0000-000000000000");
Source§

impl Eq for Uuid

Source§

impl FromStr for Uuid

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Uuid, Error>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Uuid

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Uuid

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Uuid

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Uuid

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Uuid

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Uuid

Source§

impl TryFrom<&[u8]> for Uuid

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: &[u8]) -> Result<Uuid, Error>

Performs the conversion.
Source§

impl TryFrom<&str> for Uuid

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: &str) -> Result<Uuid, Error>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Uuid

§

impl RefUnwindSafe for Uuid

§

impl Send for Uuid

§

impl Sync for Uuid

§

impl Unpin for Uuid

§

impl UnsafeUnpin for Uuid

§

impl UnwindSafe for Uuid

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.