duration-extender
A lightweight, zero-dependency Rust crate that extends primitive integer types with intuitive methods for creating std::time::Duration objects.
Write expressive, human-readable code for timeouts, delays, and schedules without the verbosity of Duration::from_secs().
Why duration-extender?
⚠️ Breaking Changes in v0.2.0
Negative values now panic instead of using absolute value.
Previously in v0.1.0:
.minutes == 5.minutes // ❌ Surprising - used abs()
Now in v0.2.0:
5.minutes // ✅ Works fine
.minutes // ❌ Panics: "duration cannot be negative: got -5 minutes"
This change prevents silent bugs. See CHANGELOG.md for details.
Before:
let timeout = from_secs;
let delay = from_secs;
let cache_ttl = from_secs;
After:
let timeout = 30.seconds;
let delay = 5.minutes;
let cache_ttl = 1.days;
Features
- Fluent API — Natural, readable syntax for duration creation
- Type-safe — Works with
u64,u32,i64, andi32 - Explicit errors — Uses saturating arithmetic for overflow; panics on negative values with clear messages
- Zero dependencies — Just the standard library
- Minimal overhead — Compiles down to the same code as manual duration creation
Installation
Add this to your Cargo.toml:
[]
= "0.2" # ← Change from 0.1
Usage
Import the DurationExt trait to unlock duration methods on integers:
use DurationExt;
use Duration;
Real-World Examples
HTTP client timeout:
let client = builder
.timeout
.build?;
Tokio sleep:
sleep.await;
Cache expiration:
cache.insert_with_ttl;
Rate limiting:
let rate_limit = new;
Available Methods
The DurationExt trait provides these methods:
| Method | Equivalent |
|---|---|
.seconds() |
Duration::from_secs(n) |
.minutes() |
Duration::from_secs(n * 60) |
.hours() |
Duration::from_secs(n * 3600) |
.days() |
Duration::from_secs(n * 86400) |
.weeks() |
Duration::from_secs(n * 604800) |
Supported Types
The DurationExt trait is implemented for:
u64andu32— Direct conversioni64andi32— Panics on negative values to prevent bugs
All operations use saturating arithmetic to prevent overflow panics.
Safety Guarantees
- Overflow safe — Saturating arithmetic prevents overflow panics
- Negative handling — Signed integers panic on negative values with clear error messages
- Type safety — Leverages Rust's type system for compile-time correctness
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is dual-licensed under:
You may choose either license for your purposes.
Acknowledgments
Inspired by duration extension patterns from other languages and the Rust community's focus on ergonomic APIs.