use super::*;
impl Ulid {
#[inline(always)]
pub const fn from_u128(raw: u128) -> Self {
Self { raw }
}
#[inline(always)]
pub const fn as_u128(self) -> u128 {
let Self { raw } = self;
raw
}
#[inline(always)]
pub const fn from_parts(timestamp_ms: u64, random_80: u128) -> Self {
let ts: u128 = (timestamp_ms & ULID_TS_MASK_48) as u128;
let rnd: u128 = random_80 & ((1u128 << 80) - 1);
Self {
raw: (ts << 80) | rnd,
}
}
#[inline(always)]
pub const fn timestamp_ms(self) -> u64 {
(self.as_u128() >> 80) as u64
}
#[inline(always)]
pub const fn random(self) -> u128 {
self.as_u128() & ((1u128 << 80) - 1)
}
#[inline(always)]
pub const fn to_bytes(self) -> [u8; 16] {
self.as_u128().to_be_bytes()
}
#[inline(always)]
pub const fn from_bytes(bytes: [u8; 16]) -> Self {
Self {
raw: u128::from_be_bytes(bytes),
}
}
#[inline(always)]
pub const fn encode_stack(self) -> [u8; ULID_STR_LEN] {
let mut out: [u8; ULID_STR_LEN] = [b'0'; ULID_STR_LEN];
let mut val: u128 = self.as_u128();
let mut idx: usize = ULID_STR_LEN;
while idx > 0 {
idx -= 1;
out[idx] = CROCKFORD_ENCODE[(val & 0x1f) as usize];
val >>= 5;
}
out
}
pub fn parse(input: &str) -> Result<Self, IdError> {
let bytes: &[u8] = input.as_bytes();
if bytes.len() != ULID_STR_LEN {
return Err(IdError::InvalidUlidLength);
}
let first: u8 = CROCKFORD_DECODE[bytes[0] as usize];
if first == 0xff {
return Err(IdError::InvalidUlidCharacter);
}
if first > 7 {
return Err(IdError::UlidOverflow);
}
let mut acc: u128 = u128::from(first);
let mut idx: usize = 1;
while idx < ULID_STR_LEN {
let digit: u8 = CROCKFORD_DECODE[bytes[idx] as usize];
if digit == 0xff {
return Err(IdError::InvalidUlidCharacter);
}
acc = (acc << 5) | u128::from(digit);
idx += 1;
}
Ok(Self { raw: acc })
}
}
impl fmt::Display for Ulid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let buf: [u8; ULID_STR_LEN] = self.encode_stack();
let text: &str = from_utf8(&buf).unwrap_or_default();
f.write_str(text)
}
}
impl FromStr for Ulid {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
impl Default for UlidGenerator {
fn default() -> Self {
Self::new()
}
}
impl UlidGenerator {
pub fn new() -> Self {
let now_nanos: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d.as_nanos() as u64,
Err(_) => 0x243f_6a88_85a3_08d3,
};
let stack_addr: u64 = (&now_nanos as *const u64) as usize as u64;
Self::with_seed(splitmix64(now_nanos ^ stack_addr.rotate_left(17)))
}
pub fn with_seed(seed: u64) -> Self {
Self {
hi_state: AtomicU64::new(0),
lo_state: AtomicU64::new(0),
seed: AtomicU64::new(seed),
}
}
#[inline(always)]
pub fn next_ulid(&self) -> Ulid {
self.next_ulid_at(current_unix_ms())
}
#[inline(always)]
pub fn next_ulid_at(&self, now_unix_ms: u64) -> Ulid {
let Self {
hi_state,
lo_state,
seed,
} = self;
let ts_48: u64 = now_unix_ms & ULID_TS_MASK_48;
let mut observed_hi: u64 = hi_state.load(Ordering::Relaxed);
loop {
let last_ts: u64 = observed_hi >> 16;
if ts_48 > last_ts {
let s1: u64 = seed.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed);
let r_lo: u64 = splitmix64(s1 ^ ts_48);
let r_hi: u64 = splitmix64(r_lo) & 0x7fff;
let new_hi: u64 = (ts_48 << 16) | r_hi;
match hi_state.compare_exchange_weak(
observed_hi,
new_hi,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => {
lo_state.store(r_lo, Ordering::Release);
let raw: u128 = (u128::from(new_hi) << 64) | u128::from(r_lo);
return Ulid::from_u128(raw);
}
Err(actual) => observed_hi = actual,
}
} else {
let prev_lo: u64 = lo_state.fetch_add(1, Ordering::AcqRel);
let next_lo: u64 = prev_lo.wrapping_add(1);
if next_lo != 0 {
let current_hi: u64 = hi_state.load(Ordering::Acquire);
let raw: u128 = (u128::from(current_hi) << 64) | u128::from(next_lo);
return Ulid::from_u128(raw);
}
let next_hi_val: u64 = observed_hi.wrapping_add(1);
let next_ts: u64 = (next_hi_val >> 16) & ULID_TS_MASK_48;
let next_r_hi: u64 = next_hi_val & ULID_RAND_HI_MASK_16;
let packed: u64 = (next_ts << 16) | next_r_hi;
match hi_state.compare_exchange_weak(
observed_hi,
packed,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => {
let raw: u128 = (u128::from(packed) << 64) | u128::from(next_lo);
return Ulid::from_u128(raw);
}
Err(actual) => observed_hi = actual,
}
}
}
}
}