Struct MonotonicClock

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

A monotonic time source that returns elapsed time since process start, offset from a user-defined epoch.

This avoids wall-clock adjustments (e.g., NTP or daylight savings changes) while still aligning timestamps to a fixed origin.

Internally, the clock measures time by capturing Instant::now() at construction and adding to it the duration elapsed since a given epoch (computed from SystemTime::now() at startup).

Implementations§

Source§

impl MonotonicClock

Source

pub fn with_epoch(epoch: Duration) -> Self

Constructs a monotonic clock using a custom epoch as the origin (t = 0), specified in milliseconds since the Unix epoch.

The provided epoch defines the zero-point for all future timestamps returned by this clock. Internally, the clock spawns a background thread that updates a shared atomic counter once per millisecond, using a monotonic timer (Instant) to measure elapsed time since startup.

On each call to current_millis, the clock returns the current tick value plus a fixed offset - the precomputed difference between the current wall-clock time (SystemTime::now()) and the given epoch.

This design avoids syscalls on the hot path and ensures that time never goes backward, even if the system clock is adjusted externally.

§Parameters
  • epoch: The origin timestamp, as a Duration since 1970-01-01 UTC.
§Panics

Panics if:

  • The current system time is earlier than the given epoch
  • The internal ticker thread has already been initialized
§Example
use std::time::{Duration, Instant};
use ferroid::{MonotonicClock, TimeSource};
let now = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .unwrap();

// Or use a default epoch
// use ferroid::TWITTER_EPOCH,
// let now = TWITTER_EPOCH;
let clock = MonotonicClock::with_epoch(now);

std::thread::sleep(Duration::from_millis(5));

let ts: u64 = clock.current_millis();

// On most systems, this will report a value near 5 ms. However, due to
// small differences in timer alignment and sleep accuracy, the counter
// may be slightly behind. It's common to observe values like 4–6 ms
// after sleeping for 5 ms. The value will never go backward and is
// guaranteed to increase monotonically.
// assert!(ts >= 5);

This allows you to control the timestamp layout (e.g., Snowflake-style ID encoding) by anchoring all generated times to a custom epoch of your choosing.

Trait Implementations§

Source§

impl Clone for MonotonicClock

Source§

fn clone(&self) -> MonotonicClock

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for MonotonicClock

Source§

fn default() -> Self

Constructs a monotonic clock aligned to the default CUSTOM_EPOCH.

Panics if system time is earlier than the custom epoch.

Source§

impl TimeSource<u128> for MonotonicClock

Source§

fn current_millis(&self) -> u128

Returns the number of milliseconds since the configured epoch, based on the elapsed monotonic time since construction.

Source§

impl TimeSource<u64> for MonotonicClock

Source§

fn current_millis(&self) -> u64

Returns the number of milliseconds since the configured epoch, based on the elapsed monotonic time since construction.

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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<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