use super::*;
impl UuidV7 {
#[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 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 timestamp_ms(self) -> u64 {
(self.as_u128() >> 80) as u64
}
#[inline(always)]
pub const fn version(self) -> u8 {
((self.as_u128() >> 76) & 0x0f) as u8
}
#[inline(always)]
pub const fn sequence(self) -> u16 {
((self.as_u128() >> 64) & 0x0fff) as u16
}
#[inline(always)]
pub const fn encode_stack(self) -> [u8; UUID_STR_LEN] {
let bytes: [u8; 16] = self.to_bytes();
let mut out: [u8; UUID_STR_LEN] = [b'-'; UUID_STR_LEN];
let mut src: usize = 0;
let mut dst: usize = 0;
while src < 16 {
if src == 4 || src == 6 || src == 8 || src == 10 {
dst += 1;
}
let b: u8 = bytes[src];
out[dst] = HEX_LOWER[(b >> 4) as usize];
out[dst + 1] = HEX_LOWER[(b & 0x0f) as usize];
dst += 2;
src += 1;
}
out
}
pub fn parse(input: &str) -> Result<Self, IdError> {
let bytes: &[u8] = input.as_bytes();
let hyphenated: bool = match bytes.len() {
36 => true,
32 => false,
_ => return Err(IdError::InvalidUuidFormat),
};
if hyphenated
&& (bytes[8] != b'-' || bytes[13] != b'-' || bytes[18] != b'-' || bytes[23] != b'-')
{
return Err(IdError::InvalidUuidFormat);
}
let mut acc: u128 = 0;
for (idx, &ch) in bytes.iter().enumerate() {
if hyphenated && (idx == 8 || idx == 13 || idx == 18 || idx == 23) {
continue;
}
let nibble: u8 = match ch {
b'0'..=b'9' => ch - b'0',
b'a'..=b'f' => ch - b'a' + 10,
b'A'..=b'F' => ch - b'A' + 10,
_ => return Err(IdError::InvalidUuidFormat),
};
acc = (acc << 4) | u128::from(nibble);
}
Ok(Self { raw: acc })
}
}
impl fmt::Display for UuidV7 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let buf: [u8; UUID_STR_LEN] = self.encode_stack();
let text: &str = from_utf8(&buf).unwrap_or_default();
f.write_str(text)
}
}
impl FromStr for UuidV7 {
type Err = IdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
impl Default for UuidV7Generator {
fn default() -> Self {
Self::new()
}
}
impl UuidV7Generator {
pub fn new() -> Self {
let now_nanos: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d.as_nanos() as u64,
Err(_) => 0x1319_8a2e_0370_7344,
};
let stack_addr: u64 = (&now_nanos as *const u64) as usize as u64;
Self::with_seed(splitmix64(now_nanos ^ stack_addr.rotate_left(23)))
}
pub fn with_seed(seed: u64) -> Self {
Self {
state: AtomicU64::new(0),
seed: AtomicU64::new(seed),
}
}
#[inline(always)]
pub fn next_uuid(&self) -> UuidV7 {
self.next_uuid_at(current_unix_ms())
}
#[inline(always)]
pub fn next_uuid_at(&self, now_unix_ms: u64) -> UuidV7 {
let Self { state, seed } = self;
let ts_48: u64 = now_unix_ms & ULID_TS_MASK_48;
let mut observed: u64 = state.load(Ordering::Relaxed);
let (final_ts, seq): (u64, u64) = loop {
let last_ts: u64 = observed >> 12;
let last_seq: u64 = observed & UUID_V7_SEQ_MASK;
let (next_ts, next_seq): (u64, u64) = if ts_48 > last_ts {
(ts_48, 0)
} else if last_seq < UUID_V7_SEQ_MASK {
(last_ts, last_seq + 1)
} else {
((last_ts + 1) & ULID_TS_MASK_48, 0)
};
let packed: u64 = (next_ts << 12) | next_seq;
match state.compare_exchange_weak(observed, packed, Ordering::AcqRel, Ordering::Relaxed)
{
Ok(_) => break (next_ts, next_seq),
Err(actual) => observed = actual,
}
};
let hi: u64 = ((final_ts << 16) | UUID_V7_VERSION_NIBBLE) | seq;
let entropy: u64 =
splitmix64(seed.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed) ^ hi);
let lo: u64 = UUID_VARIANT_RFC4122_HI | (entropy & UUID_RAND_B_MASK);
UuidV7::from_u128((u128::from(hi) << 64) | u128::from(lo))
}
}