11 releases (4 breaking)

0.5.6 Jan 13, 2020
0.5.5 Jan 9, 2020
0.4.0 Jan 6, 2020
0.3.0 Jan 6, 2020
0.1.0 Jan 6, 2020

#11 in #uid

MIT license

5KB
69 lines

snowflake-rust

Kubernetes "twitter" snowflakes.this is not release version,please do not use in production.

By default the original Twitter snowflake format defines:

  • 35 bits are used to store a custom epoch with 10 millisecond precision
  • 16 bits are used to store low 16 bit from ip address
  • 12 bits are used to store a sequence number

Usage

Add this to your Cargo.toml:


[dependencies]
snowflake-rust = "0.5.6"

and this to your crate root:


use snowflake_rust;

Example


use snowflake_rust::Snowflake;

fn main() {
    let mut s = Snowflake::kubernetes();
    let id = s.generate().unwrap();
    println!("{:?}", id)
}

// singleton example
use snowflake_rust::Snowflake;

fn main() {
    let id = id().unwrap();
    println!("{:?}", id)
}

pub fn id() -> Option<i64> {
    let instance = get_instance();
    let mut sf = instance.lock().unwrap();
    sf.generate()
}

fn get_instance() -> Arc<Mutex<Snowflake>> {

    static mut SINGLETON: Option<Arc<Mutex<Snowflake>>> = None;

    unsafe {
        SINGLETON.get_or_insert_with( || {
            Arc::new(Mutex::new(Snowflake::kubernetes()))
        }).clone()
    }
}

Dependencies

~1MB
~18K SLoC