Expand description
A simple library for parsing human-readable duration strings into std::time::Duration.
§Usage
This library provides a parse function for quick and easy parsing, and a Parser
struct for more control over parsing behavior.
§The parse function
The parse function is a convenience wrapper around a default Parser.
use durstr::parse;
use std::time::Duration;
let dur = parse("12 minutes, 21 seconds");
assert_eq!(dur, Ok(Duration::from_secs(741)));
let dur = parse("1hr 2min 3sec");
assert_eq!(dur, Ok(Duration::from_secs(3723)));§The Parser struct
For more control, you can use the Parser struct directly. For example, to parse with case-insensitivity:
use durstr::{Parser, ParserOptions};
use std::time::Duration;
let options = ParserOptions { ignore_case: true, ..Default::default() };
let parser = Parser::new(options);
let dur = parser.parse("1 MINUTE, 2 SECONDS");
assert_eq!(dur, Ok(Duration::from_secs(62)));§Units
By default, the following units are provided:
| Unit | Aliases |
|---|---|
| Millisecond | ms, msec(s), millisecond(s) |
| Second | s, sec(s), second(s) |
| Minute | m, min(s), minute(s) |
| Hour | h, hr(s), hour(s) |
You can define your own units, and their values, using the ParserUnits struct:
use durstr::{Parser, ParserOptions, ParserUnits};
use std::time::Duration;
let mut units = ParserUnits::default();
units.add_unit("days", Duration::from_secs(3600) * 24);
let parser = Parser::new(ParserOptions {
units,
..Default::default()
});
let d = parser.parse("4 days");
assert_eq!(d, Ok(Duration::from_secs(3600) * 24 * 4));Structs§
- Parser
- A configurable parser for duration strings.
- Parser
Options - Options to customize the behavior of a
Parser. - Parser
Units - Used to customize the parser’s units and their values.
Enums§
- Error
- An error that can occur when parsing a duration string.
Functions§
- parse
- Parses a duration string into a
std::time::Duration.