Skip to main content

snowflake_gen/
lib.rs

1//! # snowflake-gen
2//!
3//! A configurable Snowflake ID generator for Rust.
4//!
5//! ## Overview
6//!
7//! This crate implements the [Snowflake](https://en.wikipedia.org/wiki/Snowflake_ID) algorithm
8//! with fully configurable bit allocation so you can tune the balance between:
9//!
10//! - **Timestamp range** — how far into the future IDs remain valid
11//! - **Throughput** — how many IDs per millisecond (sequence bits)
12//! - **Node / machine count** — how many distributed generators you can run
13//!
14//! The classic Twitter layout is used by default:
15//!
16//! | Field       | Bits | Max value          |
17//! |-------------|------|--------------------|
18//! | Timestamp   | 41   | ~69 years           |
19//! | Machine ID  | 5    | 31                 |
20//! | Node ID     | 5    | 31                 |
21//! | Sequence    | 12   | 4 096 / ms         |
22//!
23//! ## Quick start
24//!
25//! ```rust
26//! use snowflake_gen::SnowflakeIdGenerator;
27//!
28//! let mut idgen = SnowflakeIdGenerator::new(1, 1).unwrap();
29//! let id = idgen.generate().unwrap();
30//! assert!(id > 0);
31//! ```
32//!
33//! ## Custom layout
34//!
35//! ```rust
36//! use snowflake_gen::{BitLayout, SnowflakeIdGenerator};
37//!
38//! // 10 sequence bits → 1 023 IDs/ms, 8 machine + 7 node bits
39//! let layout = BitLayout::new(38, 8, 7, 10).unwrap();
40//! let mut idgen = SnowflakeIdGenerator::with_layout(1, 1, layout).unwrap();
41//! let id = idgen.generate().unwrap();
42//! assert!(id > 0);
43//! ```
44
45pub mod bucket;
46pub mod error;
47pub mod generator;
48pub mod global;
49pub mod layout;
50pub(crate) mod utils;
51
52pub use bucket::SnowflakeIdBucket;
53pub use error::SnowflakeError;
54pub use generator::{SnowflakeComponents, SnowflakeIdGenerator};
55pub use global::{init, init_with_epoch, is_initialized, next_id, real_time_next_id};
56pub use layout::BitLayout;
57
58/// Convenience re-exports.
59pub mod prelude {
60    pub use super::{
61        BitLayout, SnowflakeComponents, SnowflakeError, SnowflakeIdBucket, SnowflakeIdGenerator,
62    };
63}