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§
- Clock
Skew - Error returned by
Snowflake::try_next_idwhen 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.