pub struct LockSnowflakeGenerator<ID, T>{ /* private fields */ }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
Snowflakelayout
§Recommended When
- You’re in a multi-threaded environment
- Fair access across threads is important
§See Also
Implementations§
Source§impl<ID, T> LockSnowflakeGenerator<ID, T>
impl<ID, T> LockSnowflakeGenerator<ID, T>
Sourcepub fn new(machine_id: ID::Ty, clock: T) -> Self
pub fn new(machine_id: ID::Ty, clock: T) -> Self
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 clock 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.clock: ATimeSourceimplementation (e.g.,MonotonicClock) that determines how timestamps are generated.
§Returns
A new LockSnowflakeGenerator ready to produce unique, time-ordered
IDs.
§Example
use ferroid::{LockSnowflakeGenerator, SnowflakeTwitterId, MonotonicClock};
let generator = LockSnowflakeGenerator::<SnowflakeTwitterId, _>::new(0, MonotonicClock::default());
let id = generator.next_id();Sourcepub fn from_components(
timestamp: ID::Ty,
machine_id: ID::Ty,
sequence: ID::Ty,
clock: T,
) -> Self
pub fn from_components( timestamp: ID::Ty, machine_id: ID::Ty, sequence: ID::Ty, clock: T, ) -> Self
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 identifiersequence: The initial sequence numberclock: ATimeSourceimplementation 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.
Sourcepub fn next_id(&self) -> IdGenStatus<ID>
pub fn next_id(&self) -> IdGenStatus<ID>
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
clock 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, SnowflakeTwitterId, IdGenStatus, MonotonicClock, TimeSource};
// Create a clock and a generator with machine_id = 0
let clock = MonotonicClock::default();
let generator = LockSnowflakeGenerator::<SnowflakeTwitterId, _>::new(0, clock);
// Attempt to generate a new ID
match generator.next_id() {
IdGenStatus::Ready { id } => {
println!("ID: {}", id);
assert_eq!(id.machine_id(), 0);
}
IdGenStatus::Pending { yield_for } => {
println!("Exhausted; wait for: {}ms", yield_for);
}
}Sourcepub fn try_next_id(&self) -> Result<IdGenStatus<ID>>
pub fn try_next_id(&self) -> Result<IdGenStatus<ID>>
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 availableOk(IdGenStatus::Pending { yield_for }): The time to wait (in milliseconds) before trying againErr(e): A recoverable error occurred (e.g., time source failure)
§Example
use ferroid::{LockSnowflakeGenerator, SnowflakeTwitterId, IdGenStatus, MonotonicClock, TimeSource};
// Create a clock and a generator with machine_id = 0
let clock = MonotonicClock::default();
let generator = LockSnowflakeGenerator::<SnowflakeTwitterId, _>::new(0, clock);
// Attempt to generate a new ID
match generator.try_next_id() {
Ok(IdGenStatus::Ready { id }) => {
println!("ID: {}", id);
assert_eq!(id.machine_id(), 0);
}
Ok(IdGenStatus::Pending { yield_for }) => {
println!("Exhausted; wait for: {}ms", yield_for);
}
Err(err) => eprintln!("Generator error: {}", err),
}Trait Implementations§
Source§impl<ID, T> SnowflakeGenerator<ID, T> for LockSnowflakeGenerator<ID, T>
impl<ID, T> SnowflakeGenerator<ID, T> for LockSnowflakeGenerator<ID, T>
fn new(machine_id: ID::Ty, clock: T) -> Self
Source§fn next_id(&self) -> IdGenStatus<ID>
fn next_id(&self) -> IdGenStatus<ID>
Source§fn try_next_id(&self) -> Result<IdGenStatus<ID>>
fn try_next_id(&self) -> Result<IdGenStatus<ID>>
Self::next_id that returns a Result.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>
impl<ID, T> Sync for LockSnowflakeGenerator<ID, T>
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<G, ID, T> SnowflakeGeneratorAsyncExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncExt<ID, T> for G
Source§fn try_next_id_async<'a, S>(&'a self) -> impl Future<Output = Result<ID, Error>>where
S: SleepProvider,
fn try_next_id_async<'a, S>(&'a self) -> impl Future<Output = Result<ID, Error>>where
S: SleepProvider,
Source§impl<G, ID, T> SnowflakeGeneratorAsyncSmolExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncSmolExt<ID, T> for G
Source§impl<G, ID, T> SnowflakeGeneratorAsyncTokioExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncTokioExt<ID, T> for G
Source§fn try_next_id_async(&self) -> impl Future<Output = Result<ID, Error>>
fn try_next_id_async(&self) -> impl Future<Output = Result<ID, Error>>
TokioSleep provider. Read more