snowflake-gen
A configurable Snowflake ID generator for Rust.
Features
- Configurable bit layout -- tune the balance between timestamp range, throughput, and node count
- Thread-local global API -- zero-lock, zero-contention ID generation across threads
- ID decomposition -- decode any generated ID back into its timestamp, machine, node, and sequence parts
- Buffered generation --
SnowflakeIdBucketpre-generates a full sequence batch for maximum throughput - Custom epochs -- use Discord-style, Twitter-style, or your own epoch
Default layout (Twitter-compatible)
| Field | Bits | Max value |
|---|---|---|
| Timestamp | 41 | ~69 years |
| Machine ID | 5 | 31 |
| Node ID | 5 | 31 |
| Sequence | 12 | 4,095/ms |
Quick start
use SnowflakeIdGenerator;
let mut gen = new.unwrap;
let id = gen.generate.unwrap;
println!;
Custom bit layout
use ;
// 10 sequence bits (1,023 IDs/ms), 8 machine + 7 node bits
let layout = new.unwrap;
let mut gen = with_layout.unwrap;
let id = gen.generate.unwrap;
Thread-local global API
Initialize once, then call next_id() from any thread with no locking:
use ;
Each thread gets its own generator with a unique node_id assigned automatically.
ID decomposition
use SnowflakeIdGenerator;
let mut gen = new.unwrap;
let id = gen.generate.unwrap;
let parts = gen.decompose;
assert_eq!;
assert_eq!;
Buffered generation
SnowflakeIdBucket pre-generates a full sequence cycle and serves IDs from a buffer:
use SnowflakeIdBucket;
let mut bucket = new.unwrap;
let id = bucket.get_id;
License
MIT