commit 63adf7d53ee1356162b87664a901df048b18b810 Author: Adrian Hedqvist Date: Wed Aug 9 22:32:40 2023 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c311279 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "timer" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b213788 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "timer" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..83395f9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,51 @@ +use std::io::Write; + +const HOUR: u64 = 60 * 60; +const MINUTE: u64 = 60; + +fn main() { + let Some(arg) = std::env::args().nth(1) else { + eprintln!("Missing time argument"); + return; + }; + let start = std::time::Instant::now(); + + let parts: Vec<&str> = arg.split(':').collect(); + let secs = match parts[..] { + [s] => s.parse::().expect("parse seconds"), + [m, s] => { + s.parse::().expect("parse seconds") + + m.parse::().expect("parse minutes") * MINUTE + } + [h, m, s] => { + s.parse::().expect("parse seconds") + + m.parse::().expect("parse minutes") * MINUTE + + h.parse::().expect("parse hours") * HOUR + } + _ => { + eprintln!("Invalid time format: {arg}"); + return; + } + }; + let show_hours = secs > HOUR; + let duration = std::time::Duration::from_secs(secs); + let stop = start + duration; + let mut now = std::time::Instant::now(); + + while now < stop { + let rem = stop - now; + let rems = rem.as_secs(); + let h = rems / HOUR; + let m = (rems / MINUTE) % 60; + let s = rems % 60; + if show_hours { + print!("\r{h:02}:{m:02}:{s:02}"); + } else { + print!("\r{m:02}:{s:02}"); + } + std::io::stdout().lock().flush().expect("stdout lock"); + std::thread::sleep(std::time::Duration::from_secs(1)); + now = std::time::Instant::now(); + } + println!(); +}