Skip to content

Commit

Permalink
use humantime for time parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
trusch committed Dec 18, 2024
1 parent 4779b0b commit 30b6ade
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
20 changes: 17 additions & 3 deletions src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,12 @@ impl ComputeUnit {
}

fn parse_string(s: &str) -> Result<i64, String> {

// 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
Expand All @@ -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,
Expand Down Expand Up @@ -776,6 +779,17 @@ mod tests {
let res: Result<ComputeUnit, String> = "123 this is wrong".parse();
assert!(res.is_err());
}

#[test]
fn test_duration_parsing() {
let res: Result<ComputeUnit, String> = "1hr".parse();
assert!(res.is_ok());
assert_eq!(res.unwrap().as_number(), Ok(60 * 60));

let res: Result<ComputeUnit, String> = "1hr 30min 10sec".parse();
assert!(res.is_ok());
assert_eq!(res.unwrap().as_number(), Ok(60 * 60 + 30 * 60 + 10));
}
}

#[test]
Expand Down

0 comments on commit 30b6ade

Please sign in to comment.