mirror of
https://github.com/jht5945/rust_util.git
synced 2025-12-29 00:20:04 +08:00
feat: add parse_duration
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
use std::time::SystemTime;
|
use std::time::SystemTime;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
pub fn get_current_secs() -> u64 {
|
pub fn get_current_secs() -> u64 {
|
||||||
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0 /* SHOULD NOT HAPPEN */ )
|
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0 /* SHOULD NOT HAPPEN */ )
|
||||||
@@ -7,3 +8,35 @@ pub fn get_current_secs() -> u64 {
|
|||||||
pub fn get_current_millis() -> u128 {
|
pub fn get_current_millis() -> u128 {
|
||||||
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0 /* SHOULD NOT HAPPEN */ )
|
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0 /* SHOULD NOT HAPPEN */ )
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn parse_duration(t: &str) -> Option<Duration> {
|
||||||
|
if t.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let parse_and_process_time = |mul: u32| {
|
||||||
|
t[..t.len() - 1].parse::<f64>().map(|ti| Duration::from_millis((ti * mul as f64) as u64)).ok()
|
||||||
|
};
|
||||||
|
match t.to_ascii_lowercase().chars().last() {
|
||||||
|
Some('s') => parse_and_process_time(1000),
|
||||||
|
Some('m') => parse_and_process_time(60 * 1000),
|
||||||
|
Some('h') => parse_and_process_time(60 * 60 * 1000),
|
||||||
|
Some('d') => parse_and_process_time(24 * 60 * 60 * 1000),
|
||||||
|
_ => t.parse::<u64>().map(|t| Duration::from_millis(t)).ok(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_parse_duration() {
|
||||||
|
assert_eq!(None, parse_duration(""));
|
||||||
|
assert_eq!(None, parse_duration("X"));
|
||||||
|
assert_eq!(None, parse_duration("S"));
|
||||||
|
assert_eq!(Duration::from_millis(1), parse_duration("1").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(100), parse_duration("100").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(1000), parse_duration("1s").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(2000), parse_duration("2S").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(1500), parse_duration("1.5s").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(60000), parse_duration("1m").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(3600000), parse_duration("1h").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(1800000), parse_duration("0.5h").unwrap());
|
||||||
|
assert_eq!(Duration::from_millis(24*3600000), parse_duration("1d").unwrap());
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user