From 30b6ade6f75713cc6aa6b58076058f08f92c76cd Mon Sep 17 00:00:00 2001 From: Tino Rusch Date: Wed, 18 Dec 2024 10:31:12 +0100 Subject: [PATCH] use humantime for time parsing --- Cargo.lock | 1 + Cargo.toml | 1 + src/models.rs | 20 +++++++++++++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4be15bc..e56f592 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,6 +758,7 @@ dependencies = [ "derive_builder", "hex", "http 1.1.0", + "humantime", "log", "pretty_env_logger", "prost 0.13.3", diff --git a/Cargo.toml b/Cargo.toml index 7aef6bf..da5acad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ thiserror = "1" tokio = { version = "1", features = ["full"] } tonic = { version = "0.12", features = ["tls", "tls-native-roots"] } backon = "1.2.0" +humantime = "2.1.0" [dev-dependencies] pretty_env_logger = "0.5.0" diff --git a/src/models.rs b/src/models.rs index a71a010..dc49dac 100644 --- a/src/models.rs +++ b/src/models.rs @@ -658,6 +658,12 @@ impl ComputeUnit { } fn parse_string(s: &str) -> Result { + + // first check if its a duration using humantime + if let Ok(duration) = humantime::parse_duration(s) { + return Ok(duration.as_secs() as i64); + } + let numeric: String = s.chars().take_while(|c| c.is_digit(10)).collect(); let unit = s[numeric.len()..].to_lowercase().replace(" ", ""); let base: i64 = numeric @@ -670,9 +676,6 @@ impl ComputeUnit { "mb" | "m" => 1024 * 1024, "gb" | "g" => 1024 * 1024 * 1024, "tb" | "t" => 1024 * 1024 * 1024 * 1024, - "min" => 60, - "hr" | "h" => 60 * 60, - "day" | "d" => 60 * 60 * 24, "cpu" | "cpus" | "core" | "cores" => 1000, "gpu" | "gpus" => 1000, "mcpu" | "mcpus" | "millicpu" | "millicpus" => 1, @@ -776,6 +779,17 @@ mod tests { let res: Result = "123 this is wrong".parse(); assert!(res.is_err()); } + + #[test] + fn test_duration_parsing() { + let res: Result = "1hr".parse(); + assert!(res.is_ok()); + assert_eq!(res.unwrap().as_number(), Ok(60 * 60)); + + let res: Result = "1hr 30min 10sec".parse(); + assert!(res.is_ok()); + assert_eq!(res.unwrap().as_number(), Ok(60 * 60 + 30 * 60 + 10)); + } } #[test]