diff options
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 71 |
1 files 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 <https://www.gnu.org/licenses/>. */ -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(), - "<WIDTH>".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(), - "<HEIGHT>".bold(), - "--help".bold()); - exit(2); - } +const DIMENSION_RANGE: RangeInclusive<usize> = 1..=std::usize::MAX; + +fn dimension_in_range(s: &str) -> Result<usize, String> { + 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 <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<f64> = 0.0..=1.0; + +fn skew_in_range(s: &str) -> Result<f64, String> { + 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() + )) + } } |