#snowflake #generation #ids #generate #type #api

snowflaked

A crate for creating and working with snowflake ids

13 releases (4 stable)

1.0.3 Feb 24, 2024
1.0.2 May 24, 2023
1.0.1 Apr 26, 2023
1.0.0 Feb 15, 2023
0.1.2 Jun 14, 2022

#559 in Rust patterns

Download history 143/week @ 2024-08-21 219/week @ 2024-08-28 156/week @ 2024-09-04 191/week @ 2024-09-11 93/week @ 2024-09-18 143/week @ 2024-09-25 112/week @ 2024-10-02 135/week @ 2024-10-09 643/week @ 2024-10-16 565/week @ 2024-10-23 829/week @ 2024-10-30 325/week @ 2024-11-06 496/week @ 2024-11-13 413/week @ 2024-11-20 396/week @ 2024-11-27 483/week @ 2024-12-04

1,916 downloads per month
Used in 5 crates

MIT/Apache

41KB
737 lines

Snowflaked

Crates.io Docs.rs

A crate for creating and working with snowflake ids.

Usage

Add snowflaked to your Cargo.toml:

snowflaked = "1.0.0"

This crate provides APIs for generating new snowflake ids and defining custom snowflake types.

Snowflake Generation

Use the Generator type to create new snowflake ids:

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):

use snowflaked::sync::Generator;

static GENERATOR: Generator = Generator::new(0);

fn generate_id() -> u64 {
    GENERATOR.generate()
}

Using custom snowflake types

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:

use snowflaked::Snowflake;

struct UserId(u64);

impl Snowflake for UserId {
    fn from_parts(timestamp: u64, instance: u64, sequence: u64) -> Self {
        Self(u64::from_parts(timestamp, instance, sequence))
    }

    fn timestamp(&self) -> u64 {
        self.0.timestamp()
    }

    fn instance(&self) -> u64 {
        self.0.instance()
    }

    fn sequence(&self) -> u64 {
        self.0.sequence()
    }
}

License

Licensed under either

Dependencies

~0–26MB
~328K SLoC