From d89d9ca73b2a16b430952a8d606050a8e037b420 Mon Sep 17 00:00:00 2001 From: Michael Gehring Date: Tue, 3 Feb 2015 22:19:13 +0100 Subject: [PATCH] Various functions in std::str return Result instead of Option now --- src/base64/base64.rs | 6 +++--- src/common/time.rs | 4 ++-- src/cut/ranges.rs | 35 +++++++++++++++++++++++------------ src/du/du.rs | 2 +- src/expand/expand.rs | 2 +- src/factor/factor.rs | 4 ++-- src/fmt/fmt.rs | 12 ++++++------ src/fold/fold.rs | 4 ++-- src/head/head.rs | 14 +++++++------- src/kill/kill.rs | 8 ++++---- src/mkdir/mkdir.rs | 2 +- src/mkfifo/mkfifo.rs | 6 +++--- src/nice/nice.rs | 6 +++--- src/nl/helper.rs | 8 ++++---- src/nproc/nproc.rs | 10 +++++----- src/seq/seq.rs | 4 ++-- src/shuf/shuf.rs | 14 +++++++------- src/split/split.rs | 16 ++++++++-------- src/stdbuf/libstdbuf.rs | 4 ++-- src/stdbuf/stdbuf.rs | 2 +- src/tail/tail.rs | 8 ++++---- src/test/test.rs | 4 ++-- src/truncate/truncate.rs | 6 +++--- src/unexpand/unexpand.rs | 2 +- src/uniq/uniq.rs | 2 +- src/uptime/uptime.rs | 4 ++-- 26 files changed, 100 insertions(+), 89 deletions(-) diff --git a/src/base64/base64.rs b/src/base64/base64.rs index 54ac93278..fbefc79fe 100644 --- a/src/base64/base64.rs +++ b/src/base64/base64.rs @@ -66,9 +66,9 @@ pub fn uumain(args: Vec) -> isize { let ignore_garbage = matches.opt_present("ignore-garbage"); let line_wrap = match matches.opt_str("wrap") { Some(s) => match s.parse() { - Some(s) => s, - None => { - crash!(1, "error: {}", "Argument to option 'wrap' improperly formatted."); + Ok(s) => s, + Err(e)=> { + crash!(1, "error: Argument to option 'wrap' improperly formatted: {}", e); } }, None => 76 diff --git a/src/common/time.rs b/src/common/time.rs index 7b8f9a505..6a30c6e05 100644 --- a/src/common/time.rs +++ b/src/common/time.rs @@ -29,7 +29,7 @@ pub fn from_str(string: &str) -> Result { } }; match numstr.parse::() { - Some(m) => Ok(m * times as f64), - None => Err(format!("invalid time interval '{}'", string)) + Ok(m) => Ok(m * times as f64), + Err(e) => Err(format!("invalid time interval '{}': {}", string, e)) } } diff --git a/src/cut/ranges.rs b/src/cut/ranges.rs index 1c834f89e..c97885761 100644 --- a/src/cut/ranges.rs +++ b/src/cut/ranges.rs @@ -16,30 +16,41 @@ pub struct Range { } impl std::str::FromStr for Range { - fn from_str(s: &str) -> Option { + type Err = &'static str; + + fn from_str(s: &str) -> Result { use std::usize::MAX; let mut parts = s.splitn(1, '-'); match (parts.next(), parts.next()) { (Some(nm), None) => { - nm.parse::().and_then(|nm| if nm > 0 { Some(nm) } else { None }) - .map(|nm| Range { low: nm, high: nm }) + if let Ok(nm) = nm.parse::() { + if nm > 0 { Ok(Range{ low: nm, high: nm}) } else { Err("invalid range") } + } else { + Err("invalid range") + } } (Some(n), Some(m)) if m.len() == 0 => { - n.parse::().and_then(|low| if low > 0 { Some(low) } else { None }) - .map(|low| Range { low: low, high: MAX }) + if let Ok(low) = n.parse::() { + if low > 0 { Ok(Range{ low: low, high: MAX}) } else { Err("invalid range") } + } else { + Err("invalid range") + } } (Some(n), Some(m)) if n.len() == 0 => { - m.parse::().and_then(|high| if high >= 1 { Some(high) } else { None }) - .map(|high| Range { low: 1, high: high }) + if let Ok(high) = m.parse::() { + if high > 0 { Ok(Range{ low: 1, high: high}) } else { Err("invalid range") } + } else { + Err("invalid range") + } } (Some(n), Some(m)) => { match (n.parse::(), m.parse::()) { - (Some(low), Some(high)) if low > 0 && low <= high => { - Some(Range { low: low, high: high }) + (Ok(low), Ok(high)) if low > 0 && low <= high => { + Ok(Range { low: low, high: high }) } - _ => None + _ => Err("invalid range") } } _ => unreachable!() @@ -55,8 +66,8 @@ impl Range { for item in list.split(',') { match std::str::FromStr::from_str(item) { - Some(range_item) => ranges.push(range_item), - None => return Err(format!("range '{}' was invalid", item)) + Ok(range_item) => ranges.push(range_item), + Err(e)=> return Err(format!("range '{}' was invalid: {}", item, e)) } } diff --git a/src/du/du.rs b/src/du/du.rs index bb37fcd39..76f549123 100644 --- a/src/du/du.rs +++ b/src/du/du.rs @@ -194,7 +194,7 @@ ers of 1000).", let summarize = matches.opt_present("summarize"); let max_depth_str = matches.opt_str("max-depth"); - let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::()); + let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::().ok()); match (max_depth_str, max_depth) { (Some(ref s), _) if summarize => { show_error!("summarizing conflicts with --max-depth={}", *s); diff --git a/src/expand/expand.rs b/src/expand/expand.rs index 70fc5c34d..e89b62b98 100644 --- a/src/expand/expand.rs +++ b/src/expand/expand.rs @@ -33,7 +33,7 @@ fn tabstops_parse(s: String) -> Vec { let nums = words.into_iter() .map(|sn| sn.parse::() .unwrap_or_else( - || crash!(1, "{}\n", "tab size contains invalid character(s)")) + |_| crash!(1, "{}\n", "tab size contains invalid character(s)")) ) .collect::>(); diff --git a/src/factor/factor.rs b/src/factor/factor.rs index 80e1960a3..112cd99f0 100644 --- a/src/factor/factor.rs +++ b/src/factor/factor.rs @@ -58,8 +58,8 @@ fn print_factors(num: u64) { fn print_factors_str(num_str: &str) { let num = match num_str.parse::() { - Some(x) => x, - None => { crash!(1, "{} not a number", num_str); } + Ok(x) => x, + Err(e)=> { crash!(1, "{} not a number: {}", num_str, e); } }; print_factors(num); } diff --git a/src/fmt/fmt.rs b/src/fmt/fmt.rs index 466012afa..ec0c10ba9 100644 --- a/src/fmt/fmt.rs +++ b/src/fmt/fmt.rs @@ -146,8 +146,8 @@ pub fn uumain(args: Vec) -> isize { Some(s) => { fmt_opts.width = match s.parse::() { - Some(t) => t, - None => { crash!(1, "Invalid WIDTH specification: `{}'", s); } + Ok(t) => t, + Err(e) => { crash!(1, "Invalid WIDTH specification: `{}': {}", s, e); } }; fmt_opts.goal = cmp::min(fmt_opts.width * 94 / 100, fmt_opts.width - 3); } @@ -158,8 +158,8 @@ pub fn uumain(args: Vec) -> isize { Some(s) => { fmt_opts.goal = match s.parse::() { - Some(t) => t, - None => { crash!(1, "Invalid GOAL specification: `{}'", s); } + Ok(t) => t, + Err(e) => { crash!(1, "Invalid GOAL specification: `{}': {}", s, e); } }; if !matches.opt_present("w") { fmt_opts.width = cmp::max(fmt_opts.goal * 100 / 94, fmt_opts.goal + 3); @@ -174,8 +174,8 @@ pub fn uumain(args: Vec) -> isize { Some(s) => { fmt_opts.tabwidth = match s.parse::() { - Some(t) => t, - None => { crash!(1, "Invalid TABWIDTH specification: `{}'", s); } + Ok(t) => t, + Err(e) => { crash!(1, "Invalid TABWIDTH specification: `{}': {}", s, e); } }; } None => () diff --git a/src/fold/fold.rs b/src/fold/fold.rs index e20e9dcf3..8ccd0b13c 100644 --- a/src/fold/fold.rs +++ b/src/fold/fold.rs @@ -64,8 +64,8 @@ pub fn uumain(args: Vec) -> isize { }; let width = match poss_width { Some(inp_width) => match inp_width.parse::() { - Some(width) => width, - None => crash!(1, "illegal width value (\"{}\")", inp_width) + Ok(width) => width, + Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e) }, None => 80 }; diff --git a/src/head/head.rs b/src/head/head.rs index 33b56202a..b7611130a 100644 --- a/src/head/head.rs +++ b/src/head/head.rs @@ -71,18 +71,18 @@ pub fn uumain(args: Vec) -> isize { return 1; } match n.parse::() { - Some(m) => { line_count = m } - None => { - show_error!("invalid line count '{}'", n); + Ok(m) => { line_count = m } + Err(e) => { + show_error!("invalid line count '{}': {}", n, e); return 1; } } } None => match given_options.opt_str("c") { Some(count) => match count.parse::() { - Some(m) => byte_count = m, - None => { - show_error!("invalid byte count '{}'", count); + Ok(m) => byte_count = m, + Err(e)=> { + show_error!("invalid byte count '{}': {}", count, e); return 1; } }, @@ -151,7 +151,7 @@ fn obsolete(options: &[String]) -> (Vec, Option) { // If this is the last number if pos == len - 1 { options.remove(a); - let number: Option = from_utf8(¤t[1..len]).unwrap().parse::(); + let number: Option = from_utf8(¤t[1..len]).unwrap().parse::().ok(); return (options, Some(number.unwrap())); } } diff --git a/src/kill/kill.rs b/src/kill/kill.rs index d1b979544..83f0afea4 100644 --- a/src/kill/kill.rs +++ b/src/kill/kill.rs @@ -109,13 +109,13 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { if slice.char_at(0) == '-' && slice.len() > 1 && slice.char_at(1).is_digit(10) { let val = &slice[1..]; match val.parse() { - Some(num) => { + Ok(num) => { if signals::is_signal(num) { args.remove(i); return (args, Some(val.to_string())); } } - None => break /* getopts will error out for us */ + Err(_)=> break /* getopts will error out for us */ } } i += 1; @@ -194,7 +194,7 @@ fn kill(signalname: &str, pids: std::vec::Vec) -> isize { }; for pid in pids.iter() { match pid.as_slice().parse() { - Some(x) => { + Ok(x) => { let result = Process::kill(x, signal_value as isize); match result { Ok(_) => (), @@ -204,7 +204,7 @@ fn kill(signalname: &str, pids: std::vec::Vec) -> isize { } }; }, - None => crash!(EXIT_ERR, "failed to parse argument {}", pid) + Err(e) => crash!(EXIT_ERR, "failed to parse argument {}: {}", pid, e) }; } status diff --git a/src/mkdir/mkdir.rs b/src/mkdir/mkdir.rs index 67946aaf3..c0f16e79a 100644 --- a/src/mkdir/mkdir.rs +++ b/src/mkdir/mkdir.rs @@ -64,7 +64,7 @@ pub fn uumain(args: Vec) -> isize { let mode_match = matches.opts_str(&["mode".to_string()]); let mode: FilePermission = if mode_match.is_some() { let m = mode_match.unwrap(); - let res: Option = from_str_radix(m.as_slice(), 8); + let res: Option = from_str_radix(m.as_slice(), 8).ok(); if res.is_some() { unsafe { std::mem::transmute(res.unwrap()) } } else { diff --git a/src/mkfifo/mkfifo.rs b/src/mkfifo/mkfifo.rs index c990d4cee..e76b44b15 100644 --- a/src/mkfifo/mkfifo.rs +++ b/src/mkfifo/mkfifo.rs @@ -57,9 +57,9 @@ pub fn uumain(args: Vec) -> isize { let mode = match matches.opt_str("m") { Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) { - Some(m) => m, - None => { - show_error!("invalid mode"); + Ok(m) => m, + Err(e )=> { + show_error!("invalid mode: {}", e); return 1; } }, diff --git a/src/nice/nice.rs b/src/nice/nice.rs index 3ccdd82cb..8131454fa 100644 --- a/src/nice/nice.rs +++ b/src/nice/nice.rs @@ -80,9 +80,9 @@ pub fn uumain(args: Vec) -> isize { return 125; } match nstr.as_slice().parse() { - Some(num) => num, - None => { - show_error!("\"{}\" is not a valid number", nstr); + Ok(num) => num, + Err(e)=> { + show_error!("\"{}\" is not a valid number: {}", nstr, e); return 125; } } diff --git a/src/nl/helper.rs b/src/nl/helper.rs index 7b8cc66d9..c1d0fc584 100644 --- a/src/nl/helper.rs +++ b/src/nl/helper.rs @@ -72,7 +72,7 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec< match opts.opt_str("i") { None => {} Some(val) => { - let conv: Option = val.as_slice().parse(); + let conv: Option = val.as_slice().parse().ok(); match conv { None => { errs.push(String::from_str("Illegal value for -i")); @@ -84,7 +84,7 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec< match opts.opt_str("w") { None => {} Some(val) => { - let conv: Option = val.as_slice().parse(); + let conv: Option = val.as_slice().parse().ok(); match conv { None => { errs.push(String::from_str("Illegal value for -w")); @@ -96,7 +96,7 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec< match opts.opt_str("v") { None => {} Some(val) => { - let conv: Option = val.as_slice().parse(); + let conv: Option = val.as_slice().parse().ok(); match conv { None => { errs.push(String::from_str("Illegal value for -v")); @@ -108,7 +108,7 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec< match opts.opt_str("l") { None => {} Some(val) => { - let conv: Option = val.as_slice().parse(); + let conv: Option = val.as_slice().parse().ok(); match conv { None => { errs.push(String::from_str("Illegal value for -l")); diff --git a/src/nproc/nproc.rs b/src/nproc/nproc.rs index bf050c2fb..ac8cd3f11 100644 --- a/src/nproc/nproc.rs +++ b/src/nproc/nproc.rs @@ -54,9 +54,9 @@ pub fn uumain(args: Vec) -> isize { let mut ignore = match matches.opt_str("ignore") { Some(numstr) => match numstr.parse() { - Some(num) => num, - None => { - show_error!("\"{}\" is not a valid number", numstr); + Ok(num) => num, + Err(e) => { + show_error!("\"{}\" is not a valid number: {}", numstr, e); return 1; } }, @@ -66,8 +66,8 @@ pub fn uumain(args: Vec) -> isize { if !matches.opt_present("all") { ignore += match os::getenv("OMP_NUM_THREADS") { Some(threadstr) => match threadstr.parse() { - Some(num) => num, - None => 0 + Ok(num) => num, + Err(e)=> 0 }, None => 0 }; diff --git a/src/seq/seq.rs b/src/seq/seq.rs index 3fcc93cca..2a651199b 100644 --- a/src/seq/seq.rs +++ b/src/seq/seq.rs @@ -27,8 +27,8 @@ fn parse_float(mut s: &str) -> Result { s = &s[1..]; } match s.parse() { - Some(n) => Ok(n), - None => Err(format!("seq: invalid floating point argument: {}", s)) + Ok(n) => Ok(n), + Err(e) => Err(format!("seq: invalid floating point argument `{}`: {}", s, e)) } } diff --git a/src/shuf/shuf.rs b/src/shuf/shuf.rs index faf39e96f..3e86fac30 100644 --- a/src/shuf/shuf.rs +++ b/src/shuf/shuf.rs @@ -97,9 +97,9 @@ With no FILE, or when FILE is -, read standard input.", let zero = matches.opt_present("zero-terminated"); let count = match matches.opt_str("head-count") { Some(cnt) => match cnt.parse::() { - Some(val) => val, - None => { - show_error!("'{}' is not a valid count", cnt); + Ok(val) => val, + Err(e) => { + show_error!("'{}' is not a valid count: {}", cnt, e); return 1; } }, @@ -192,12 +192,12 @@ fn parse_range(input_range: String) -> Result, (String, is Err(("invalid range format".to_string(), 1)) } else { let begin = match split[0].parse::() { - Some(m) => m, - None => return Err((format!("{} is not a valid number", split[0]), 1)) + Ok(m) => m, + Err(e)=> return Err((format!("{} is not a valid number: {}", split[0], e), 1)) }; let end = match split[1].parse::() { - Some(m) => m, - None => return Err((format!("{} is not a valid number", split[1]), 1)) + Ok(m) => m, + Err(e)=> return Err((format!("{} is not a valid number: {}", split[1], e), 1)) }; Ok(range_inclusive(begin, end)) } diff --git a/src/split/split.rs b/src/split/split.rs index e9ca79659..443310921 100644 --- a/src/split/split.rs +++ b/src/split/split.rs @@ -72,8 +72,8 @@ pub fn uumain(args: Vec) -> isize { settings.suffix_length = match matches.opt_str("a") { Some(n) => match n.as_slice().parse() { - Some(m) => m, - None => crash!(1, "cannot parse num") + Ok(m) => m, + Err(e) => crash!(1, "cannot parse num: {}", e) }, None => 2 }; @@ -136,8 +136,8 @@ struct LineSplitter { impl LineSplitter { fn new(settings: &Settings) -> Box { let n = match settings.strategy_param.as_slice().parse() { - Some(a) => a, - _ => crash!(1, "invalid number of lines") + Ok(a) => a, + Err(e) => crash!(1, "invalid number of lines: {}", e) }; Box::new(LineSplitter { saved_lines_to_write: n, @@ -178,13 +178,13 @@ impl ByteSplitter { }; let n = if suffix.is_alphabetic() { match strategy_param.as_slice().iter().map(|c| *c).collect::().as_slice().parse::() { - Some(a) => a, - _ => crash!(1, "invalid number of bytes") + Ok(a) => a, + Err(e) => crash!(1, "invalid number of bytes: {}", e) } } else { match settings.strategy_param.as_slice().parse::() { - Some(a) => a, - _ => crash!(1, "invalid number of bytes") + Ok(a) => a, + Err(e) => crash!(1, "invalid number of bytes: {}", e) } }; Box::new(ByteSplitter { diff --git a/src/stdbuf/libstdbuf.rs b/src/stdbuf/libstdbuf.rs index 4c14fab0f..755f6fbe9 100644 --- a/src/stdbuf/libstdbuf.rs +++ b/src/stdbuf/libstdbuf.rs @@ -25,8 +25,8 @@ fn set_buffer(stream: *mut FILE, value: &str) { "L" => (_IOLBF, 0 as size_t), input => { let buff_size: usize = match input.parse() { - Some(num) => num, - None => crash!(1, "incorrect size of buffer!") + Ok(num) => num, + Err(e) => crash!(1, "incorrect size of buffer!: {}", e) }; (_IOFBF, buff_size as size_t) } diff --git a/src/stdbuf/stdbuf.rs b/src/stdbuf/stdbuf.rs index 51b411d85..5ffc703bb 100644 --- a/src/stdbuf/stdbuf.rs +++ b/src/stdbuf/stdbuf.rs @@ -97,7 +97,7 @@ fn parse_size(size: &str) -> Option { if recovered.as_slice() != size { return None; } - let buf_size: u64 = match num.parse() { + let buf_size: u64 = match num.parse().ok() { Some(m) => m, None => return None, }; diff --git a/src/tail/tail.rs b/src/tail/tail.rs index 3f994ee1e..350f6567f 100644 --- a/src/tail/tail.rs +++ b/src/tail/tail.rs @@ -73,7 +73,7 @@ pub fn uumain(args: Vec) -> isize { if follow { match given_options.opt_str("s") { Some(n) => { - let parsed: Option = n.parse(); + let parsed: Option = n.parse().ok(); match parsed { Some(m) => { sleep_msec = m * 1000 } None => {} @@ -196,8 +196,8 @@ fn parse_size(mut size_slice: &str) -> Option { } else { let value = size_slice.parse(); match value { - Some(v) => Some(multiplier * v), - None => None + Ok(v) => Some(multiplier * v), + _ => None } } } @@ -224,7 +224,7 @@ fn obsolete(options: &[String]) -> (Vec, Option) { // If this is the last number if pos == len - 1 { options.remove(a); - let number: Option = from_utf8(¤t[1..len]).unwrap().parse(); + let number: Option = from_utf8(¤t[1..len]).unwrap().parse().ok(); return (options, Some(number.unwrap())); } } diff --git a/src/test/test.rs b/src/test/test.rs index 91caba31f..a3434e77a 100644 --- a/src/test/test.rs +++ b/src/test/test.rs @@ -127,7 +127,7 @@ fn integers(a: &[u8], b: &[u8], cond: IntegerCondition) -> bool { _ => return false, }; let (a, b): (i64, i64) = match (a.parse(), b.parse()) { - (Some(a), Some(b)) => (a, b), + (Ok(a), Ok(b)) => (a, b), _ => return false, }; match cond { @@ -142,7 +142,7 @@ fn integers(a: &[u8], b: &[u8], cond: IntegerCondition) -> bool { fn isatty(fd: &[u8]) -> bool { use libc::{isatty}; - from_utf8(fd).ok().and_then(|s| s.parse()) + from_utf8(fd).ok().and_then(|s| s.parse().ok()) .map(|i| unsafe { isatty(i) == 1 }).unwrap_or(false) } diff --git a/src/truncate/truncate.rs b/src/truncate/truncate.rs index b02666f68..85f35e69c 100644 --- a/src/truncate/truncate.rs +++ b/src/truncate/truncate.rs @@ -186,9 +186,9 @@ fn parse_size(size: &str) -> (u64, TruncateMode) { slice }.to_string(); let mut number: u64 = match bytes.as_slice().parse() { - Some(num) => num, - None => { - crash!(1, "'{}' is not a valid number.", size) + Ok(num) => num, + Err(e) => { + crash!(1, "'{}' is not a valid number: {}", size, e) } }; if size.char_at(size.len() - 1).is_alphabetic() { diff --git a/src/unexpand/unexpand.rs b/src/unexpand/unexpand.rs index bcf743f00..40e4ffdd4 100644 --- a/src/unexpand/unexpand.rs +++ b/src/unexpand/unexpand.rs @@ -30,7 +30,7 @@ fn tabstops_parse(s: String) -> Vec { let nums = words.into_iter() .map(|sn| sn.parse() .unwrap_or_else( - || crash!(1, "{}\n", "tab size contains invalid character(s)")) + |_| crash!(1, "{}\n", "tab size contains invalid character(s)")) ) .collect::>(); diff --git a/src/uniq/uniq.rs b/src/uniq/uniq.rs index f0e31fce2..d1fd13484 100644 --- a/src/uniq/uniq.rs +++ b/src/uniq/uniq.rs @@ -113,7 +113,7 @@ impl Uniq { fn opt_parsed(opt_name: &str, matches: &getopts::Matches) -> Option { matches.opt_str(opt_name).map(|arg_str| { - let opt_val: Option = arg_str.parse(); + let opt_val: Option = arg_str.parse().ok(); opt_val.unwrap_or_else(|| crash!(1, "Invalid argument for {}: {}", opt_name, arg_str)) }) diff --git a/src/uptime/uptime.rs b/src/uptime/uptime.rs index ca0cb645e..d872292fe 100644 --- a/src/uptime/uptime.rs +++ b/src/uptime/uptime.rs @@ -181,8 +181,8 @@ fn get_uptime(boot_time: Option) -> i64 { match uptime_text.as_slice().words().next() { Some(s) => match s.replace(".", "").as_slice().parse() { - Some(n) => n, - None => -1 + Ok(n) => n, + Err(_) => -1 }, None => -1 }