Skip to main content

parse_duration

Function parse_duration 

Source
pub fn parse_duration(text: &str) -> Result<Duration, Error>
Expand description

Reads a duration from its literal spelling, such as "3d8h30m" or "1.5s": the spelling a ::duration cast reads and a ::string cast writes.

The text is one or more components, each a whole number with an optional decimal fraction followed by one of the units y, mo, w, d, h, m, s and ms, with no whitespace, no sign and no empty text. A repeated unit adds to the amount before it. A fraction is spread over whole smaller units (a month 30 days, a year 365), and one that does not come to a whole number of milliseconds is refused.

A text that does not spell a duration answers an EvaluationError with the reason invalid_duration_format, and one whose unit is outside i64 the reason integer_overflow.

use predicator_rs::{Duration, parse_duration};

assert_eq!(parse_duration("1h30m")?, Duration { hours: 1, minutes: 30, ..Duration::default() });
assert_eq!(parse_duration("0.5mo")?, Duration { days: 15, ..Duration::default() });
assert_eq!(parse_duration("1d ").unwrap_err().reason(), "invalid_duration_format");