From 1a4ff7c28a1dc8ee3e1aa22e8e5941b37e7d1adc Mon Sep 17 00:00:00 2001 From: a14m Date: Thu, 1 Apr 2021 23:35:51 +0200 Subject: Add CLI Width/Height validations --- CLI/rust/src/game_of_life/opts.rs | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 CLI/rust/src/game_of_life/opts.rs (limited to 'CLI/rust/src/game_of_life') diff --git a/CLI/rust/src/game_of_life/opts.rs b/CLI/rust/src/game_of_life/opts.rs new file mode 100644 index 0000000..c0ece98 --- /dev/null +++ b/CLI/rust/src/game_of_life/opts.rs @@ -0,0 +1,40 @@ +/// Clap validators module +/// +/// Used for validating different CLI args (like width, height and delay) +/// Ref: https://docs.rs/clap/3.0.0-beta.2/clap/struct.Arg.html#method.validator +pub(crate) mod validators { + use terminal_size::{terminal_size, Height, Width}; + + /// Validator to check if width configuration can be used + /// + /// The maximum width allowed is the current terminal window width + pub(crate) fn is_fitting_term_width(val: &str) -> Result<(), String> { + let (Width(term_width), Height(_)) = terminal_size().unwrap(); + match val.parse::() { + Ok(n) if n > 0 && n <= term_width => Ok(()), + Ok(_) => Err(format!( + "must be between 1 and {} (current terminal width)", + term_width + )), + Err(e) => Err(e.to_string()), + } + } + + /// Validator to check if height configuration can be used + /// + /// The maximum height allowed is the current terminal window height - 2 + /// The last 2 lines are used for status reporting (seed/input) and space + /// for ease of use + pub(crate) fn is_fitting_term_height(val: &str) -> Result<(), String> { + let (Width(_), Height(term_height)) = terminal_size().unwrap(); + let term_height = term_height - 2; + match val.parse::() { + Ok(n) if n > 0 && n <= term_height => Ok(()), + Ok(_) => Err(format!( + "must be between 1 and {} (current terminal height)", + term_height + )), + Err(e) => Err(e.to_string()), + } + } +} -- cgit v1.2.3