atomic-snowflake 11.1.0

Zero-dependency lock-free monotonic 64-bit Snowflake ID, 128-bit ULID, and RFC 9562 UUIDv7 generators with stack-buffered Crockford Base32 and hyphenated hex codecs.
Documentation
use super::*;

/// Core accessors and zero-allocation hex codecs for [`UuidV7`].
impl UuidV7 {
    /// Wraps a raw 128-bit integer as a [`UuidV7`].
    ///
    /// # Arguments
    ///
    /// - `u128` - Raw 128-bit UUID value.
    ///
    /// # Returns
    ///
    /// - `Self` - Typed UUIDv7 wrapper.
    #[inline(always)]
    pub const fn from_u128(raw: u128) -> Self {
        Self { raw }
    }

    /// Returns the raw 128-bit integer value.
    ///
    /// # Returns
    ///
    /// - `u128` - Underlying 128-bit value.
    #[inline(always)]
    pub const fn as_u128(self) -> u128 {
        let Self { raw } = self;
        raw
    }

    /// Returns the 16-byte big-endian representation.
    ///
    /// # Returns
    ///
    /// - `[u8; 16]` - Big-endian UUID bytes.
    #[inline(always)]
    pub const fn to_bytes(self) -> [u8; 16] {
        self.as_u128().to_be_bytes()
    }

    /// Reconstructs a [`UuidV7`] from a 16-byte big-endian byte array.
    ///
    /// # Arguments
    ///
    /// - `[u8; 16]` - Big-endian UUID bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Reconstructed UUIDv7.
    #[inline(always)]
    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
        Self {
            raw: u128::from_be_bytes(bytes),
        }
    }

    /// Returns the embedded 48-bit Unix timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Unix timestamp in milliseconds.
    #[inline(always)]
    pub const fn timestamp_ms(self) -> u64 {
        (self.as_u128() >> 80) as u64
    }

    /// Returns the 4-bit UUID version nibble (`7` for valid RFC 9562 UUIDv7).
    ///
    /// # Returns
    ///
    /// - `u8` - Version field (`0..=15`).
    #[inline(always)]
    pub const fn version(self) -> u8 {
        ((self.as_u128() >> 76) & 0x0f) as u8
    }

    /// Returns the 12-bit monotonic `rand_a` sequence counter.
    ///
    /// # Returns
    ///
    /// - `u16` - 12-bit sub-millisecond counter (`0..=4095`).
    #[inline(always)]
    pub const fn sequence(self) -> u16 {
        ((self.as_u128() >> 64) & 0x0fff) as u16
    }

    /// Encodes the UUIDv7 into a canonical 36-byte hyphenated lowercase ASCII stack buffer.
    ///
    /// # Returns
    ///
    /// - `[u8; UUID_STR_LEN]` - Canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` bytes.
    #[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
    }

    /// Parses either a 36-character hyphenated UUID or a 32-character compact hex UUID.
    ///
    /// # Arguments
    ///
    /// - `&str` - Input UUID text.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IdError>` - Parsed UUIDv7 or format error.
    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 })
    }
}

/// Formats [`UuidV7`] as canonical lowercase hyphenated text.
impl fmt::Display for UuidV7 {
    /// Writes the 36-character hyphenated UUIDv7 into `f`.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - Destination formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    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)
    }
}

/// Parses a UUID string into [`UuidV7`].
impl FromStr for UuidV7 {
    type Err = IdError;

    /// Parses a hyphenated or compact hex UUID string.
    ///
    /// # Arguments
    ///
    /// - `&str` - UUID string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed UUIDv7 or error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Default construction for [`UuidV7Generator`].
impl Default for UuidV7Generator {
    /// Creates a new [`UuidV7Generator`] seeded from wall-clock entropy.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready UUIDv7 generator.
    fn default() -> Self {
        Self::new()
    }
}

/// Lock-free monotonic RFC 9562 UUIDv7 generation methods.
impl UuidV7Generator {
    /// Creates a new [`UuidV7Generator`] seeded from wall-clock time and stack address.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready lock-free UUIDv7 generator.
    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)))
    }

    /// Creates a [`UuidV7Generator`] with an explicit initial 64-bit entropy seed.
    ///
    /// # Arguments
    ///
    /// - `u64` - Initial entropy seed.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready UUIDv7 generator.
    pub fn with_seed(seed: u64) -> Self {
        Self {
            state: AtomicU64::new(0),
            seed: AtomicU64::new(seed),
        }
    }

    /// Generates the next strictly monotonic RFC 9562 [`UuidV7`] using wall-clock time.
    ///
    /// # Returns
    ///
    /// - `UuidV7` - A unique, time-ordered UUIDv7.
    #[inline(always)]
    pub fn next_uuid(&self) -> UuidV7 {
        self.next_uuid_at(current_unix_ms())
    }

    /// Generates the next strictly monotonic RFC 9562 [`UuidV7`] at an explicit Unix timestamp.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unix timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// - `UuidV7` - A unique, time-ordered UUIDv7.
    #[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))
    }
}