DurationExt

Trait DurationExt 

Source
pub trait DurationExt {
    // Required methods
    fn from_nanos_saturating(ns: u128) -> Duration;
    fn parse(s: &str) -> Result<Duration, String>;
}
Expand description

Extension trait providing additional functionality for Duration.

Required Methods§

Source

fn from_nanos_saturating(ns: u128) -> Duration

Creates a duration from nanoseconds represented as a u128. Saturates anything beyond the representable range.

Source

fn parse(s: &str) -> Result<Duration, String>

Parse a duration string with time unit suffixes.

This function accepts duration strings with the following suffixes:

  • ms: Milliseconds (e.g., “500ms”, “1000ms”)
  • s: Seconds (e.g., “30s”, “5s”)
  • m: Minutes (e.g., “2m”, “30m”)
  • h: Hours (e.g., “1h”, “24h”)

A suffix is required - strings without suffixes will return an error.

§Overflow Protection

The function includes overflow protection for time unit conversions:

  • Hours are safely converted to seconds (hours * 3600) with overflow checking
  • Minutes are safely converted to seconds (minutes * 60) with overflow checking
  • Values that would cause integer overflow return an error
§Arguments
  • s - A string slice containing the duration with required suffix
§Returns
  • Ok(Duration) - Successfully parsed duration
  • Err(String) - Error message describing what went wrong (invalid format, overflow, etc.)
§Examples

// Different time units
assert_eq!(Duration::parse("500ms").unwrap(), Duration::from_millis(500));
assert_eq!(Duration::parse("30s").unwrap(), Duration::from_secs(30));
assert_eq!(Duration::parse("5m").unwrap(), Duration::from_secs(300));
assert_eq!(Duration::parse("2h").unwrap(), Duration::from_secs(7200));

// Error cases
assert!(Duration::parse("invalid").is_err());
assert!(Duration::parse("10x").is_err());
assert!(Duration::parse("5minutes").is_err()); // Long forms not supported
assert!(Duration::parse("60").is_err()); // No suffix required

// Overflow protection
let max_hours = u64::MAX / 3600;
assert!(Duration::parse(&format!("{}h", max_hours)).is_ok());      // At limit
assert!(Duration::parse(&format!("{}h", max_hours + 1)).is_err()); // Overflow

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.

Implementations on Foreign Types§

Source§

impl DurationExt for Duration

Implementors§