LockSnowflakeGenerator

Struct LockSnowflakeGenerator 

Source
pub struct LockSnowflakeGenerator<ID, T>
where ID: SnowflakeId, T: TimeSource<ID::Ty>,
{ /* private fields */ }
Available on crate features snowflake and lock only.
Expand description

A lock-based Snowflake ID generator suitable for multi-threaded environments.

This generator wraps the Snowflake state in an Arc<Mutex<_>>, allowing safe shared use across threads.

§Features

  • ✅ Thread-safe
  • ✅ Safely implement any SnowflakeId layout
  • You’re in a multi-threaded environment
  • Fair access across threads is important
  • Your target doesn’t support atomics.

§See Also

Implementations§

Source§

impl<ID, T> LockSnowflakeGenerator<ID, T>
where ID: SnowflakeId, T: TimeSource<ID::Ty>,

Source

pub fn new(machine_id: ID::Ty, time: T) -> Self

Available on crate features snowflake or ulid only.

Creates a new LockSnowflakeGenerator initialized with the current time and a given machine ID.

This constructor sets the initial timestamp and sequence to zero, and uses the provided time to fetch the current time during ID generation. It is the recommended way to create a new atomic generator for typical use cases.

§Parameters
  • machine_id: A unique identifier for the node or instance generating IDs. This value will be encoded into every generated ID.
  • time: A TimeSource implementation (e.g., MonotonicClock) that determines how timestamps are generated.
§Returns

A new LockSnowflakeGenerator ready to produce unique, time-ordered IDs.

§Example
use ferroid::{LockSnowflakeGenerator, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};

let generator = LockSnowflakeGenerator::new(0, MonotonicClock::with_epoch(TWITTER_EPOCH));

let id: SnowflakeTwitterId = loop {
    match generator.next_id() {
        IdGenStatus::Ready { id } => break id,
        IdGenStatus::Pending { .. } => core::hint::spin_loop(),
    }
};
Source

pub fn from_components( timestamp: ID::Ty, machine_id: ID::Ty, sequence: ID::Ty, time: T, ) -> Self

Available on crate features snowflake or ulid only.

Creates a new ID generator from explicit component values.

This constructor is primarily useful for advanced use cases such as restoring state from persistent storage or controlling the starting point of the generator manually.

§Parameters
  • timestamp: The initial timestamp component (usually in milliseconds)
  • machine_id: The machine or worker identifier
  • sequence: The initial sequence number
  • time: A TimeSource implementation used to fetch the current time
§Returns

A new generator instance preloaded with the given state.

§⚠️ Note

In typical use cases, you should prefer Self::new to let the generator initialize itself from the current time.

Source

pub fn next_id(&self) -> IdGenStatus<ID>

Available on crate features snowflake or ulid only.

Attempts to generate the next available ID.

Returns a new, time-ordered, unique ID if generation succeeds. If the generator is temporarily exhausted (e.g., the sequence is full and the time has not advanced), it returns IdGenStatus::Pending.

§Panics

Panics if the lock is poisoned. For explicitly fallible behavior, use Self::try_next_id instead.

§Example
use ferroid::{LockSnowflakeGenerator, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};

let generator = LockSnowflakeGenerator::new(0, MonotonicClock::with_epoch(TWITTER_EPOCH));

let id: SnowflakeTwitterId = loop {
    match generator.next_id() {
        IdGenStatus::Ready { id } => break id,
        IdGenStatus::Pending { .. } => std::thread::yield_now(),
    }
};
Source

pub fn try_next_id(&self) -> Result<IdGenStatus<ID>, Error<Infallible>>

Available on crate features snowflake or ulid only.

A fallible version of Self::next_id that returns a Result.

This method attempts to generate the next ID based on the current time and internal state. If successful, it returns IdGenStatus::Ready with a newly generated ID. If the generator is temporarily exhausted, it returns IdGenStatus::Pending. If an internal failure occurs (e.g., a time source or lock error), it returns an error.

§Returns
  • Ok(IdGenStatus::Ready { id }): A new ID is available
  • Ok(IdGenStatus::Pending { yield_for }): The time to wait (in milliseconds) before trying again
  • Err(e): the lock was poisoned
§Errors
  • Returns an error if the underlying lock has been poisoned.
§Example
use ferroid::{LockSnowflakeGenerator, ToU64, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};

let generator = LockSnowflakeGenerator::new(0, MonotonicClock::with_epoch(TWITTER_EPOCH));

// Attempt to generate a new ID
let id: SnowflakeTwitterId = loop {
    match generator.try_next_id() {
        Ok(IdGenStatus::Ready { id }) => break id,
        Ok(IdGenStatus::Pending { yield_for }) => {
            std::thread::sleep(core::time::Duration::from_millis(yield_for.to_u64()));
        }
        Err(e) => panic!("Generator error: {}", e),
    }
};

Trait Implementations§

Source§

impl<ID, T> SnowflakeGenerator<ID, T> for LockSnowflakeGenerator<ID, T>
where ID: SnowflakeId, T: TimeSource<ID::Ty>,

Available on crate features snowflake or ulid only.
Source§

type Err = Error

Source§

fn new(machine_id: ID::Ty, time: T) -> Self

Source§

fn next_id(&self) -> IdGenStatus<ID>

Returns the next available ID
Source§

fn try_next_id(&self) -> Result<IdGenStatus<ID>, Self::Err>

A fallible version of Self::next_id that returns a Result. Read more

Auto Trait Implementations§

§

impl<ID, T> Freeze for LockSnowflakeGenerator<ID, T>
where T: Freeze,

§

impl<ID, T> RefUnwindSafe for LockSnowflakeGenerator<ID, T>
where T: RefUnwindSafe,

§

impl<ID, T> Send for LockSnowflakeGenerator<ID, T>
where T: Send, ID: Send,

§

impl<ID, T> Sync for LockSnowflakeGenerator<ID, T>
where T: Sync, ID: Send,

§

impl<ID, T> Unpin for LockSnowflakeGenerator<ID, T>
where T: Unpin,

§

impl<ID, T> UnwindSafe for LockSnowflakeGenerator<ID, T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<G, ID, T> SnowflakeGeneratorAsyncExt<ID, T> for G
where G: SnowflakeGenerator<ID, T>, ID: SnowflakeId, T: TimeSource<<ID as Id>::Ty>,

Source§

type Err = <G as SnowflakeGenerator<ID, T>>::Err

Available on crate features futures and snowflake only.
Source§

fn try_next_id_async<'a, S>( &'a self, ) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncExt<ID, T>>::Err>>
where S: SleepProvider,

Available on crate features futures and snowflake only.
Returns a future that resolves to the next available Snowflake ID. Read more
Source§

impl<G, ID, T> SnowflakeGeneratorAsyncSmolExt<ID, T> for G
where G: SnowflakeGenerator<ID, T>, ID: SnowflakeId, T: TimeSource<<ID as Id>::Ty>,

Source§

type Err = <G as SnowflakeGenerator<ID, T>>::Err

Available on crate feature async-smol and crate feature snowflake and (crate features async-tokio or async-smol) only.
Source§

fn try_next_id_async( &self, ) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncSmolExt<ID, T>>::Err>>

Available on crate feature async-smol and crate feature snowflake and (crate features async-tokio or async-smol) only.
Returns a future that resolves to the next available Snowflake ID using the SmolSleep provider. Read more
Source§

impl<G, ID, T> SnowflakeGeneratorAsyncTokioExt<ID, T> for G
where G: SnowflakeGenerator<ID, T>, ID: SnowflakeId, T: TimeSource<<ID as Id>::Ty>,

Source§

type Err = <G as SnowflakeGenerator<ID, T>>::Err

Available on crate feature async-tokio and crate feature snowflake and (crate features async-tokio or async-smol) only.
Source§

fn try_next_id_async( &self, ) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncTokioExt<ID, T>>::Err>>

Available on crate feature async-tokio and crate feature snowflake and (crate features async-tokio or async-smol) only.
Returns a future that resolves to the next available Snowflake ID using the TokioSleep provider. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V