Struct Snowflake

Source
pub struct Snowflake { /* private fields */ }
Expand description

Snowflake ID generator

This struct implements the Snowflake algorithm for generating unique IDs. Each ID is composed of:

  • Timestamp (41 bits)
  • Node ID (10 bits)
  • Sequence number (12 bits)

Implementations§

Source§

impl Snowflake

Source

pub fn new(node: u16, epoch: Option<i64>) -> Result<Self, SnowflakeError>

Creates a new Snowflake instance

§Arguments
  • node - A unique identifier for the node generating the IDs (0-1023)
  • epoch - An optional custom epoch in milliseconds. If None, DEFAULT_EPOCH is used.
§Returns

A Result containing the new Snowflake instance or a SnowflakeError

§Errors

Returns SnowflakeError::MachineIdOutOfRange if the node ID is greater than 1023

Source

pub fn generate(&self) -> Result<u64, SnowflakeError>

Generates a new Snowflake ID

§Returns

A Result containing the generated ID as a u64 or a SnowflakeError

§Errors
  • SnowflakeError::ClockMovedBackwards if the system time moves backwards
  • SnowflakeError::SequenceOverflow if unable to generate a unique ID within 5 seconds
Source

pub fn parse_id(id: u64) -> (u64, u16, u16)

Parses a Snowflake ID into its components

§Arguments
  • id - The Snowflake ID to parse
§Returns

A tuple containing the timestamp, node ID, and sequence number

§Example
let (timestamp, node, sequence) = Snowflake::parse_id(1234567890);
println!("Timestamp: {}, Node: {}, Sequence: {}", timestamp, node, sequence);

Auto Trait Implementations§

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<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.