Crates.io | hyperflake-rs |
lib.rs | hyperflake-rs |
version | 0.1.1 |
source | src |
created_at | 2024-09-10 05:30:47.095344 |
updated_at | 2024-09-10 08:06:48.940545 |
description | A simple and lightweight Rust crate library to generate unique snowflake like IDs starting from beginning of the 21th century. |
homepage | |
repository | https://github.com/bravo68web/hyperflake-rs |
max_upload_size | |
id | 1370074 |
size | 10,005 |
hyperflake-rs
is a Rust crate library for generating unique and distributed IDs that are suitable for use as primary keys in distributed systems.
It generates 64-bit IDs (in string format) that are composed of a timestamp, a worker ID, and a sequence number. These IDs are based on Twitter's Snowflake ID generation algorithm.
You can install hyperflake-rs
using cargo by adding it to your Cargo.toml
file:
[dependencies]
hyperflake-rs = "0.1.1"
The SnowflakeId instance has the following methods:
generate()
: Generates a unique ID in string format.decode()
: Retrive timestamp when the ID was generated.Here's an example of how to use hyperflake-rs
:
use hyperflake_rs::snowflake;
fn main() {
let mut snowflake_id = snowflake::SnowflakeId::new();
for _ in 0..1000 {
let id = snowflake_id.generate();
println!("Snowflake ID: {}", id); // 3268462822371098624
}
}
This will generate a unique ID in string format.
You can validate IDs generated by hyperflake
using the decode()
method:
use hyperflake_rs::snowflake;
fn main() {
let mut snowflake_id = snowflake::SnowflakeId::new();
let id = snowflake_id.generate();
println!("Snowflake ID: {}", id); // 3268462822371098624
let ts = snowflake_id.decode(&id);
println!("Decoded Snowflake ID: {:?}", ts); // 1725947061956
}
This will return the timestamp when the ID was generated.
Also you can head to https://hyperflake-validator-ui.vercel.app to validate your IDs using a simple Web UI.
The SnowflakeId instance throws an error if the clock moves backwards, i.e., if the current timestamp is less than the last timestamp.
This can happen if the system clock is adjusted manually or if the system clock drifts significantly.
If this happens, the library throws an Error with the message Clock is moving backwards!
.
Here's an example of how to generate 10 IDs:
use hyperflake_rs::snowflake;
fn main() {
let mut snowflake_id = snowflake::SnowflakeId::new();
for _ in 0..10 {
let id = snowflake_id.generate();
println!("Snowflake ID: {}", id);
}
}
If you encounter any problems feel free to open an issue on GitHub.