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::*;

/// Accessors and codecs for [`SnowflakeId`].
impl SnowflakeId {
    /// Wraps a raw 64-bit integer as a [`SnowflakeId`].
    ///
    /// # Arguments
    ///
    /// - `u64` - The raw 64-bit Snowflake integer.
    ///
    /// # Returns
    ///
    /// - `Self` - The typed Snowflake ID wrapper.
    #[inline(always)]
    pub const fn from_u64(raw: u64) -> Self {
        Self { raw }
    }

    /// Extracts the raw 64-bit integer value.
    ///
    /// # Returns
    ///
    /// - `u64` - The underlying 64-bit value.
    #[inline(always)]
    pub const fn as_u64(self) -> u64 {
        let Self { raw } = self;
        raw
    }

    /// Composes a [`SnowflakeId`] directly from its fields.
    ///
    /// # Arguments
    ///
    /// - `u64` - Milliseconds elapsed since the generator's custom epoch (masked to 41 bits).
    /// - `u16` - 10-bit node identifier (`0..=1023`).
    /// - `u16` - 12-bit sequence counter (`0..=4095`).
    ///
    /// # Returns
    ///
    /// - `Self` - The composed Snowflake identifier.
    #[inline(always)]
    pub const fn from_parts(relative_ms: u64, node_id: u16, sequence: u16) -> Self {
        let raw: u64 = ((relative_ms & TIMESTAMP_MASK) << TIMESTAMP_SHIFT)
            | ((node_id as u64 & NODE_MASK) << SEQUENCE_BITS)
            | (sequence as u64 & SEQUENCE_MASK);
        Self { raw }
    }

    /// Returns the 41-bit timestamp offset in milliseconds relative to the custom epoch.
    ///
    /// # Returns
    ///
    /// - `u64` - Elapsed milliseconds since custom epoch.
    #[inline(always)]
    pub const fn timestamp_offset_ms(self) -> u64 {
        (self.as_u64() >> TIMESTAMP_SHIFT) & TIMESTAMP_MASK
    }

    /// Returns the Unix timestamp in milliseconds given the custom epoch.
    ///
    /// # Arguments
    ///
    /// - `u64` - The custom epoch in Unix milliseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - The absolute Unix timestamp in milliseconds.
    #[inline(always)]
    pub const fn timestamp_ms(self, epoch_ms: u64) -> u64 {
        epoch_ms.saturating_add(self.timestamp_offset_ms())
    }

    /// Returns the 10-bit node identifier embedded in the Snowflake ID.
    ///
    /// # Returns
    ///
    /// - `u16` - Node identifier in `0..=1023`.
    #[inline(always)]
    pub const fn node_id(self) -> u16 {
        ((self.as_u64() >> SEQUENCE_BITS) & NODE_MASK) as u16
    }

    /// Returns the 12-bit sequence counter embedded in the Snowflake ID.
    ///
    /// # Returns
    ///
    /// - `u16` - Sequence number in `0..=4095`.
    #[inline(always)]
    pub const fn sequence(self) -> u16 {
        (self.as_u64() & SEQUENCE_MASK) as u16
    }

    /// Encodes the Snowflake ID into a compact Base62 string.
    ///
    /// # Returns
    ///
    /// - `String` - Base62 textual encoding (1 to 11 ASCII characters).
    pub fn to_base62(self) -> String {
        let mut value: u64 = self.as_u64();
        if value == 0 {
            return String::from("0");
        }
        let mut buf: [u8; BASE62_STACK_CAP] = [0u8; BASE62_STACK_CAP];
        let mut idx: usize = BASE62_STACK_CAP;
        while value > 0 {
            idx -= 1;
            let rem: usize = (value % 62) as usize;
            buf[idx] = BASE62_ALPHABET[rem];
            value /= 62;
        }
        String::from_utf8_lossy(&buf[idx..]).into_owned()
    }

    /// Decodes a Base62 string back into a [`SnowflakeId`].
    ///
    /// # Arguments
    ///
    /// - `&str` - The Base62 encoded string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IdError>` - The decoded Snowflake ID or parse error.
    pub fn from_base62(input: &str) -> Result<Self, IdError> {
        if input.is_empty() || input.len() > BASE62_STACK_CAP {
            return Err(IdError::InvalidSnowflakeString);
        }
        let mut acc: u64 = 0;
        for &byte in input.as_bytes() {
            let digit: u64 = match byte {
                b'0'..=b'9' => u64::from(byte - b'0'),
                b'A'..=b'Z' => u64::from(byte - b'A') + 10,
                b'a'..=b'z' => u64::from(byte - b'a') + 36,
                _ => return Err(IdError::InvalidSnowflakeString),
            };
            acc = acc
                .checked_mul(62)
                .and_then(|v: u64| v.checked_add(digit))
                .ok_or(IdError::InvalidSnowflakeString)?;
        }
        Ok(Self::from_u64(acc))
    }
}

/// Converts [`SnowflakeId`] into `u64`.
impl From<SnowflakeId> for u64 {
    /// Extracts the underlying 64-bit value.
    ///
    /// # Arguments
    ///
    /// - `SnowflakeId` - Source Snowflake identifier.
    ///
    /// # Returns
    ///
    /// - `u64` - Underlying 64-bit integer.
    #[inline(always)]
    fn from(id: SnowflakeId) -> Self {
        id.as_u64()
    }
}

/// Converts `u64` into [`SnowflakeId`].
impl From<u64> for SnowflakeId {
    /// Wraps a raw 64-bit integer.
    ///
    /// # Arguments
    ///
    /// - `u64` - Raw 64-bit integer.
    ///
    /// # Returns
    ///
    /// - `Self` - Typed Snowflake identifier.
    #[inline(always)]
    fn from(raw: u64) -> Self {
        Self::from_u64(raw)
    }
}

/// Formats [`SnowflakeId`] as a base-10 integer string.
impl fmt::Display for SnowflakeId {
    /// Writes the decimal representation of the Snowflake ID.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - Destination formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_u64())
    }
}

/// Parses a base-10 string into a [`SnowflakeId`].
impl FromStr for SnowflakeId {
    type Err = IdError;

    /// Parses a decimal string into a [`SnowflakeId`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Decimal string representation.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed Snowflake ID or error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let raw: u64 = s
            .parse::<u64>()
            .map_err(|_| IdError::InvalidSnowflakeString)?;
        Ok(Self::from_u64(raw))
    }
}

/// Lock-free ID generation methods for [`SnowflakeGenerator`].
impl SnowflakeGenerator {
    /// Creates a new generator with the default custom epoch (`2020-01-01T00:00:00Z`).
    ///
    /// # Arguments
    ///
    /// - `u16` - Unique node identifier in `0..=1023`.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IdError>` - The ready generator or `IdError::NodeIdOutOfRange`.
    pub fn new(node_id: u16) -> Result<Self, IdError> {
        Self::with_epoch(node_id, DEFAULT_SNOWFLAKE_EPOCH_MS)
    }

    /// Creates a new generator with an explicit custom epoch in Unix milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u16` - Unique node identifier in `0..=1023`.
    /// - `u64` - Custom epoch in Unix milliseconds.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IdError>` - The ready generator or `IdError::NodeIdOutOfRange`.
    pub fn with_epoch(node_id: u16, epoch_ms: u64) -> Result<Self, IdError> {
        if node_id > MAX_NODE_ID {
            return Err(IdError::NodeIdOutOfRange);
        }
        Ok(Self {
            epoch_ms,
            node_id,
            state: AtomicU64::new(0),
        })
    }

    /// Returns the configured custom epoch in Unix milliseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Custom epoch timestamp in milliseconds.
    #[inline(always)]
    pub fn get_epoch_ms(&self) -> u64 {
        let Self { epoch_ms, .. } = self;
        *epoch_ms
    }

    /// Returns the configured 10-bit node identifier.
    ///
    /// # Returns
    ///
    /// - `u16` - Node identifier (`0..=1023`).
    #[inline(always)]
    pub fn get_node_id(&self) -> u16 {
        let Self { node_id, .. } = self;
        *node_id
    }

    /// Generates the next strictly monotonic 64-bit Snowflake ID using wall-clock time.
    ///
    /// Uses a single lock-free `AtomicU64` compare-exchange loop; clock rollbacks or
    /// intra-millisecond sequence exhaustion advance the logical millisecond monotonically
    /// without blocking or panicking.
    ///
    /// # Returns
    ///
    /// - `SnowflakeId` - A unique, strictly increasing Snowflake identifier.
    #[inline(always)]
    pub fn next_id(&self) -> SnowflakeId {
        self.next_id_at(current_unix_ms())
    }

    /// Generates the next strictly monotonic 64-bit Snowflake ID at an explicit Unix timestamp.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current Unix timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// - `SnowflakeId` - A unique, strictly increasing Snowflake identifier.
    #[inline(always)]
    pub fn next_id_at(&self, now_unix_ms: u64) -> SnowflakeId {
        let Self {
            epoch_ms,
            node_id,
            state,
        } = self;
        let rel_now: u64 = now_unix_ms.saturating_sub(*epoch_ms) & TIMESTAMP_MASK;
        let mut observed: u64 = state.load(Ordering::Relaxed);
        loop {
            let last_ts: u64 = observed >> SEQUENCE_BITS;
            let last_seq: u64 = observed & SEQUENCE_MASK;
            let (next_ts, next_seq): (u64, u64) = if rel_now > last_ts {
                (rel_now, 0)
            } else if last_seq < SEQUENCE_MASK {
                (last_ts, last_seq + 1)
            } else {
                ((last_ts + 1) & TIMESTAMP_MASK, 0)
            };
            let packed: u64 = (next_ts << SEQUENCE_BITS) | next_seq;
            match state.compare_exchange_weak(observed, packed, Ordering::AcqRel, Ordering::Relaxed)
            {
                Ok(_) => {
                    return SnowflakeId::from_parts(next_ts, *node_id, next_seq as u16);
                }
                Err(actual) => observed = actual,
            }
        }
    }
}