### Install cargo-afl Source: https://github.com/uuid-rs/uuid/blob/main/fuzz/README.md Install the cargo-afl tool, which is required for fuzzing. ```shell cargo install -f argo-afl ``` -------------------------------- ### Common Patterns: Generate and Store Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Example demonstrating how to generate a random v4 UUID and convert it to a string for storage or display. ```APIDOC ## Common Patterns: Generate and Store Example demonstrating how to generate a random v4 UUID and convert it to a string for storage or display. ```rust use uuid::Uuid; let uuid = Uuid::new_v4(); let string = uuid.to_string(); println!("Generated: {}", string); ``` ``` -------------------------------- ### Common Patterns: Parse and Validate Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Example showing how to parse a string into a UUID and handle potential parsing errors. ```APIDOC ## Common Patterns: Parse and Validate Example showing how to parse a string into a UUID and handle potential parsing errors. ```rust use uuid::Uuid; if let Ok(uuid) = Uuid::parse_str(input) { // Valid UUID } else { // Invalid UUID } ``` ``` -------------------------------- ### Common Patterns: Use in Structs (with Serde) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Example illustrating how to use UUIDs within structs and serialize/deserialize them using the Serde library. ```APIDOC ## Common Patterns: Use in Structs (with Serde) Example illustrating how to use UUIDs within structs and serialize/deserialize them using the Serde library. ```rust use uuid::Uuid; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct User { id: Uuid, name: String, } ``` ``` -------------------------------- ### Common Patterns: Build Custom UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Example showing how to construct a custom UUID using the `Builder` with specific version and variant settings. ```APIDOC ## Common Patterns: Build Custom UUID Example showing how to construct a custom UUID using the `Builder` with specific version and variant settings. ```rust use uuid::{Builder, Version, Variant}; let uuid = Builder::from_bytes([0; 16]) .with_version(Version::Custom) .with_variant(Variant::RFC4122) .into_uuid(); ``` ``` -------------------------------- ### Serialize and Deserialize UUID with Serde Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example demonstrating how to use the `serde` feature to serialize and deserialize a struct containing a `Uuid` to and from JSON. ```rust use uuid::Uuid; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct User { id: Uuid, name: String, } let json = serde_json::json!({ "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Alice" }); let user: User = serde_json::from_value(json)?; ``` -------------------------------- ### Example ClockSequence Implementation Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md A sample implementation of the `ClockSequence` trait that increments a counter. Uses `rand::random` for initial counter value. ```rust use uuid::ClockSequence; struct MyClockSequence { counter: u16, } impl MyClockSequence { fn new() -> Self { MyClockSequence { counter: rand::random(), } } } impl ClockSequence for MyClockSequence { fn generate_sequence(&mut self, _high: u32, _low: u32) -> u16 { self.counter = self.counter.wrapping_add(1); self.counter } } ``` -------------------------------- ### Generate Version 1 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 1 UUID using the 'v1' feature. Requires 'Uuid', 'Timestamp', and 'ContextV1'. ```rust use uuid::{Uuid, Timestamp, ContextV1}; let context = ContextV1::new(42); let ts = Timestamp::now(&context); let uuid = Uuid::new_v1(ts, &[1, 2, 3, 4, 5, 6]); ``` -------------------------------- ### Cast Uuid to Bytes with Bytemuck Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example demonstrating how to use the `bytemuck` feature to cast a `Uuid` to its byte representation (`&[u8; 16]`) without performing a copy. ```rust use uuid::Uuid; use bytemuck::Pod; let uuid = Uuid::new_v4(); let bytes = bytemuck::bytes_of(&uuid); ``` -------------------------------- ### Bulk Formatting UUIDs to Lowercase Hex Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md An example demonstrating efficient bulk formatting of multiple UUIDs into lowercase hyphenated strings using a pre-allocated buffer. This method is faster than allocating a new String for each UUID. ```rust use uuid::Uuid; let uuids = vec![Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()]; let mut buffer = Uuid::encode_buffer(); for uuid in uuids { let encoded = uuid.hyphenated().encode_lower(&mut buffer); process(encoded); // Use the string slice } ``` -------------------------------- ### Generate Version 5 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 5 UUID using the 'v5' feature. This method uses a namespace UUID and a byte slice representing a name. ```rust use uuid::Uuid; let uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com"); ``` -------------------------------- ### Run Fuzz Case Interactively Source: https://github.com/uuid-rs/uuid/blob/main/fuzz/README.md Run a specific fuzz test case interactively. This command starts the AFL TUI and requires specifying input and output directories, as well as the path to the fuzz target executable. ```shell cargo afl fuzz -i fuzz/$TARGET_NAME/in -o fuzz/target/$TARGET_NAME fuzz/target/debug/$TARGET_NAME ``` -------------------------------- ### Generate Version 7 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 7 UUID using the 'v7' feature. This method produces a sortable UUID based on the current Unix timestamp. ```rust use uuid::Uuid; let uuid = Uuid::now_v7(); ``` -------------------------------- ### ParseLength Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Illustrates an error when the input string's length does not match any of the valid UUID format lengths (32, 36, 38, or 45 characters). This is a preliminary check before detailed parsing. ```Rust use uuid::Uuid; // 30 characters - too short for any format let result = Uuid::parse_str("550e8400-e29b-41d4-a716-44665544000"); // Error: invalid length: found 35 ``` -------------------------------- ### Generate Version 3 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 3 UUID using the 'v3' feature. This method uses a namespace UUID and a byte slice representing a name. ```rust use uuid::Uuid; let uuid = Uuid::new_v3(&Uuid::NAMESPACE_DNS, b"example.com"); ``` -------------------------------- ### Generate Version 8 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 8 UUID using the 'v8' feature. This method takes a 16-byte array for custom data. ```rust use uuid::Uuid; let uuid = Uuid::new_v8([0x0f; 16]); ``` -------------------------------- ### ContextV1 Constructor and Usage Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md Demonstrates creating a `ContextV1` instance with an initial counter and using it to generate a Version 1 UUID. ```rust use uuid::{Uuid, Timestamp, ContextV1}; let context = ContextV1::new(42); let ts = Timestamp::now(&context); let uuid = Uuid::new_v1(ts, &[0, 1, 2, 3, 4, 5]); ``` -------------------------------- ### Consume Builder and Get UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Consumes the Builder and returns the constructed UUID. This is a const-friendly operation. ```rust pub const fn into_uuid(self) -> Uuid ``` ```rust use uuid::Builder; let uuid = Builder::nil() .into_uuid(); ``` -------------------------------- ### to_bytes_le() Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the bytes of the UUID with each field in little-endian order. Useful for Microsoft GUID compatibility. ```APIDOC ## to_bytes_le() ### Description Returns the bytes of the UUID with each field in little-endian order. Useful for Microsoft GUID compatibility. ### Method `pub const fn to_bytes_le(&self) -> Bytes` ### Parameters No parameters. ### Returns `[u8; 16]` — The UUID bytes with fields byte-swapped. ### Example ```rust use uuid::Uuid; let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?; let bytes_le = uuid.to_bytes_le(); ``` ``` -------------------------------- ### Get Reference to UUID from Builder Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Returns a reference to the UUID without consuming the builder. This is a const-friendly operation. ```rust pub const fn as_uuid(&self) -> &Uuid ``` -------------------------------- ### Build Custom UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Constructs a UUID with specific version and variant settings, starting from a byte array. ```rust use uuid::{Builder, Version, Variant}; let uuid = Builder::from_bytes([0; 16]) .with_version(Version::Custom) .with_variant(Variant::RFC4122) .into_uuid(); ``` -------------------------------- ### ContextV6 Constructor Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md Initializes a ContextV6 for Version 6 UUID generation. Identical to ContextV1. ```rust impl ContextV6 { pub fn new(initial_counter: u16) -> Self } ``` -------------------------------- ### UUID bytes in Little-Endian Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the bytes of the UUID with each field in little-endian order. This format is compatible with Microsoft GUIDs. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?; let bytes_le = uuid.to_bytes_le(); ``` -------------------------------- ### Common Patterns: Create Deterministic from Domain Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Demonstrates creating deterministic UUIDs (v3 or v5) from a namespace and a name, such as a domain name. ```APIDOC ## Common Patterns: Create Deterministic from Domain Demonstrates creating deterministic UUIDs (v3 or v5) from a namespace and a name, such as a domain name. ```rust use uuid::Uuid; // Option 1: v5 (SHA-1, preferred) let uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com"); // Option 2: v3 (MD5, legacy) let uuid = Uuid::new_v3(&Uuid::NAMESPACE_DNS, b"example.com"); ``` ``` -------------------------------- ### Get UUID as Bytes Reference Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns a reference to the underlying 16-byte array. The length of the returned slice is always 16. ```rust use uuid::Uuid; let uuid = Uuid::nil(); let bytes = uuid.as_bytes(); assert_eq!(bytes.len(), 16); ``` -------------------------------- ### Nil UUID Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Represents an error condition where a nil UUID is encountered in a context that does not permit it, such as when creating a `NonNilUuid`. ```Rust use uuid::Uuid; // Example demonstrating a scenario that might lead to a Nil error (conceptual) // let nil_uuid = Uuid::nil(); // let non_nil_uuid = NonNilUuid::try_from(nil_uuid); // Error: the UUID is nil ``` -------------------------------- ### uuid-rs API Documentation Overview Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/README.md This section provides an overview of the API documentation structure and conventions used within the uuid-rs project. It details how to navigate the documentation, understand code blocks, tables, method signatures, parameters, return values, error conditions, and source references. ```APIDOC ## uuid-rs API Documentation Conventions ### Document Organization - Organized by logical grouping, depth, usability, and completeness. - Each document is self-contained. ### Source Information - Documentation derived from source code at `/workspace/home/uuid`. - Version: 1.23.3, Edition: 2021, MSRV: 1.85.0. ### Key Tasks and Corresponding Documentation Sections - Generate random UUID: `01-uuid-struct.md` → Creating UUIDs → `new_v4()` - Create sortable UUID: `01-uuid-struct.md` → Creating UUIDs → `new_v7()` - Parse UUID string: `07-formatting-and-parsing.md` → Parsing UUIDs - Format UUID: `07-formatting-and-parsing.md` → Formatting UUIDs - Time-based UUIDs: `06-timestamp-reference.md` - Handle errors: `04-errors.md` - Choose features: `05-configuration.md` - Use Builder: `02-builder.md` - Type definitions: `03-types.md` ### Format Conventions - **Code blocks**: Triple backticks with language identifier. - **Tables**: Markdown format. - **Method signatures**: Exact, copy-paste ready. - **Parameters**: Documented as: `name | type | required | description`. - **Returns**: Exact return type. - **Throws**: Lists error conditions. - **Sources**: Reference file path and line number. - **Examples**: Tested and functional. ### Navigation Tips 1. Start with `00-index.md` for orientation. 2. Use Ctrl+F to search for specific function names. 3. Files are numbered for easy reference. 4. Method index in `00-index.md` lists all 70+ exported items. 5. Cross-references use markdown links. ### What This IS NOT - ❌ Tutorial or getting-started guide - ❌ Design rationale or implementation details - ❌ Historical changelog or RFC details - ❌ Community contribution guidelines - ❌ Performance benchmarks or comparisons - ❌ Library recommendations or alternatives ### What This IS - ✅ Complete API reference - ✅ All exported types and methods - ✅ Parameter documentation - ✅ Return type documentation - ✅ Error documentation - ✅ Configuration reference - ✅ Usage examples - ✅ Source code locations --- ``` -------------------------------- ### Dependency Configuration for All Standard Versions Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate to enable all standard UUID versions (v1, v3, v4, v5, v6, v7). ```toml uuid = { version = "1.23.3", features = ["v1", "v3", "v4", "v5", "v6", "v7"] } ``` -------------------------------- ### Get UUID Version Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the version of the UUID if it is recognized, otherwise returns None. The version is returned as an Option enum. ```rust use uuid::{Uuid, Version}; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; assert_eq!(uuid.get_version(), Some(Version::Random)); ``` -------------------------------- ### Enable zerocopy Feature Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Enables zero-copy deserialization with the unstable `zerocopy` crate. Requires setting RUSTFLAGS. ```toml [dependencies.uuid] version = "1.23.3" features = ["zerocopy"] ``` ```bash RUSTFLAGS="--cfg uuid_unstable" cargo build ``` -------------------------------- ### Get UUID Variant Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the variant of the UUID structure. This determines the interpretation of the variant field bits but does not validate RFC conformance. ```rust use uuid::{Uuid, Variant}; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; assert_eq!(uuid.get_variant(), Variant::RFC4122); ``` -------------------------------- ### Dependency Configuration for All Features Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate to enable all available features, including all UUID versions, serialization formats, and random number generators. ```toml uuid = { version = "1.23.3", features = ["v1", "v3", "v4", "v5", "v6", "v7", "v8", "serde", "borsh", "fast-rng"] } ``` -------------------------------- ### Minimal Dependency Configuration Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Specifies the minimal uuid crate version for projects that only require parsing functionality. ```toml uuid = "1.23.3" ``` -------------------------------- ### ContextV7 Constructor Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md Initializes a ContextV7 for Version 7 UUID generation. Manages a monotonic counter internally. ```rust impl ContextV7 { pub fn new() -> Self } ``` -------------------------------- ### Generate Version 4 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 4 UUID using the 'v4' feature. This method produces a random UUID. ```rust use uuid::Uuid; let uuid = Uuid::new_v4(); ``` -------------------------------- ### Create Custom UUID with Version and Variant Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Demonstrates creating a custom UUID by setting both version and variant bits using the Builder pattern. ```rust use uuid::{Builder, Version, Variant}; let builder = Builder::from_bytes([0x0f; 16]) .with_version(Version::Custom) .with_variant(Variant::RFC4122); let uuid = builder.into_uuid(); ``` -------------------------------- ### Configure System for Fuzzing Source: https://github.com/uuid-rs/uuid/blob/main/fuzz/README.md Configure your system to prepare for fuzzing operations with cargo-afl. ```shell cargo afl config --build --force cargo afl system-config ``` -------------------------------- ### Using Result Methods for UUID Parsing Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Demonstrates various `Result` methods like `unwrap`, `expect`, `unwrap_or`, `map`, and `and_then` for handling UUID parsing outcomes. ```rust use uuid::Uuid; // Using unwrap (panics on error) let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(); // Using expect (panics with custom message) let uuid = Uuid::parse_str(input) .expect("failed to parse UUID from environment"); // Using unwrap_or (provides default) let uuid = Uuid::parse_str(input) .unwrap_or(Uuid::nil()); // Using map for transformation let result = Uuid::parse_str(input) .map(|uuid| format!("UUID: {}", uuid.hyphenated())); // Using and_then for chaining let result = Uuid::parse_str(input1) .and_then(|_| Uuid::parse_str(input2)); ``` -------------------------------- ### ParseChar Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Demonstrates an error when an invalid character is encountered during UUID string parsing. This occurs with non-hexadecimal characters in the UUID string. ```Rust use uuid::Uuid; // Invalid character 'G' at position 8 let result = Uuid::parse_str("550e8400-G29b-41d4-a716-446655440000"); // Error: invalid character: found 'G' at 9 ``` -------------------------------- ### Distributed System Feature Combination Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Recommended features for distributed systems, using v1/v6 for time-ordered identifiers and v7 for sortable timestamps. ```toml [dependencies.uuid] version = "1.23.3" features = ["v1", "v6", "v7"] ``` -------------------------------- ### Get Timestamp from UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Extracts the timestamp from a version 1, 6, or 7 UUID. Returns None for other versions. The timestamp is returned as an Option. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("20616934-4ba2-11e7-8000-010203040506")?; if let Some(ts) = uuid.get_timestamp() { // timestamp is extracted as a version-agnostic Timestamp } ``` -------------------------------- ### with_version Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Returns a new Builder with the version bits set. This is a const-friendly version of `set_version`. ```APIDOC ## with_version(v: Version) ### Description Returns a new Builder with the version bits set. Const-friendly version of `set_version`. ### Parameters #### Path Parameters - **v** (Version) - Required - The version to set ### Returns `Builder` — A new builder with the version set. ### Example ```rust use uuid::{Builder, Version}; let uuid = Builder::nil() .with_version(Version::Custom) .into_uuid(); ``` ``` -------------------------------- ### Format UUID as Simple String Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md Use the `simple()` formatter to get a 32-character hexadecimal string representation of a UUID. This method is useful when hyphens are not desired. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; println!("{}", uuid.simple()); // Output: 550e8400e29b41d4a716446655440000 println!("{:X}", uuid.simple()); // Output: 550E8400E29B41D4A716446655440000 ``` -------------------------------- ### Generate Version 6 UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Example of generating a Version 6 UUID using the 'v6' feature. This method creates sortable, time-ordered UUIDs. ```rust use uuid::{Uuid, Timestamp, ContextV1}; let context = ContextV1::new(42); let ts = Timestamp::now(&context); let uuid = Uuid::new_v6(ts, &[1, 2, 3, 4, 5, 6]); ``` -------------------------------- ### Dependency Configuration for Deterministic IDs Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate to include the 'v5' feature for generating deterministic UUIDs. ```toml uuid = { version = "1.23.3", features = ["v5"] } ``` -------------------------------- ### Get UUID Version Number Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the version number as an integer (0-15) without checking if it's a recognized version. This provides a raw version number. ```rust pub const fn get_version_num(&self) -> usize ``` -------------------------------- ### Common Patterns: Sortable IDs for Database Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Illustrates generating sortable UUIDs (v7 or v6) suitable for use as database primary keys. ```APIDOC ## Common Patterns: Sortable IDs for Database Illustrates generating sortable UUIDs (v7 or v6) suitable for use as database primary keys. ```rust use uuid::Uuid; // v7: Sortable, modern, recommended let uuid = Uuid::now_v7(); // v6: Sortable, legacy alternative let context = uuid::ContextV1::new(0); let ts = uuid::Timestamp::now(&context); let uuid = Uuid::new_v6(ts, &[1, 2, 3, 4, 5, 6]); ``` ``` -------------------------------- ### Format UUID as Braced String Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md Use the `braced()` formatter to get a UUID string enclosed in curly braces. This format is also automatically supported by `parse_str`. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; println!("{}", uuid.braced()); // Output: {550e8400-e29b-41d4-a716-446655440000} println!("{:X}", uuid.braced()); // Output: {550E8400-E29B-41D4-A716-446655440000} ``` ```rust let uuid = Uuid::parse_str("{550e8400-e29b-41d4-a716-446655440000}")?; ``` -------------------------------- ### Format UUIDs using Hyphenated Specifier Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md Use the `hyphenated()` method to get a formatter for the standard hyphenated UUID format. It supports encoding in both lowercase and uppercase. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; println!("{}", uuid.hyphenated()); // Output: 550e8400-e29b-41d4-a716-446655440000 println!("{:X}", uuid.hyphenated()); // Output: 550E8400-E29B-41D4-A716-446655440000 let mut buffer = Uuid::encode_buffer(); let encoded = uuid.hyphenated().encode_lower(&mut buffer); assert_eq!(encoded, "550e8400-e29b-41d4-a716-446655440000"); ``` -------------------------------- ### Convert External Data to UUID Builder Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Shows how to create a UUID Builder from raw bytes, specific fields, or random bytes with a specified version. ```rust use uuid::Builder; // From raw bytes let builder = Builder::from_bytes([0; 16])?; // From fields (common in database libraries) let builder = Builder::from_fields( 0xa1a2a3a4, 0xb1b2, 0xc1c2, &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8] ); // From a custom UUID generation algorithm let builder = Builder::from_random_bytes([/* random bytes */; 16]) .with_version(Version::Random); ``` -------------------------------- ### Create Builder from Byte Slice (Little-Endian) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Creates a Builder from a byte slice, interpreting the bytes in little-endian field order. An error is returned if the slice is not 16 bytes. ```rust pub fn from_slice_le(b: &[u8]) -> Result ``` -------------------------------- ### ParseByteLength Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Illustrates an error when `Uuid::from_slice` is called with a byte slice that is not exactly 16 bytes long. This is crucial for byte-based UUID representations. ```Rust use uuid::Uuid; let bytes = vec![0u8; 15]; let result = Uuid::from_slice(&bytes); // Error: invalid length: expected 16 bytes, found 15 ``` -------------------------------- ### Format UUID as URN String Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md Use the `urn()` formatter to get a URN-compliant string representation of a UUID, prefixed with `urn:uuid:`. This format is automatically supported by `parse_str`. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; println!("{}", uuid.urn()); // Output: urn:uuid:550e8400-e29b-41d4-a716-446655440000 println!("{:X}", uuid.urn()); // Output: urn:uuid:550E8400-E29B-41D4-A716-446655440000 ``` ```rust let uuid = Uuid::parse_str("urn:uuid:550e8400-e29b-41d4-a716-446655440000")?; ``` -------------------------------- ### Enable Borsh Serialization for UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Use this configuration to enable serialization with the Borsh binary format, which is useful for storage or RPC in ecosystems like Solana. It implements `BorshDeserialize` and `BorshSerialize` for `Uuid`. ```toml [dependencies.uuid] version = "1.23.3" features = ["borsh"] ``` -------------------------------- ### Alternative Serde Formats for UUIDs Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/07-formatting-and-parsing.md Illustrates how to specify alternative Serde formats for UUID serialization using `#[serde(with = "...")]`. This allows for formats like 'simple' (32 hex digits without hyphens). ```rust use uuid::Uuid; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Data { #[serde(with = "uuid::serde::simple")] id: Uuid, } // Serializes as: {"id":"550e8400e29b41d4a716446655440000"} ``` -------------------------------- ### ParseInvalidUTF8 Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Demonstrates the error when the input bytes provided to a UUID parsing function are not valid UTF-8. This is relevant for functions that expect string-like byte inputs. ```Rust use uuid::Uuid; let invalid_bytes = b"550e8400-e29b-41d4-a716-\xFF\xFF"; let result = Uuid::try_parse_ascii(invalid_bytes); // Error: non-UTF8 input ``` -------------------------------- ### ParseGroupLength Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Highlights an error where a group within a hyphenated UUID string has an incorrect number of hexadecimal digits for its position. This validates the structure of each UUID segment. ```Rust use uuid::Uuid; // Third group should be 4 hex digits, but has 3 let result = Uuid::parse_str("550e8400-e29b-41d-a716-446655440000"); // Error: invalid group length in group 2: expected 4, found 3 ``` -------------------------------- ### Enable Serde Serialization for UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Use this configuration when you need to serialize UUIDs in JSON, YAML, or binary formats via the serde crate. It implements `Serialize` and `Deserialize` for `Uuid`. ```toml [dependencies.uuid] version = "1.23.3" features = ["serde"] [dependencies.serde] version = "1.0" features = ["derive"] [dependencies.serde_json] version = "1.0" ``` -------------------------------- ### Uuid::now_v7 Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Creates a version 7 UUID using the current system time. Requires the `v7` feature and `std`/`rng`. ```APIDOC ## Uuid::now_v7() ### Description Creates a version 7 UUID using the current system time. Requires the `v7` feature and `std`/`rng`. ### Parameters #### Path Parameters - **—** (—) - — - No parameters ### Returns `Uuid` — A sortable UUID containing the current timestamp. ### Example ```rust use uuid::Uuid; let uuid = Uuid::now_v7(); ``` ``` -------------------------------- ### Get Node ID from UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the node ID from a version 1 or 6 UUID. Returns None for other versions. The node ID is returned as an Option<[u8; 6]>. ```rust use uuid::Uuid; let uuid = Uuid::parse_str("20616934-4ba2-11e7-8000-010203040506")?; if let Some(node_id) = uuid.get_node_id() { println!("Node: {:?}", node_id); } ``` -------------------------------- ### WebAssembly Feature Combination Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Features for WebAssembly applications, enabling JavaScript interop for OS randomness. ```toml [dependencies.uuid] version = "1.23.3" features = ["v4", "v7", "js"] ``` -------------------------------- ### Dependency Configuration for Web API (JSON) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate with features for web APIs, including random ID generation (v4), sortable IDs (v7), and JSON serialization support (serde). ```toml uuid = { version = "1.23.3", features = ["v4", "v7", "serde"] } ``` -------------------------------- ### Database Application Feature Combination Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Recommended features for using sortable v7 UUIDs in database applications for better index performance. ```toml [dependencies.uuid] version = "1.23.3" features = ["v7", "serde"] ``` -------------------------------- ### Get UUID Fields Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the four field values of the UUID in big-endian order as per RFC 9562. The fields are returned as a tuple: (u32, u16, u16, &[u8; 8]). ```rust use uuid::Uuid; let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?; let (d1, d2, d3, d4) = uuid.as_fields(); ``` -------------------------------- ### ParseGroupCount Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Shows an error when a hyphenated UUID string does not contain the expected 5 groups separated by 4 hyphens. This ensures correct formatting for standard UUID representations. ```Rust use uuid::Uuid; // Missing one hyphen (4 groups instead of 5) let result = Uuid::parse_str("550e8400-e29b-41d4-446655440000"); // Error: invalid group count: expected 5, found 4 ``` -------------------------------- ### Enable Bytemuck for Zero-Copy UUID Manipulation Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Use this configuration to enable zero-copy byte manipulation with the `bytemuck` crate. It implements `Pod`, `Zeroable`, and `TransparentWrapper` traits, allowing casting between `[u8; 16]` and `Uuid` without copying. ```toml [dependencies.uuid] version = "1.23.3" features = ["bytemuck"] ``` -------------------------------- ### ParseOther Error Example Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/04-errors.md Shows a generic parsing failure when `Uuid::try_parse()` or `try_parse_ascii()` are used and the parsing fails without specific diagnostic information. For more detailed errors, `Uuid::parse_str()` is recommended. ```Rust use uuid::Uuid; let result = Uuid::try_parse_ascii(b"invalid"); // Error: failed to parse a UUID ``` -------------------------------- ### Dependency Configuration for Sortable IDs Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate to include the 'v7' feature for generating sortable UUIDs. ```toml uuid = { version = "1.23.3", features = ["v7"] } ``` -------------------------------- ### Timestamp::now Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md Creates a timestamp from the current system time. Requires the `std` feature and a `ClockSequence` context. ```APIDOC ## Timestamp::now ### Description Creates a timestamp from the current system time. ### Method `Timestamp::now(context: &impl ClockSequence) -> Self` ### Parameters #### Path Parameters - **context** (`&impl ClockSequence`) - Required - A clock sequence implementation (e.g., `ContextV1`) ### Response #### Success Response - **Self** (`Timestamp`) - The current system timestamp. ### Example ```rust use uuid::{Timestamp, ContextV1}; let context = ContextV1::new(42); let ts = Timestamp::now(&context); ``` ``` -------------------------------- ### UUID Creation Methods Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md This section details the various methods available for creating UUIDs, including nil, max, version-specific (v1, v3, v4, v5, v6, v7, v8), and conversion from byte slices or fields. ```APIDOC ## UUID Creation This section details the various methods available for creating UUIDs, including nil, max, version-specific (v1, v3, v4, v5, v6, v7, v8), and conversion from byte slices or fields. ### Methods - `Uuid::nil()`: Creates a nil UUID. - `Uuid::max()`: Creates a max UUID. - `Uuid::new_v1(ts, node)`: Creates a v1 UUID with a timestamp and node. - `Uuid::now_v1(node)`: Creates a v1 UUID using the current time and a node. - `Uuid::new_v3(ns, name)`: Creates a v3 UUID using a namespace and name (MD5). - `Uuid::new_v4()`: Creates a v4 UUID (random). - `Uuid::new_v5(ns, name)`: Creates a v5 UUID using a namespace and name (SHA-1). - `Uuid::new_v6(ts, node)`: Creates a v6 UUID with a timestamp and node. - `Uuid::now_v6(node)`: Creates a v6 UUID using the current time and a node. - `Uuid::new_v7(ts)`: Creates a v7 UUID with a timestamp. - `Uuid::now_v7()`: Creates a v7 UUID using the current time. - `Uuid::new_v8(buf)`: Creates a v8 UUID from a buffer. - `Uuid::from_bytes(bytes)`: Creates a UUID from a 16-byte array. - `Uuid::from_slice(bytes)`: Creates a UUID from a byte slice, returning a Result. - `Uuid::from_fields(d1, d2, d3, d4)`: Creates a UUID from its constituent fields (big-endian). - `Uuid::from_fields_le(...)`: Creates a UUID from its constituent fields (little-endian). - `Uuid::from_u128(v)`: Creates a UUID from a u128 integer (big-endian). - `Uuid::from_u128_le(v)`: Creates a UUID from a u128 integer (little-endian). - `Uuid::from_u64_pair(hi, lo)`: Creates a UUID from two u64 integers (high and low parts). ``` -------------------------------- ### ContextV1 Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/06-timestamp-reference.md A `ClockSequence` implementation for Version 1 UUIDs. ```APIDOC ## ContextV1 ### Description `ContextV1` is a ready-made `ClockSequence` implementation for Version 1 UUIDs (timestamp + node ID, non-sortable order). ### Constructor ```rust impl ContextV1 { pub fn new(initial_counter: u16) -> Self } ``` ### Parameters #### Path Parameters - **initial_counter** (`u16`) - Required - Starting clock sequence. RFC 9562 recommends a random value. ### Thread Safety `ContextV1` uses atomic operations internally and is `Send + Sync`. Share across threads via `Arc`. ### Example ```rust use uuid::{Uuid, Timestamp, ContextV1}; let context = ContextV1::new(42); let ts = Timestamp::now(&context); let uuid = Uuid::new_v1(ts, &[0, 1, 2, 3, 4, 5]); ``` ``` -------------------------------- ### Create Version 7 UUID from Unix Timestamp (Millis) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Initializes a version 7 UUID builder from a Unix timestamp in milliseconds and 10 bytes of counter/random data for sub-millisecond uniqueness. ```rust pub const fn from_unix_timestamp_millis(millis: u64, counter_random_bytes: &[u8; 10]) -> Self ``` -------------------------------- ### Create Builder from u128 (Little-Endian) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Initializes a Builder from a 128-bit unsigned integer, interpreting the value in little-endian order. ```rust pub const fn from_u128_le(v: u128) -> Self ``` -------------------------------- ### Reproduce Crashes Source: https://github.com/uuid-rs/uuid/blob/main/fuzz/README.md Run regular unit tests to automatically re-test any crashes found during fuzzing. Crashes are saved in the target directory. ```shell cargo test --manifest-path fuzz/Cargo.toml ``` -------------------------------- ### Create Builder with Specific Version Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Returns a new Builder with the version bits set. This is a const-friendly alternative to `set_version`. ```rust pub const fn with_version(mut self, v: Version) -> Self ``` ```rust use uuid::{Builder, Version}; let uuid = Builder::nil() .with_version(Version::Custom) .into_uuid(); ``` -------------------------------- ### Create Deterministic UUID from Domain Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Generates a deterministic UUID using version 5 (SHA-1) or version 3 (MD5) based on a namespace and a name, such as a domain name. ```rust use uuid::Uuid; // Option 1: v5 (SHA-1, preferred) let uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com"); // Option 2: v3 (MD5, legacy) let uuid = Uuid::new_v3(&Uuid::NAMESPACE_DNS, b"example.com"); ``` -------------------------------- ### Standard Namespace UUIDs and V5 Generation Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Utilizes predefined RFC 9562 namespace UUIDs (DNS, URL, OID, X500) to create deterministic version 5 UUIDs. ```rust use uuid::Uuid; let dns_uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com"); let url_uuid = Uuid::new_v5(&Uuid::NAMESPACE_URL, b"https://example.com"); ``` -------------------------------- ### Enable Slog Logging for UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Use this configuration to enable structured logging with the `slog` crate. It implements `slog::Value` for `Uuid`, allowing UUIDs to be logged within structured log messages. ```toml [dependencies.uuid] version = "1.23.3" features = ["slog"] ``` -------------------------------- ### Create Builder from Fields (Little-Endian) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Constructs a Builder from four distinct field values in little-endian order. Note the reversed integer field endianness. ```rust pub const fn from_fields_le(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Self ``` -------------------------------- ### Builder::from_unix_timestamp_millis Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Creates a Builder configured for a version 7 UUID from a Unix timestamp in milliseconds. ```APIDOC ## Builder::from_unix_timestamp_millis(millis, counter_random_bytes) ### Description Creates a Builder configured for a version 7 UUID from a Unix timestamp in milliseconds. ### Parameters #### Path Parameters - **millis** (u64) - Required - Milliseconds since Unix epoch - **counter_random_bytes** (array[u8; 10]) - Required - 10 bytes of counter/random data for sub-millisecond uniqueness ### Returns `Builder` — A builder pre-configured with version 7 and RFC4122 variant. ``` -------------------------------- ### Enable Fast RNG for UUID Generation Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Enable this feature to use a faster random number generation algorithm from the `rand` crate for v4 and v7 UUIDs. This results in faster generation at the cost of more dependencies and a slightly larger binary size. ```toml [dependencies.uuid] version = "1.23.3" features = ["v4", "fast-rng"] ``` -------------------------------- ### Enable Standard Library Functionality for UUID Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md This configuration enables standard library functionality, including methods requiring system time or heap allocation, and implements the `Error` trait. It is enabled by default and includes `std::string::String` conversion. ```toml [dependencies.uuid] version = "1.23.3" ``` -------------------------------- ### Dependency Configuration for Random IDs Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Configures the uuid crate to include the 'v4' feature for generating random UUIDs. ```toml uuid = { version = "1.23.3", features = ["v4"] } ``` -------------------------------- ### Create NonNilUuid from Uuid Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/03-types.md Shows how to create a NonNilUuid, which wraps a Uuid and ensures it is not the nil UUID. This is useful for domain types that require a valid, non-zero identifier. ```rust use uuid::{Uuid, NonNilUuid}; let uuid = Uuid::new_v4(); match NonNilUuid::new(uuid) { Some(non_nil) => println!("Valid: {}", non_nil), None => println!("UUID was nil"), } ``` -------------------------------- ### Create Version 5 UUID from SHA-1 Digest Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Initializes a version 5 UUID builder using the 16 least-significant bytes of a SHA-1 digest. ```rust pub const fn from_sha1_bytes(sha1_bytes: Bytes) -> Self ``` -------------------------------- ### get_version() Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Returns the version of the UUID if it is recognized, otherwise returns `None`. ```APIDOC ## get_version() ### Description Returns the version of the UUID if it is recognized, otherwise returns `None`. ### Method `const fn` ### Parameters No parameters ### Returns `Option` — The version enum or `None` for unrecognized versions. ### Example ```rust use uuid::{Uuid, Version}; let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000")?; assert_eq!(uuid.get_version(), Some(Version::Random)); ``` ``` -------------------------------- ### Builder::from_fields_le Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Creates a Builder from four field values in little-endian order. ```APIDOC ## Builder::from_fields_le ### Description Creates a Builder from four field values in little-endian order. ### Method `const fn from_fields_le(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Self` ### Parameters #### Path Parameters - **d1** (`u32`) - Required - First field (little-endian) - **d2** (`u16`) - Required - Second field (little-endian) - **d3** (`u16`) - Required - Third field (little-endian) - **d4** (`&[u8; 8]`) - Required - Last 8-byte field ### Response #### Success Response - **Builder** (`Builder`) - A builder with the specified fields. ### Request Example ```rust // Example for from_fields_le would involve providing the four field components in little-endian. ``` ``` -------------------------------- ### Enable Version 5 UUID Generation Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Use the 'v5' feature to enable Version 5 UUID generation, which creates SHA-1-based namespace UUIDs. This is preferred over v3 for deterministic UUIDs. ```toml [dependencies.uuid] version = "1.23.3" features = ["v5"] ``` -------------------------------- ### Builder::from_u128 Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/02-builder.md Creates a Builder from a 128-bit unsigned integer. ```APIDOC ## Builder::from_u128 ### Description Creates a Builder from a 128-bit unsigned integer. ### Method `const fn from_u128(v: u128) -> Self` ### Parameters #### Path Parameters - **v** (`u128`) - Required - A 128-bit value ### Response #### Success Response - **Builder** (`Builder`) - A builder with the specified value. ### Request Example ```rust // Example for from_u128 would involve providing a u128 value. ``` ``` -------------------------------- ### Uuid::new_v5(namespace, name) Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/01-uuid-struct.md Generates a version 5 UUID by hashing a namespace UUID and a name using SHA-1. Requires the `v5` feature. ```APIDOC ## Uuid::new_v5(namespace, name) ### Description Creates a version 5 UUID from a SHA-1 hash of a namespace UUID and name. Requires the `v5` feature. Preferred over v3 as SHA-1 is more modern. ### Method `pub fn new_v5(namespace: &Uuid, name: &[u8]) -> Uuid` ### Parameters #### Path Parameters - **namespace** (`&Uuid`) - Required - A predefined namespace UUID like `Uuid::NAMESPACE_DNS` - **name** (`&[u8]`) - Required - The data to hash (typically a domain or identifier) ### Returns `Uuid` — A deterministic UUID generated from the namespace and name. ### Example ```rust use uuid::Uuid; let uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"example.com"); ``` ``` -------------------------------- ### Use UUID in Structs with Serde Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/00-index.md Demonstrates how to use UUIDs within structs that are serialized or deserialized using the Serde library. ```rust use uuid::Uuid; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct User { id: Uuid, name: String, } ``` -------------------------------- ### Fuzzing / Property Testing Feature Combination Source: https://github.com/uuid-rs/uuid/blob/main/_autodocs/05-configuration.md Recommended features for fuzzing and property testing, enabling generation of random UUIDs for test data. ```toml [dependencies.uuid] version = "1.23.3" features = ["v4", "arbitrary"] ```