Skip to main content

Module snowflake

Module snowflake 

Source
Available on crate feature snowflake only.
Expand description

§Snowflake ID generation

64-bit IDs in the Twitter Snowflake layout: a 41-bit millisecond timestamp offset from a configurable epoch, a 10-bit worker ID, and a 12-bit per-millisecond sequence.

 63                   22         12         0
 +---------------------+----------+----------+
 | 41 bits ms offset   | 10 bits  | 12 bits  |
 | (since epoch_ms)    | worker   | sequence |
 +---------------------+----------+----------+

IDs are strictly monotonic within a single worker. When 4096 IDs are minted in the same millisecond the generator blocks (microsleep loop) until the wall clock advances. When the wall clock moves backward, Snowflake::try_next_id returns Err(ClockSkew) and Snowflake::next_id panics — the spec forbids issuing IDs whose timestamps could collide with previously issued ones.

use id_forge::snowflake::Snowflake;

let gen = Snowflake::new(1);
let a = gen.next_id();
let b = gen.next_id();
assert!(b > a);
let (ts_offset, worker, seq) = Snowflake::parts(b);
assert_eq!(worker, 1);
assert!(ts_offset > 0);
assert!(seq <= 4095);

Structs§

ClockSkew
Error returned by Snowflake::try_next_id when the system clock has moved backward since the most recent ID was issued.
Snowflake
Snowflake ID generator.

Constants§

DEFAULT_EPOCH_MS
Default epoch (2026-01-01T00:00:00Z in milliseconds since UNIX epoch).
SEQUENCE_BITS
Number of bits assigned to the sequence field in an ID.
TIMESTAMP_BITS
Number of bits assigned to the timestamp offset in an ID.
WORKER_BITS
Number of bits assigned to the worker field in an ID.