From 43f4c8add00b363bd79c580d30a36399d84ab24d Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Sun, 6 Aug 2023 20:32:16 +0200 Subject: Move args parsing to Flags::parse --- src/main.rs | 53 ++++++++++++++++++++++++++++------------------------- 1 file changed, 28 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index cca7c87..ab47e83 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,6 +27,33 @@ struct Flags { pub verbose: bool, } +impl Flags { + fn parse() -> Result<(Flags, Vec), lexopt::Error> { + use lexopt::prelude::*; + + let mut rest = Vec::with_capacity(env::args().len()); + let mut flags = Flags::default(); + let mut parser = lexopt::Parser::from_env(); + + while let Some(arg) = parser.next()? { + match arg { + Short('0') | Long("nul") => flags.nul = true, + Short('d') | Long("dryrun") => flags.dryrun = true, + Short('e') | Long("encode") => flags.encode = true, + Short('i') | Long("individual") => flags.individual = true, + Short('v') | Long("verbose") => flags.verbose = true, + Value(v) => { + rest.push(v); + rest.extend(iter::from_fn(|| parser.value().ok())); + } + _ => return Err(arg.unexpected()), + } + } + + Ok((flags, rest)) + } +} + fn usage(bad_flags: Option) -> ! { let p = env::args().next().unwrap(); if let Some(e) = bad_flags { @@ -43,7 +70,7 @@ fn main() { } fn work() -> Result<(), io::Error> { - let (flags, rest) = match parse_args() { + let (flags, rest) = match Flags::parse() { Ok(a) => a, Err(e) => usage(Some(e)), }; @@ -172,30 +199,6 @@ fn work() -> Result<(), io::Error> { Ok(()) } -fn parse_args() -> Result<(Flags, Vec), lexopt::Error> { - use lexopt::prelude::*; - - let mut rest = Vec::with_capacity(env::args().len()); - let mut flags = Flags::default(); - let mut parser = lexopt::Parser::from_env(); - while let Some(arg) = parser.next()? { - match arg { - Short('0') | Long("nul") => flags.nul = true, - Short('d') | Long("dryrun") => flags.dryrun = true, - Short('e') | Long("encode") => flags.encode = true, - Short('i') | Long("individual") => flags.individual = true, - Short('v') | Long("verbose") => flags.verbose = true, - Value(v) => { - rest.push(v); - rest.extend(iter::from_fn(|| parser.value().ok())); - } - _ => return Err(arg.unexpected()), - } - } - - Ok((flags, rest)) -} - fn encode_string(s: &str) -> String { s.chars() .flat_map(|c| { -- cgit v1.2.3