Various functions in std::str return Result instead of Option now

This commit is contained in:
Michael Gehring 2015-02-03 22:19:13 +01:00
parent 05709c37d6
commit d89d9ca73b
26 changed files with 100 additions and 89 deletions

View file

@ -66,9 +66,9 @@ pub fn uumain(args: Vec<String>) -> 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

View file

@ -29,7 +29,7 @@ pub fn from_str(string: &str) -> Result<f64, String> {
}
};
match numstr.parse::<f64>() {
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))
}
}

View file

@ -16,30 +16,41 @@ pub struct Range {
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
type Err = &'static str;
fn from_str(s: &str) -> Result<Range, &'static str> {
use std::usize::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
nm.parse::<usize>().and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
if let Ok(nm) = nm.parse::<usize>() {
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::<usize>().and_then(|low| if low > 0 { Some(low) } else { None })
.map(|low| Range { low: low, high: MAX })
if let Ok(low) = n.parse::<usize>() {
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::<usize>().and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
if let Ok(high) = m.parse::<usize>() {
if high > 0 { Ok(Range{ low: 1, high: high}) } else { Err("invalid range") }
} else {
Err("invalid range")
}
}
(Some(n), Some(m)) => {
match (n.parse::<usize>(), m.parse::<usize>()) {
(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))
}
}

View file

@ -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::<usize>());
let max_depth = max_depth_str.as_ref().and_then(|s| s.parse::<usize>().ok());
match (max_depth_str, max_depth) {
(Some(ref s), _) if summarize => {
show_error!("summarizing conflicts with --max-depth={}", *s);

View file

@ -33,7 +33,7 @@ fn tabstops_parse(s: String) -> Vec<usize> {
let nums = words.into_iter()
.map(|sn| sn.parse::<usize>()
.unwrap_or_else(
|| crash!(1, "{}\n", "tab size contains invalid character(s)"))
|_| crash!(1, "{}\n", "tab size contains invalid character(s)"))
)
.collect::<Vec<usize>>();

View file

@ -58,8 +58,8 @@ fn print_factors(num: u64) {
fn print_factors_str(num_str: &str) {
let num = match num_str.parse::<u64>() {
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);
}

View file

@ -146,8 +146,8 @@ pub fn uumain(args: Vec<String>) -> isize {
Some(s) => {
fmt_opts.width =
match s.parse::<usize>() {
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<String>) -> isize {
Some(s) => {
fmt_opts.goal =
match s.parse::<usize>() {
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<String>) -> isize {
Some(s) => {
fmt_opts.tabwidth =
match s.parse::<usize>() {
Some(t) => t,
None => { crash!(1, "Invalid TABWIDTH specification: `{}'", s); }
Ok(t) => t,
Err(e) => { crash!(1, "Invalid TABWIDTH specification: `{}': {}", s, e); }
};
}
None => ()

View file

@ -64,8 +64,8 @@ pub fn uumain(args: Vec<String>) -> isize {
};
let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() {
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
};

View file

@ -71,18 +71,18 @@ pub fn uumain(args: Vec<String>) -> isize {
return 1;
}
match n.parse::<usize>() {
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::<usize>() {
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<String>, Option<usize>) {
// If this is the last number
if pos == len - 1 {
options.remove(a);
let number: Option<usize> = from_utf8(&current[1..len]).unwrap().parse::<usize>();
let number: Option<usize> = from_utf8(&current[1..len]).unwrap().parse::<usize>().ok();
return (options, Some(number.unwrap()));
}
}

View file

@ -109,13 +109,13 @@ fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) {
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<String>) -> 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<String>) -> isize {
}
};
},
None => crash!(EXIT_ERR, "failed to parse argument {}", pid)
Err(e) => crash!(EXIT_ERR, "failed to parse argument {}: {}", pid, e)
};
}
status

View file

@ -64,7 +64,7 @@ pub fn uumain(args: Vec<String>) -> 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<u32> = from_str_radix(m.as_slice(), 8);
let res: Option<u32> = from_str_radix(m.as_slice(), 8).ok();
if res.is_some() {
unsafe { std::mem::transmute(res.unwrap()) }
} else {

View file

@ -57,9 +57,9 @@ pub fn uumain(args: Vec<String>) -> 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;
}
},

View file

@ -80,9 +80,9 @@ pub fn uumain(args: Vec<String>) -> 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;
}
}

View file

@ -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<u64> = val.as_slice().parse();
let conv: Option<u64> = 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<usize> = val.as_slice().parse();
let conv: Option<usize> = 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<u64> = val.as_slice().parse();
let conv: Option<u64> = 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<u64> = val.as_slice().parse();
let conv: Option<u64> = val.as_slice().parse().ok();
match conv {
None => {
errs.push(String::from_str("Illegal value for -l"));

View file

@ -54,9 +54,9 @@ pub fn uumain(args: Vec<String>) -> 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<String>) -> 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
};

View file

@ -27,8 +27,8 @@ fn parse_float(mut s: &str) -> Result<f64, String> {
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))
}
}

View file

@ -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::<usize>() {
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<RangeInclusive<usize>, (String, is
Err(("invalid range format".to_string(), 1))
} else {
let begin = match split[0].parse::<usize>() {
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::<usize>() {
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))
}

View file

@ -72,8 +72,8 @@ pub fn uumain(args: Vec<String>) -> 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<Splitter> {
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::<String>().as_slice().parse::<usize>() {
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::<usize>() {
Some(a) => a,
_ => crash!(1, "invalid number of bytes")
Ok(a) => a,
Err(e) => crash!(1, "invalid number of bytes: {}", e)
}
};
Box::new(ByteSplitter {

View file

@ -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)
}

View file

@ -97,7 +97,7 @@ fn parse_size(size: &str) -> Option<u64> {
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,
};

View file

@ -73,7 +73,7 @@ pub fn uumain(args: Vec<String>) -> isize {
if follow {
match given_options.opt_str("s") {
Some(n) => {
let parsed: Option<u64> = n.parse();
let parsed: Option<u64> = n.parse().ok();
match parsed {
Some(m) => { sleep_msec = m * 1000 }
None => {}
@ -196,8 +196,8 @@ fn parse_size(mut size_slice: &str) -> Option<usize> {
} 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<String>, Option<usize>) {
// If this is the last number
if pos == len - 1 {
options.remove(a);
let number: Option<usize> = from_utf8(&current[1..len]).unwrap().parse();
let number: Option<usize> = from_utf8(&current[1..len]).unwrap().parse().ok();
return (options, Some(number.unwrap()));
}
}

View file

@ -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)
}

View file

@ -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() {

View file

@ -30,7 +30,7 @@ fn tabstops_parse(s: String) -> Vec<usize> {
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::<Vec<usize>>();

View file

@ -113,7 +113,7 @@ impl Uniq {
fn opt_parsed<T: FromStr>(opt_name: &str, matches: &getopts::Matches) -> Option<T> {
matches.opt_str(opt_name).map(|arg_str| {
let opt_val: Option<T> = arg_str.parse();
let opt_val: Option<T> = arg_str.parse().ok();
opt_val.unwrap_or_else(||
crash!(1, "Invalid argument for {}: {}", opt_name, arg_str))
})

View file

@ -181,8 +181,8 @@ fn get_uptime(boot_time: Option<time_t>) -> 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
}