pub struct AtomicSnowflakeGenerator<ID, T>{ /* private fields */ }snowflake and crate feature atomic and target_has_atomic=64 only.Expand description
A lock-free Snowflake ID generator suitable for multi-threaded environments.
This generator stores the Snowflake state in an AtomicU64, allowing safe
shared use across threads.
§Features
- ✅ Thread-safe
- ❌ Safely implement any
SnowflakeIdlayout
§Caveats
This implementation uses an AtomicU64 internally, so it only supports ID
layouts where the underlying type is u64. You cannot use layouts with
larger or smaller representations (i.e., ID::Ty must be u64).
§Recommended When
- You’re in a multi-threaded environment
- Fair access is sacrificed for higher throughput
§See Also
Implementations§
Source§impl<ID, T> AtomicSnowflakeGenerator<ID, T>
impl<ID, T> AtomicSnowflakeGenerator<ID, T>
Sourcepub fn new(machine_id: ID::Ty, time: T) -> Self
Available on crate features snowflake or ulid only.
pub fn new(machine_id: ID::Ty, time: T) -> Self
snowflake or ulid only.Creates a new AtomicSnowflakeGenerator 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: ATimeSourceimplementation (e.g.,MonotonicClock) that determines how timestamps are generated.
§Returns
A new AtomicSnowflakeGenerator ready to produce unique, time-ordered
IDs.
§Example
use ferroid::{AtomicSnowflakeGenerator, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};
let generator = AtomicSnowflakeGenerator::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(),
}
};Sourcepub fn from_components(
timestamp: ID::Ty,
machine_id: ID::Ty,
sequence: ID::Ty,
time: T,
) -> Self
Available on crate features snowflake or ulid only.
pub fn from_components( timestamp: ID::Ty, machine_id: ID::Ty, sequence: ID::Ty, time: T, ) -> Self
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 identifiersequence: The initial sequence numbertime: 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>
Available on crate features snowflake or ulid only.
pub fn next_id(&self) -> IdGenStatus<ID>
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, or CAS fails), it returns
IdGenStatus::Pending.
§Panics
This method currently has no fallible code paths, but may panic if an
internal error occurs in future implementations. For explicitly fallible
behavior, use Self::try_next_id instead.
§Example
use ferroid::{AtomicSnowflakeGenerator, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};
let generator = AtomicSnowflakeGenerator::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(),
}
};Sourcepub fn try_next_id(&self) -> Result<IdGenStatus<ID>>
Available on crate features snowflake or ulid only.
pub fn try_next_id(&self) -> Result<IdGenStatus<ID>>
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 or
CAS fails, 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(_): infallible for this generator
§Errors
- This method currently does not return any errors and always returns
Ok. It is marked as fallible to allow for future extensibility
§Example
use ferroid::{AtomicSnowflakeGenerator, ToU64, IdGenStatus, SnowflakeTwitterId, TWITTER_EPOCH, MonotonicClock};
let generator = AtomicSnowflakeGenerator::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(_) => unreachable!(),
}
};Trait Implementations§
Source§impl<ID, T> SnowflakeGenerator<ID, T> for AtomicSnowflakeGenerator<ID, T>
Available on crate features snowflake or ulid only.
impl<ID, T> SnowflakeGenerator<ID, T> for AtomicSnowflakeGenerator<ID, T>
snowflake or ulid only.type Err = Infallible
fn new(machine_id: ID::Ty, time: T) -> Self
Source§fn next_id(&self) -> IdGenStatus<ID>
fn next_id(&self) -> IdGenStatus<ID>
Source§fn try_next_id(&self) -> Result<IdGenStatus<ID>, Self::Err>
fn try_next_id(&self) -> Result<IdGenStatus<ID>, Self::Err>
Auto Trait Implementations§
impl<ID, T> !Freeze for AtomicSnowflakeGenerator<ID, T>
impl<ID, T> RefUnwindSafe for AtomicSnowflakeGenerator<ID, T>where
T: RefUnwindSafe,
ID: RefUnwindSafe,
impl<ID, T> Send for AtomicSnowflakeGenerator<ID, T>
impl<ID, T> Sync for AtomicSnowflakeGenerator<ID, T>
impl<ID, T> Unpin for AtomicSnowflakeGenerator<ID, T>
impl<ID, T> UnwindSafe for AtomicSnowflakeGenerator<ID, T>where
T: UnwindSafe,
ID: 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<G, ID, T> SnowflakeGeneratorAsyncExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncExt<ID, T> for G
Source§type Err = <G as SnowflakeGenerator<ID, T>>::Err
type Err = <G as SnowflakeGenerator<ID, T>>::Err
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,
fn try_next_id_async<'a, S>(
&'a self,
) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncExt<ID, T>>::Err>>where
S: SleepProvider,
futures and snowflake only.Source§impl<G, ID, T> SnowflakeGeneratorAsyncSmolExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncSmolExt<ID, T> for G
Source§type Err = <G as SnowflakeGenerator<ID, T>>::Err
type Err = <G as SnowflakeGenerator<ID, T>>::Err
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>>
fn try_next_id_async( &self, ) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncSmolExt<ID, T>>::Err>>
async-smol and crate feature snowflake and (crate features async-tokio or async-smol) only.Source§impl<G, ID, T> SnowflakeGeneratorAsyncTokioExt<ID, T> for G
impl<G, ID, T> SnowflakeGeneratorAsyncTokioExt<ID, T> for G
Source§type Err = <G as SnowflakeGenerator<ID, T>>::Err
type Err = <G as SnowflakeGenerator<ID, T>>::Err
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>>
fn try_next_id_async( &self, ) -> impl Future<Output = Result<ID, <G as SnowflakeGeneratorAsyncTokioExt<ID, T>>::Err>>
async-tokio and crate feature snowflake and (crate features async-tokio or async-smol) only.TokioSleep provider. Read more