
Building a Typed Duration Parser in Rust
Why parse durations into a typed value?
A raw string is flexible, but it pushes validation to the edges of your program. That often leads to scattered parsing logic, inconsistent error messages, and subtle bugs.
A typed parser gives you:
- Early validation: reject invalid values before they reach business logic.
- Clear semantics:
Durationexpresses intent better than a string. - Safer APIs: functions can accept
Durationinstead of ad hoc text. - Better reuse: the same parser can be used in config loaders, CLI tools, and HTTP handlers.
A good parser should support a small, well-defined syntax and fail loudly when the input is malformed.
Supported syntax
For this example, we will accept a simple format:
150ms2s5m1h3d
The parser will interpret the suffix as a unit and the numeric prefix as an unsigned integer. This keeps the implementation straightforward and avoids ambiguity.
| Input | Meaning | Result |
|---|---|---|
500ms | 500 milliseconds | Duration::from_millis(500) |
10s | 10 seconds | Duration::from_secs(10) |
3m | 3 minutes | Duration::from_secs(180) |
2h | 2 hours | Duration::from_secs(7200) |
1d | 1 day | Duration::from_secs(86400) |
If you need fractional values such as 1.5s, you can extend the parser later. Starting with integers keeps the code compact and predictable.
Defining the parser type
We will create a small wrapper type that owns the parsed Duration. This makes the API explicit and allows you to add helper methods later.
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParsedDuration(Duration);
impl ParsedDuration {
pub fn into_inner(self) -> Duration {
self.0
}
pub fn as_duration(&self) -> Duration {
self.0
}
}
This wrapper is optional, but it is useful when you want to distinguish “a parsed duration from user input” from any other Duration in your codebase.
Designing a useful error type
Good parsers should explain what went wrong. A generic “invalid input” message is not enough when users are editing configuration files or passing CLI arguments.
Here is a compact error type with a few specific failure modes:
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DurationParseError {
Empty,
MissingUnit,
InvalidNumber,
UnknownUnit(String),
Overflow,
}
impl fmt::Display for DurationParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DurationParseError::Empty => write!(f, "duration is empty"),
DurationParseError::MissingUnit => write!(f, "missing duration unit"),
DurationParseError::InvalidNumber => write!(f, "invalid numeric value"),
DurationParseError::UnknownUnit(unit) => write!(f, "unknown duration unit: {unit}"),
DurationParseError::Overflow => write!(f, "duration value is too large"),
}
}
}
impl std::error::Error for DurationParseError {}
This error type is intentionally small, but it already gives callers enough information to produce useful diagnostics.
Implementing FromStr
Rust’s FromStr trait is the natural fit for parsing string inputs. It integrates well with standard library patterns and makes your type easy to use.
impl FromStr for ParsedDuration {
type Err = DurationParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let input = input.trim();
if input.is_empty() {
return Err(DurationParseError::Empty);
}
let split_at = input
.find(|c: char| !c.is_ascii_digit())
.ok_or(DurationParseError::MissingUnit)?;
let (number_part, unit_part) = input.split_at(split_at);
if number_part.is_empty() {
return Err(DurationParseError::InvalidNumber);
}
if unit_part.is_empty() {
return Err(DurationParseError::MissingUnit);
}
let value: u64 = number_part
.parse()
.map_err(|_| DurationParseError::InvalidNumber)?;
let duration = match unit_part {
"ms" => Duration::from_millis(value),
"s" => Duration::from_secs(value),
"m" => Duration::from_secs(value.checked_mul(60).ok_or(DurationParseError::Overflow)?),
"h" => Duration::from_secs(value.checked_mul(60 * 60).ok_or(DurationParseError::Overflow)?),
"d" => Duration::from_secs(value.checked_mul(60 * 60 * 24).ok_or(DurationParseError::Overflow)?),
other => return Err(DurationParseError::UnknownUnit(other.to_string())),
};
Ok(ParsedDuration(duration))
}
}
How it works
- Trim whitespace so inputs like
" 5s "are accepted. - Split the string into a numeric prefix and a unit suffix.
- Parse the number as
u64. - Match the unit and convert to
Duration. - Return a typed wrapper on success.
This implementation is easy to read and easy to extend.
Using the parser in application code
Once FromStr is implemented, parsing becomes straightforward.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let timeout: ParsedDuration = "250ms".parse()?;
let retry_delay: ParsedDuration = "5s".parse()?;
println!("timeout = {:?}", timeout.as_duration());
println!("retry_delay = {:?}", retry_delay.into_inner());
Ok(())
}
This pattern is especially useful in:
- configuration loaders
- CLI tools
- test fixtures
- environment-driven settings
- scheduling and backoff logic
Because the parser returns a typed value, downstream code no longer needs to know about the original string format.
Adding validation rules
In real systems, not every duration should be accepted. For example, a timeout of 0s may be invalid, or a polling interval might need to be at least 100ms.
You can enforce such rules in a constructor or helper method:
impl ParsedDuration {
pub fn new(duration: Duration) -> Result<Self, DurationParseError> {
if duration.is_zero() {
return Err(DurationParseError::InvalidNumber);
}
Ok(Self(duration))
}
}
A more explicit approach is to define a separate validation error, but the right choice depends on how much detail your application needs. For many internal tools, a small error set is enough.
Extending the parser safely
A parser like this is intentionally minimal. If your requirements grow, you can extend it without changing the public shape of the API.
Common extensions
| Feature | Example | Notes |
|---|---|---|
| Fractional values | 1.5s | Requires parsing decimals and careful rounding |
| Compound values | 1h30m | Needs a loop over repeated number-unit segments |
| Microseconds and nanoseconds | 10us, 20ns | Useful for low-latency systems |
| Signed values | -5s | Usually not valid for Duration |
| Whitespace-separated syntax | 5 s | More permissive, but more complex |
If you add fractional support, be careful with precision loss. std::time::Duration stores seconds and nanoseconds, so you should define how rounding works. For example, 1.23456789s may need to be truncated or rounded to nanoseconds.
A more ergonomic API for callers
A parser is often more useful when it offers both parsing and convenience methods. Consider adding a helper that accepts &str and returns Duration directly:
pub fn parse_duration(input: &str) -> Result<Duration, DurationParseError> {
input.parse::<ParsedDuration>().map(|d| d.into_inner())
}
This keeps the wrapper type available for advanced use while giving most callers a simple function.
You can also implement Deref<Target = Duration> if you want transparent access, but that is usually unnecessary. A named method like as_duration() is clearer and avoids surprising behavior.
Testing the parser
Parsing code should be covered by tests because edge cases are easy to miss. Focus on valid inputs, invalid inputs, and boundary conditions.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_seconds() {
let parsed: ParsedDuration = "12s".parse().unwrap();
assert_eq!(parsed.as_duration(), Duration::from_secs(12));
}
#[test]
fn parses_milliseconds() {
let parsed: ParsedDuration = "500ms".parse().unwrap();
assert_eq!(parsed.as_duration(), Duration::from_millis(500));
}
#[test]
fn rejects_empty_input() {
let err = "".parse::<ParsedDuration>().unwrap_err();
assert_eq!(err, DurationParseError::Empty);
}
#[test]
fn rejects_unknown_unit() {
let err = "10x".parse::<ParsedDuration>().unwrap_err();
assert_eq!(err, DurationParseError::UnknownUnit("x".to_string()));
}
#[test]
fn rejects_missing_unit() {
let err = "42".parse::<ParsedDuration>().unwrap_err();
assert_eq!(err, DurationParseError::MissingUnit);
}
}
A few practical testing tips:
- test both the happy path and failure path
- include whitespace variations
- test large values that could overflow
- verify error variants, not just error strings
When this pattern is a good fit
A typed duration parser is a strong choice when you want a compact, user-facing syntax and strict validation. It works well in:
- configuration systems
- CLI applications
- job schedulers
- retry and backoff settings
- cache expiration policies
- polling and heartbeat intervals
It is less suitable when you need rich calendrical semantics such as months, leap seconds, or timezone-aware timestamps. Those concerns belong to date-time libraries, not std::time::Duration.
Best practices
A few guidelines help keep the parser maintainable:
- Keep the syntax small unless you have a concrete need for more complexity.
- Return structured errors instead of collapsing everything into one message.
- Use
FromStrso the type integrates naturally with Rust conventions. - Avoid silent coercions such as treating unknown units as seconds.
- Document accepted formats clearly in public APIs.
- Test overflow paths if you multiply units into seconds.
If the parser is part of a public crate, document examples directly in the API docs so users can copy them into their own code.
Summary
A typed duration parser turns human-friendly strings into safe, reusable Duration values. By implementing FromStr, defining a focused error type, and keeping the accepted syntax explicit, you get a small API that is easy to use and hard to misuse.
This pattern is especially valuable in Rust because it aligns with the language’s emphasis on correctness, clear ownership, and explicit failure handling. Even a modest parser like this can improve the quality of configuration and input handling across an application.