Crates.io | twitter_snowflake |
lib.rs | twitter_snowflake |
version | 1.0.2 |
source | src |
created_at | 2024-09-08 06:22:34.823894 |
updated_at | 2024-12-06 06:07:27.446746 |
description | A lightweight, efficient library that implements Twitter's Snowflake algorithm |
homepage | |
repository | https://github.com/trayvonpan/snowflake/ |
max_upload_size | |
id | 1367799 |
size | 26,779 |
Snowflake is a lightweight, efficient Rust library that implements Twitter's Snowflake algorithm for generating unique, time-based IDs. Designed for distributed systems, it provides a scalable solution to ID generation, ensuring no collisions even across multiple workers. Perfect for building high-throughput, reliable systems.
float-safe
feature ensures that the maximum ID is less than 2^53, making it compatible with floating-point number precision.https://en.wikipedia.org/wiki/Snowflake_ID
The Snowflake algorithm generates IDs based on:
The default bit allocation follows the original Snowflake design but can be customized for your specific needs.
Add Snowflake to your Cargo.toml
:
[dependencies]
twitter_snowflake = "1.0.0"
Then, import it in your Rust code:
use {std::error::Error, twitter_snowflake::Snowflake};
fn main() -> Result<(), Box<dyn Error>> {
let worker_id = 1;
let mut snowflake = Snowflake::new(worker_id)?;
let sfid = snowflake.generate()?;
println!("Snowflake ID: {}", sfid);
Ok(())
}
You can also set a custom config for ID generation:
use {std::error::Error, twitter_snowflake::Snowflake};
fn main() -> Result<(), Box<dyn Error>> {
let worker_id = 1;
let worker_id_bits = 4;
let epoch: u64 = 1609459200000; // 2021-01-01 00:00:00.000 UTC
let mut snowflake = Snowflake::builder()
.with_worker_id_bits(worker_id_bits)
.with_worker_id(worker_id)
.with_epoch(epoch)
.build()?;
let sfid = snowflake.generate()?;
println!("Snowflake ID: {}", sfid);
Ok(())
}
To ensure that the generated IDs are compatible with floating-point numbers, enable the float-safe
feature:
[dependencies]
twitter_snowflake = { version = "1", features = ["float-safe"] }
See all examples.
To run the test suite, use:
cargo test
test bench_builder ... bench: 26 ns/iter (+/- 1)
test bench_generate ... bench: 233 ns/iter (+/- 29)
test bench_new ... bench: 26 ns/iter (+/- 0)
Contributions are welcome! Feel free to submit issues, feature requests, or pull requests.
Snowflake is licensed under the MIT License. See the LICENSE file for more details.