Crates.io | snowflake-ng |
lib.rs | snowflake-ng |
version | 0.1.5 |
source | src |
created_at | 2024-10-25 07:53:49.955228 |
updated_at | 2024-10-30 03:10:20.212463 |
description | Dead easy and high performance `snowflake` implemented in Rust. |
homepage | |
repository | https://github.com/Krysztal112233/snowflake-ng |
max_upload_size | |
id | 1422188 |
size | 62,957 |
Dead easy and high performance snowflake
implemented in Rust.
This crate only implemented Twitter(formally X)'s snowflake.
ng
or next-generation
?Actually, this crate doesn't next-generation enough.
The use of -ng
is simply to distinguish between the two existing implementations:
Maybe lock-free can be a feature of next-generation
:)
snowflake
crate is completely unmaintained and it's even using Rust 2018 Edition.snowflake-rs
(rs-snowflake
at crates.io) doesn't support async/await.What we need to know is that only 4096 Snowflake ID
can be generated in a millisecond in the standard implementation.
If we assigned out the sequence(from 0 to 4095), we have to waiting for one millisecond. If we doesn't use the asynchronous, we have to sleep for one millisecond!
But at the same time, this crate also provided synchronous function, but you have to enable sync
feature:
snowflake-ng = { version = "0.1", features = ["sync"]}
YES!
Inner data use Atomic*
type to keep lock-free and atomic update.
So you can share SnowflakeGenerator
between threads safety, or make a global static one!
Firstly, add this crate to your Cargo.toml
:
snowflake-ng = "0.1"
This crate provide some extra TimeProvider
implementation based different crate:
time
chrono
And provide basic implementation based standard library: std::time::SystemTime
If you want to accelerate your build time, you can disable all the features to avoid introduce extra build dependencies.
After add to Cargo.toml
, you can made your own SnowflakeGenerator
:
let generator = SnowflakeGenerator::default();
Then, start your generation:
generator.assign_sync(&STD_PROVIDER)
You can wrap your own SnowflakeGenerator
(I called PersistedSnowflakeGenerator
):
let generator = PersistedSnowflakeGenerator::new(Arc::new(SnowflakeGenerator::default()), Arc::new(StdProvider));
generator.assign().await
Please see example for more example such as async support and custom identifier.