uuid7

Crates.io License

A Rust implementation of the proposed UUID Version 7

```rust let uuid = uuid7::uuid7(); println!("{uuid}"); // e.g. "01809424-3e59-7c05-9219-566f82fff672" println!("{:?}", uuid.as_bytes()); // as 16-byte big-endian array

let uuidstring: String = uuid7::uuid7().tostring(); ```

See draft-ietf-uuidrev-rfc4122bis-07.

Field and bit layout

This implementation produces identifiers with the following bit layout:

text 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | unix_ts_ms | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | unix_ts_ms | ver | counter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |var| counter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | rand | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Where:

The 42-bit counter is sufficiently large, so you do not usually need to worry about overflow, but in an extremely rare circumstance where it overflows, this library increments the unix_ts_ms field. As a result, the unix_ts_ms may have a greater value than that of the system's real-time clock.

UUIDv7, by design, heavily relies on the system's wall clock to guarantee the monotonically increasing order of generated IDs. A generator may not be able to produce a monotonic sequence if the system clock goes backwards. This library ignores a clock rollback and freezes the previously used unix_ts_ms unless the clock rollback is considered significant (by default, ten seconds or more). If such a significant rollback takes place, this library resets the generator and thus breaks the monotonic order of generated IDs.

Crate features

Default features:

Optional features:

Other functionality

This library also supports the generation of UUID version 4:

rust let uuid = uuid7::uuid4(); println!("{uuid}"); // e.g. "2ca4b2ce-6c13-40d4-bccf-37d222820f6f"

V7Generator provides an interface that allows finer control over the various aspects of the UUIDv7 generation:

```rust use uuid7::V7Generator;

let mut g = V7Generator::new(rand::rngs::OsRng); let customunixtsms = 0x012345678901u64; let x = g.generateorresetcore(customunixtsms, 10000); println!("{x}");

let y = g .generateorabortcore(customunixtsms, 10000) .expect("clock went backwards by 10000 milliseconds or more"); println!("{y}"); ```

License

Licensed under the Apache License, Version 2.0.

See also