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 constructors and zero-allocation Crockford Base32 codecs for [`Ulid`].
impl Ulid {
    /// Wraps a raw 128-bit integer as a [`Ulid`].
    ///
    /// # Arguments
    ///
    /// - `u128` - Raw 128-bit ULID integer.
    ///
    /// # Returns
    ///
    /// - `Self` - The typed ULID wrapper.
    #[inline(always)]
    pub const fn from_u128(raw: u128) -> Self {
        Self { raw }
    }

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

    /// Constructs a [`Ulid`] from a 48-bit Unix millisecond timestamp and 80-bit random payload.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unix timestamp in milliseconds (masked to 48 bits).
    /// - `u128` - 80-bit randomness payload (masked to lower 80 bits).
    ///
    /// # Returns
    ///
    /// - `Self` - Composed ULID.
    #[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,
        }
    }

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

    /// Returns the 80-bit random/monotonic payload component.
    ///
    /// # Returns
    ///
    /// - `u128` - Lower 80 bits of the ULID.
    #[inline(always)]
    pub const fn random(self) -> u128 {
        self.as_u128() & ((1u128 << 80) - 1)
    }

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

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

    /// Encodes the ULID into a 26-byte ASCII Crockford Base32 stack array with zero heap allocation.
    ///
    /// # Returns
    ///
    /// - `[u8; ULID_STR_LEN]` - Canonical uppercase 26-byte Crockford Base32 array.
    #[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
    }

    /// Parses a 26-character Crockford Base32 ULID string (case-insensitive, `I`/`L`/`O` tolerant).
    ///
    /// # Arguments
    ///
    /// - `&str` - The 26-character ULID string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IdError>` - The parsed ULID or an error on invalid length, character, or overflow.
    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 })
    }
}

/// Formats [`Ulid`] as a 26-character uppercase Crockford Base32 string.
impl fmt::Display for Ulid {
    /// Writes the canonical 26-character ULID string 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; ULID_STR_LEN] = self.encode_stack();
        let text: &str = from_utf8(&buf).unwrap_or_default();
        f.write_str(text)
    }
}

/// Parses a Crockford Base32 string into a [`Ulid`].
impl FromStr for Ulid {
    type Err = IdError;

    /// Parses a 26-character ULID string.
    ///
    /// # Arguments
    ///
    /// - `&str` - Input ULID text.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed ULID or error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Default construction for [`UlidGenerator`].
impl Default for UlidGenerator {
    /// Creates a new [`UlidGenerator`] seeded from wall-clock entropy and stack address.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready lock-free ULID generator.
    fn default() -> Self {
        Self::new()
    }
}

/// Lock-free monotonic generation methods for [`UlidGenerator`].
impl UlidGenerator {
    /// Creates a new lock-free [`UlidGenerator`] seeded from system time and instance address.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready lock-free ULID generator.
    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)))
    }

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

    /// Generates the next strictly monotonic [`Ulid`] using the current system clock.
    ///
    /// # Returns
    ///
    /// - `Ulid` - A unique, monotonically increasing ULID.
    #[inline(always)]
    pub fn next_ulid(&self) -> Ulid {
        self.next_ulid_at(current_unix_ms())
    }

    /// Generates the next strictly monotonic [`Ulid`] at an explicit Unix millisecond timestamp.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unix timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Ulid` - A unique, monotonically increasing ULID.
    #[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,
                }
            }
        }
    }
}