Precision

Trait Precision 

Source
pub trait Precision {
    // Required methods
    fn to_ticks(duration: Duration) -> Uint;
    fn from_ticks(ticks: Uint) -> Duration;
}
Expand description

Trait for defining precision scales for Duration-to-tick conversions.

Precision implementations define how Duration values are converted to internal tick representations and back. Each precision type represents a different time scale, enabling optimization for different use cases.

§Implementation Requirements

Implementations must satisfy these invariants:

  • Bidirectional conversion consistency: from_ticks(to_ticks(d)) ≈ d
  • Monotonicity: larger durations produce larger tick values
  • Zero preservation: to_ticks(Duration::ZERO) == 0
  • Overflow handling: graceful saturation on overflow using branchless operations

§Performance

All methods should be marked #[inline(always)] to enable compile-time optimization and ensure zero-cost abstractions. The to_ticks implementation uses branchless min() operations that compile to CMOV instructions for optimal performance.

§Generic Usage

The trait is designed to be used with generic type parameters in rate limiters and executors:

use std::time::Duration;
use rate_guard::precision::{Precision, Millis};
use rate_guard::types::Uint;

fn process_with_precision<P: Precision>(duration: Duration) -> Uint {
    P::to_ticks(duration)  // Static dispatch, zero-cost
}

let ticks = process_with_precision::<Millis>(Duration::from_millis(500));
assert_eq!(ticks, 500);

Required Methods§

Source

fn to_ticks(duration: Duration) -> Uint

Converts a Duration to ticks in this precision scale.

This method uses branchless operations for optimal performance and handles overflow by saturating to the maximum tick value using min() operations that compile to efficient CMOV instructions.

§Arguments
  • duration - The Duration to convert
§Returns

The number of ticks representing the duration in this precision

§Performance

This method is branchless and compiles to conditional move instructions, avoiding branch prediction penalties.

§Examples
use std::time::Duration;
use rate_guard::precision::{Precision, Millis};

let duration = Duration::from_millis(500);
let ticks = Millis::to_ticks(duration);
assert_eq!(ticks, 500);
Source

fn from_ticks(ticks: Uint) -> Duration

Converts ticks back to a Duration in this precision scale.

This method should be the inverse of to_ticks and handle large tick values gracefully.

§Arguments
  • ticks - The number of ticks to convert
§Returns

The Duration represented by the tick count

§Examples
use std::time::Duration;
use rate_guard::precision::{Precision, Millis};

let duration = Millis::from_ticks(1500);
assert_eq!(duration, Duration::from_millis(1500));

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§