Unique Identifiers
Recipe | Crates | Categories |
---|---|---|
Generate and Parse UUIDs | ||
Generate and Parse ULIDs |
Generate and Parse UUIDs
A UUID is a unique 128-bit value, stored as 16 octets, and regularly formatted as a hex string in five groups. UUIDs are used to assign unique identifiers to entities without requiring a central allocating authority. They are particularly useful in distributed systems, though can be used in disparate areas, such as and network protocols.
uuid
↗ generates and parses UUIDs and implements a number of utility functions.
use uuid::Uuid; use uuid::uuid; fn main() { // Generate a new UUID (version 4) randomly: let my_uuid = Uuid::new_v4(); println!("Generated UUID: {my_uuid}"); // Parse a UUID from a string: let uuid_str = "550e8400-e29b-41d4-a716-446655440000"; match Uuid::parse_str(uuid_str) { Ok(parsed_uuid) => println!("Parsed UUID: {parsed_uuid}"), Err(e) => println!("Failed to parse UUID: {e}"), } // Use a macro to create a UUID from a string literal at compile time. // This is useful for defining constant UUIDs: const ID: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8"); // Print the UUID as a URN (Uniform Resource Name): println!("{}", ID.urn()); // Compare UUIDs. // Since `another_uuid` is newly generated, it will (almost certainly) be // different from `my_uuid`: let another_uuid = Uuid::new_v4(); if my_uuid == another_uuid { println!("The UUIDs are equal."); } else { println!("The UUIDs are different."); } }
Generate and Parse ULIDs
ULID stands for Universally Unique Lexicographically Sortable Identifier, which is a type of unique identifier that is 128 bits long and can be lexicographically sorted in order of creation. It is designed to avoid some limitations of UUIDs, such as being more compact and allowing for easier sorting. Of the 128-bits, the first 48 are a Unix timestamp in milliseconds. The remaining 80 are random. The first 48 provide for lexicographic sorting and the remaining 80 ensure that the identifier is unique. Canonically, a ULID is represented as a 26 character Crockford Base32-encoded string. ulid↗ implements ULIDs in Rust:
use std::str::FromStr; use ulid::Ulid; fn main() { // Generate a new ULID. // It automatically captures the current system time for the timestamp // portion and fills the rest with cryptographically secure random data: let new_ulid = Ulid::new(); println!("Generated ULID: {new_ulid}"); // You can also get its components: println!("Timestamp: {}", new_ulid.timestamp_ms()); println!("Randomness: {:x}", new_ulid.random()); // Print as hexadecimal. println!("--------------------"); // Parse a ULID from a string: let ulid_str = "01K3W709C2RK498J5C5XBTXP1Y"; match Ulid::from_str(ulid_str) { // Or use `parse()`. Ok(parsed_ulid) => { println!("Successfully parsed ULID: {parsed_ulid}"); println!("Parsed timestamp: {:?} ms", parsed_ulid.datetime()); } Err(e) => { println!("Failed to parse ULID: {e}"); } } }
Related Topics
- Maps.
- Heapless data structures.