| Crates.io | sleep-utils |
| lib.rs | sleep-utils |
| version | 0.2.0 |
| created_at | 2025-11-04 12:12:48.794679+00 |
| updated_at | 2025-11-04 12:39:28.260993+00 |
| description | Smart sleep utilities with flexible input formats and automatic zero-value handling |
| homepage | |
| repository | https://github.com/ymc-github/sleep-utils |
| max_upload_size | |
| id | 1916174 |
| size | 182,634 |
A smart sleep utilities library for Rust with flexible input formats and automatic zero-value handling.
Durationisize for cross-platform supportAdd this to your Cargo.toml:
[dependencies]
sleep-utils = "0.1"
use sleep_utils::smart_sleep;
use std::time::Duration;
// Various input formats
smart_sleep(100).unwrap(); // 100 milliseconds
smart_sleep("200ms").unwrap(); // 200 milliseconds
smart_sleep("1.5s").unwrap(); // 1.5 seconds
smart_sleep("2 seconds").unwrap(); // 2 seconds
smart_sleep(0).unwrap(); // no sleep
smart_sleep(-50).unwrap(); // no sleep
smart_sleep(Duration::from_secs(1)).unwrap(); // 1 second
100 → 100ms500 → 500ms0 → no sleep-100 → no sleep"100ms", "100 millis", "100 milliseconds""1s", "1 sec", "1 second", "1 seconds""1.5s", "1.5 seconds" → 1500ms"2m", "2 min", "2 minutes" → 120,000msDuration::from_millis(100)Duration::from_secs(1)smart_sleep<S: Into<SleepInput>>(input: S) -> Result<()>The primary function that accepts various input formats and performs sleep if needed.
parse_sleep_duration(input: &str) -> Result<Duration>Parses a duration string into a Duration object.
sleep(duration: Duration) -> Result<()>Standard sleep function for backward compatibility.
SleepInputRepresents different types of sleep inputs:
Number(isize)Text(String)Duration(Duration)use sleep_utils::smart_sleep;
// Sleep for 100ms
smart_sleep(100).unwrap();
// Sleep for 2 seconds
smart_sleep("2s").unwrap();
// No sleep (zero value)
smart_sleep(0).unwrap();
// No sleep (negative value)
smart_sleep(-100).unwrap();
use sleep_utils::parse_sleep_duration;
let duration = parse_sleep_duration("1.5 minutes").unwrap();
println!("Duration: {:?}", duration); // 90 seconds
use sleep_utils::{SleepInput, parse_sleep_duration};
let input = SleepInput::from("500ms");
if input.should_sleep() {
let duration = input.to_duration().unwrap();
// Custom sleep logic
std::thread::sleep(duration);
}
The library uses a custom Result<T> type and SleepError enum for error handling:
use sleep_utils::{SleepError, Result};
match smart_sleep("invalid") {
Ok(()) => println!("Sleep completed"),
Err(SleepError::InvalidDuration(msg)) => println!("Invalid duration: {}", msg),
Err(e) => println!("Other error: {}", e),
}
default (enabled by default): All features enabledminimal: Minimal feature set without complex parsingThe library uses lazy static regex patterns for efficient parsing and avoids unnecessary allocations.
Dual-licensed under:
Contributions are welcome! Please feel free to submit pull requests or open issues on GitHub.
See CHANGELOG.md for version history and changes.