3 releases
Uses old Rust 2015
0.2.2 | Oct 1, 2016 |
---|---|
0.2.1 | Aug 11, 2016 |
0.2.0 | Aug 11, 2016 |
#8 in #flake
8KB
145 lines
Flaken
A 64bit snowflake like id generator, encoder, and decoder which allows setting the bitwidths of each portion of the 64 bit encoded id.
let mut flake = Flaken::default().node(10).epoch(0).bitwidths(48, 12);
let id = flake.next();
let (timestamp, node, seq) = flake.decode(id);
assert!(timestamp > 0);
assert_eq!(node, 10);
assert_eq!(seq, 0);
assert_eq!(flake.encode(timestamp, node, seq), id);
lib.rs
:
Flaken is a configurable Snowflake ID generator where the epoch and bitwidths may be adjusted to your liking from the defaults. ID generation from an instantiated generator will always increase in value. If a ID generator is created after a clock moves back from previously created IDs conflicting ID values are possible, otherwise clock changes do not affect ID generation.
Encode and decode example
use std::time;
use flaken::Flaken;
let ts = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap();
let ts_ms = ts.as_secs()*1000 + (ts.subsec_nanos() as u64)/1000000;
let mf = Flaken::default();
let id = mf.encode(ts_ms, 10, 100);
let (ts0, node0, seq0) = mf.decode(id);
assert_eq!(ts0, ts_ms);
assert_eq!(node0, 10);
assert_eq!(seq0, 100);
ID generation example
use flaken::Flaken;
let mut flake = Flaken::default().node(1).epoch(0).bitwidths(40, 10);
let id0 = flake.next();
let (ts0, node0, seq0) = flake.decode(id0);
assert!(ts0 > 0);
assert_eq!(node0, 1);
assert_eq!(seq0, 0);
assert_eq!(flake.encode(ts0, node0, seq0), id0);