pub trait TimeSource {
// Required method
fn now(&self) -> Duration;
}Expand description
Trait for providing elapsed time since a starting point.
TimeSource implementations abstract different sources of time while maintaining consistent “elapsed time” semantics. Each implementation has an implicit starting point and returns the Duration elapsed since that point.
§Contract
Implementations must guarantee:
- Monotonicity:
now()never decreases between calls - Zero start: The first call to
now()should returnDuration::ZEROor close to it - Consistency: Multiple calls without time progression return the same value
- Reasonable precision: Should provide precision appropriate for the use case
§Performance Requirements
- Methods should be marked
#[inline(always)]when possible - Implementations should minimize allocation and system calls
- The abstraction should compile to efficient machine code
§Examples
§Implementing a Custom TimeSource
use rate_guard::time_source::TimeSource;
use std::time::{Duration, Instant};
struct CustomTimeSource {
start: Instant,
}
impl CustomTimeSource {
fn new() -> Self {
Self {
start: Instant::now(),
}
}
}
impl TimeSource for CustomTimeSource {
fn now(&self) -> Duration {
self.start.elapsed()
}
}§Usage in Rate Limiting
use rate_guard::time_source::{TimeSource, MockTimeSource};
use rate_guard::precision::{Precision, Millis};
use rate_guard::types::Uint;
use std::time::Duration;
fn get_current_ticks<T: TimeSource, P: Precision>(time_source: &T) -> Uint {
let elapsed = time_source.now();
P::to_ticks(elapsed)
}
let time_source = MockTimeSource::new();
time_source.advance(Duration::from_millis(500));
let ticks = get_current_ticks::<_, Millis>(&time_source);
assert_eq!(ticks, 500);Required Methods§
Sourcefn now(&self) -> Duration
fn now(&self) -> Duration
Returns the elapsed Duration since this TimeSource’s starting point.
This method should return a monotonically increasing Duration that represents the time elapsed since some fixed starting point. The starting point is implementation-defined but should remain consistent for the lifetime of the TimeSource instance.
§Returns
A Duration representing elapsed time since the starting point.
The first call should return Duration::ZERO or very close to it.
§Guarantees
- Monotonic: Each call returns a value >= the previous call
- Consistent: Multiple calls without time progression return the same value
- Bounded: The returned Duration should not exceed reasonable limits
§Examples
use rate_guard::time_source::{TimeSource, MockTimeSource};
use std::time::Duration;
let time_source = MockTimeSource::new();
let t1 = time_source.now();
assert_eq!(t1, Duration::ZERO);
time_source.advance(Duration::from_millis(100));
let t2 = time_source.now();
assert_eq!(t2, Duration::from_millis(100));
// Monotonicity guarantee
assert!(t2 >= t1);Implementors§
impl TimeSource for MockTimeSource
impl TimeSource for StdTimeSource
impl TimeSource for TokioTimeSource
Available on crate feature
tokio-time only.