Crate snowflaked

source ·
Expand description

A crate for working with snowflake ids.

Most notably this provides Snowflake for working with custom snowflake ids and Generator creating new snowflake ids.

§Snowflake structure

A snowflake id is a 64-bit integer generated using the current timestamp in milliseconds, a constant instance and a sequence number.

0               1               2                 3               4                 5               6               7
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                       Timestamp                                       |     Instance      |       Sequence      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  • The Snowflake implementation for u64 uses 42 bits for the timestamp, 10 bits for the instance and 12 bits for the sequence.
  • The Snowflake implementation for i64 uses 41 bits for the timestamp, 10 bits for the instance and 12 bits for the sequence.

§Timestamp overflow

Since the timestamp range is limited it is possible for the timestamp to overflow and wrap around after a specific date. For the by-default configured UNIX epoch these dates are:

  • For i64: Sep 07 2039 15:47:35 (2039-09-07T15:47:35Z)
  • For u64: May 15 2109 07:35:11 (2109-05-15T07:35:11Z)

If overflowing after these dates is not acceptable for you Builder::epoch allows configuring a custom epoch.

§Custom snowflake ids

Custom snowflake ids can be created with the Snowflake trait.

§Example

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()
    }
}

§Generating snowflake ids

Generator can be used to generate unique snowflake ids. Additionally sync::Generator can be used when working with multiple threads (requires the sync feature).

§Example

use snowflaked::Generator;

let mut generator = Generator::new(0);
let id: u64 = generator.generate();

Generator::generate can also generate custom snowflake ids:


use snowflaked::Generator;

let mut generator = Generator::new(0);
let id: UserId = generator.generate();

For more details on sync::Generator see the sync module.

§Feature flags

sync: Enables the sync module.

Modules§

  • syncsync
    Thread-safe Snowflake Generator

Structs§

Traits§

  • A type that can be used as a snowflake id.