From ec0300cfcddf589cdeb00e0a0629efac75edc9ca96d8e8ccd1c9f35ded1ef1a8 Mon Sep 17 00:00:00 2001 From: Nicholas Johnson Date: Sat, 20 Apr 2024 00:00:00 +0000 Subject: Replace hardcoded error msgs with custom parsing --- src/main.rs | 71 +++++++++++++++++++++++++++++++++---------------------------- 1 file changed, 38 insertions(+), 33 deletions(-) diff --git a/src/main.rs b/src/main.rs index 0da3b0e..0aba5f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,9 +16,8 @@ along with this program. If not, see . */ -use clap::{value_parser, Parser}; -use colored::Colorize; -use std::process::exit; +use clap::Parser; +use std::ops::RangeInclusive; mod hitomezashi; @@ -26,17 +25,17 @@ mod hitomezashi; #[command(version, about, long_about = None)] // Read from `Cargo.toml` struct Cli { /// Pattern width - #[arg(value_parser = value_parser!(usize))] + #[arg(value_parser = dimension_in_range)] width: usize, /// Pattern height - #[arg(value_parser = value_parser!(usize))] + #[arg(value_parser = dimension_in_range)] height: usize, /// Set skew #[arg(short, long)] #[arg(default_value_t = 0.5)] - #[arg(value_parser = value_parser!(f64))] + #[arg(value_parser = skew_in_range)] skew: f64, } @@ -44,35 +43,41 @@ struct Cli { fn main() { let cli = Cli::parse(); - // validate bounds of width [1..] - if cli.width < 1 { - println!("{} invalid value '{}' for '{}': valid values are [1..]\n\nFor more information, try '{}'.", - "error:".red().bold(), - cli.width.to_string().yellow(), - "".bold(), - "--help".bold()); - exit(2); - } + hitomezashi::hitomezashi(cli.width, cli.height, Some(cli.skew)); +} - // validate bounds of height [1..] - if cli.height < 1 { - println!("{} invalid value '{}' for '{}': valid values are [1..]\n\nFor more information, try '{}'.", - "error:".red().bold(), - cli.height.to_string().yellow(), - "".bold(), - "--help".bold()); - exit(2); - } +const DIMENSION_RANGE: RangeInclusive = 1..=std::usize::MAX; + +fn dimension_in_range(s: &str) -> Result { + let dimension: usize = s + .parse() + .map_err(|_| format!("`{s}` isn't a dimension value!"))?; - // validate bounds of skew [0-1] - if cli.skew < 0.0 || cli.skew > 1.0 { - println!("{} invalid value '{}' for '{}': valid values are [0-1]\n\nFor more information, try '{}'.", - "error:".red().bold(), - cli.skew.to_string().yellow(), - "--skew ".bold(), - "--help".bold()); - exit(2); + if DIMENSION_RANGE.contains(&dimension) { + Ok(dimension) + } else { + Err(format!( + "Dimension not in range {}-{}", + DIMENSION_RANGE.start(), + DIMENSION_RANGE.end() + )) } +} - hitomezashi::hitomezashi(cli.width, cli.height, Some(cli.skew)); +const SKEW_RANGE: RangeInclusive = 0.0..=1.0; + +fn skew_in_range(s: &str) -> Result { + let skew: f64 = s + .parse() + .map_err(|_| format!("`{s}` isn't a skew value!"))?; + + if SKEW_RANGE.contains(&skew) { + Ok(skew) + } else { + Err(format!( + "Skew not in range {}-{}", + SKEW_RANGE.start(), + SKEW_RANGE.end() + )) + } } -- cgit v1.2.3