A crate for creating and working with snowflake ids.
Add snowflaked
to your Cargo.toml
:
toml
snowflaked = "0.1.5"
This crate provides APIs for generating new snowflake ids and defining custom snowflake types.
Use the Generator
type to create new snowflake ids:
```rust use snowflaked::Generator;
let mut generator = Generator::new(0); let id: u64 = generator.generate(); ```
Or use the thread-safe sync::Generator
type (requires the optional sync
feature):
```rust use snowflaked::sync::Generator;
// Note that we can't (yet) panic in a const context, so we use new_unchecked
.
static GENERATOR: Generator = Generator::new_unchecked(0);
fn generate_id() -> u64 { GENERATOR.generate() } ```
Custom snowflake types can be defined with the Snowflake
trait. This trait is currently
implemented for u64
and i64
and can be used to define your custom types:
```rust use snowflaked::Snowflake;
struct UserId(u64);
impl Snowflake for UserId { fn fromparts(timestamp: u64, instance: u64, sequence: u64) -> Self { Self(u64::fromparts(timestamp, instance, sequence)) }
fn timestamp(&self) -> u64 {
self.0.timestamp()
}
fn instance(&self) -> u64 {
self.0.instance()
}
fn sequence(&self) -> u64 {
self.0.sequence()
}
} ```
Licensed under either - MIT License or - Apache License, Version 2.0 at your option.