Struct BasicSnowflakeGenerator

Source
pub struct BasicSnowflakeGenerator<T, ID>
where T: TimeSource<ID::Ty>, ID: Snowflake,
{ /* private fields */ }
Expand description

A non-concurrent Snowflake ID generator suitable for single-threaded environments.

This generator is lightweight and fast, but not thread-safe.

§Features

  • ❌ Not thread-safe
  • ✅ Safely implement any Snowflake layout
  • You’re in a single-threaded environment
  • You want the fastest generator

§See Also

Implementations§

Source§

impl<T, ID> BasicSnowflakeGenerator<T, ID>
where T: TimeSource<ID::Ty>, ID: Snowflake,

Source

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

Creates a new BasicSnowflakeGenerator 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: A TimeSource implementation (e.g., MonotonicClock) that determines how timestamps are generated.
§Returns

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

§Example
use ferroid::{BasicSnowflakeGenerator, SnowflakeTwitterId, MonotonicClock};

let mut generator = BasicSnowflakeGenerator::<_, SnowflakeTwitterId>::new(0, MonotonicClock::default());
let id = generator.next_id();
Source

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 identifier
  • sequence: The initial sequence number
  • clock: 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(&mut 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

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::{BasicSnowflakeGenerator, SnowflakeTwitterId, IdGenStatus, MonotonicClock, TimeSource};

// Create a clock and a generator with machine_id = 0
let clock = MonotonicClock::default();
let mut generator = BasicSnowflakeGenerator::<_, 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_until } => {
        // This should rarely happen on the first call, but if it does,
        // backoff or yield and try again.
        println!("Exhausted; wait until: {}", yield_until);
    }
}
Source

pub fn try_next_id(&mut 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 available
  • Ok(IdGenStatus::Pending { yield_until }): Wait for time to advance
  • Err(e): A recoverable error occurred (e.g., time source failure)
§Example
use ferroid::{BasicSnowflakeGenerator, SnowflakeTwitterId, IdGenStatus, MonotonicClock, TimeSource};

// Create a clock and a generator with machine_id = 0
let clock = MonotonicClock::default();
let mut generator = BasicSnowflakeGenerator::<_, 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_until }) => {
        // This should rarely happen on the first call, but if it does,
        // backoff or yield and try again.
        println!("Exhausted; wait until: {}", yield_until);
    }
    Err(err) => eprintln!("Generator error: {}", err),
}

Trait Implementations§

Source§

impl<T, ID> SnowflakeGenerator<ID> for BasicSnowflakeGenerator<T, ID>
where T: TimeSource<ID::Ty>, ID: Snowflake,

Source§

fn next(&mut self) -> IdGenStatus<ID>

Returns the next available ID or yields if generation is temporarily stalled.
Source§

fn try_next(&mut self) -> Result<IdGenStatus<ID>>

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

Auto Trait Implementations§

§

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

§

impl<T, ID> RefUnwindSafe for BasicSnowflakeGenerator<T, ID>

§

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

§

impl<T, ID> Sync for BasicSnowflakeGenerator<T, ID>
where ID: Sync, T: Sync,

§

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

§

impl<T, ID> UnwindSafe for BasicSnowflakeGenerator<T, ID>
where ID: UnwindSafe, 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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<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<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more