Merge pull request #2398 from youknowone/err-return

clean up returning Err
This commit is contained in:
Terts Diepraam 2021-06-12 00:14:28 +02:00 committed by GitHub
commit b7460a61a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 195 additions and 286 deletions

View file

@ -54,15 +54,13 @@ impl Config {
None => None,
};
let cols = match options.value_of(options::WRAP) {
Some(num) => match num.parse::<usize>() {
Ok(n) => Some(n),
Err(e) => {
return Err(format!("Invalid wrap size: {}: {}", num, e));
}
},
None => None,
};
let cols = options
.value_of(options::WRAP)
.map(|num| {
num.parse::<usize>()
.map_err(|e| format!("Invalid wrap size: {}: {}", num, e))
})
.transpose()?;
Ok(Config {
decode: options.is_present(options::DECODE),

View file

@ -278,37 +278,25 @@ fn parse_spec(spec: &str) -> Result<(Option<u32>, Option<u32>), String> {
let usr_only = args.len() == 1 && !args[0].is_empty();
let grp_only = args.len() == 2 && args[0].is_empty();
let usr_grp = args.len() == 2 && !args[0].is_empty() && !args[1].is_empty();
if usr_only {
Ok((
Some(match Passwd::locate(args[0]) {
Ok(v) => v.uid(),
_ => return Err(format!("invalid user: {}", spec)),
}),
None,
))
} else if grp_only {
Ok((
None,
Some(match Group::locate(args[1]) {
Ok(v) => v.gid(),
_ => return Err(format!("invalid group: {}", spec)),
}),
))
} else if usr_grp {
Ok((
Some(match Passwd::locate(args[0]) {
Ok(v) => v.uid(),
_ => return Err(format!("invalid user: {}", spec)),
}),
Some(match Group::locate(args[1]) {
Ok(v) => v.gid(),
_ => return Err(format!("invalid group: {}", spec)),
}),
))
let uid = if usr_only || usr_grp {
Some(
Passwd::locate(args[0])
.map_err(|_| format!("invalid user: {}", spec))?
.uid(),
)
} else {
Ok((None, None))
}
None
};
let gid = if grp_only || usr_grp {
Some(
Group::locate(args[1])
.map_err(|_| format!("invalid group: {}", spec))?
.gid(),
)
} else {
None
};
Ok((uid, gid))
}
enum IfFrom {
@ -497,3 +485,17 @@ impl Chowner {
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_spec() {
assert_eq!(parse_spec(":"), Ok((None, None)));
assert!(parse_spec("::")
.err()
.unwrap()
.starts_with("invalid group: "));
}
}

View file

@ -160,18 +160,14 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> {
let mut bytes = init_byte_array();
loop {
match rd.read(&mut bytes) {
Ok(num_bytes) => {
if num_bytes == 0 {
return Ok((crc_final(crc, size), size));
}
for &b in bytes[..num_bytes].iter() {
crc = crc_update(crc, b);
}
size += num_bytes;
}
Err(err) => return Err(err),
let num_bytes = rd.read(&mut bytes)?;
if num_bytes == 0 {
return Ok((crc_final(crc, size), size));
}
for &b in bytes[..num_bytes].iter() {
crc = crc_update(crc, b);
}
size += num_bytes;
}
}

View file

@ -709,27 +709,26 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec<S
return Err(format!("extra operand {:?}", paths[2]).into());
}
let (mut sources, target) = match options.target_dir {
let target = match options.target_dir {
Some(ref target) => {
// All path args are sources, and the target dir was
// specified separately
(paths, PathBuf::from(target))
PathBuf::from(target)
}
None => {
// If there was no explicit target-dir, then use the last
// path_arg
let target = paths.pop().unwrap();
(paths, target)
paths.pop().unwrap()
}
};
if options.strip_trailing_slashes {
for source in sources.iter_mut() {
for source in paths.iter_mut() {
*source = source.components().as_path().to_owned()
}
}
Ok((sources, target))
Ok((paths, target))
}
fn preserve_hardlinks(
@ -1271,15 +1270,15 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes
ReflinkMode::Always => unsafe {
let result = ficlone(dst_file.as_raw_fd(), src_file.as_raw_fd() as *const i32);
if result != 0 {
return Err(format!(
Err(format!(
"failed to clone {:?} from {:?}: {}",
source,
dest,
std::io::Error::last_os_error()
)
.into());
.into())
} else {
return Ok(());
Ok(())
}
},
ReflinkMode::Auto => unsafe {
@ -1287,11 +1286,10 @@ fn copy_on_write_linux(source: &Path, dest: &Path, mode: ReflinkMode) -> CopyRes
if result != 0 {
fs::copy(source, dest).context(&*context_for(source, dest))?;
}
Ok(())
},
ReflinkMode::Never => unreachable!(),
}
Ok(())
}
/// Copies `source` to `dest` using copy-on-write if possible.

View file

@ -133,20 +133,12 @@ fn extract_patterns(args: &[String]) -> Result<Vec<Pattern>, CsplitError> {
Some(m) => m.as_str().parse().unwrap(),
};
if let Some(up_to_match) = captures.name("UPTO") {
let pattern = match Regex::new(up_to_match.as_str()) {
Err(_) => {
return Err(CsplitError::InvalidPattern(arg.to_string()));
}
Ok(reg) => reg,
};
let pattern = Regex::new(up_to_match.as_str())
.map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?;
patterns.push(Pattern::UpToMatch(pattern, offset, execute_ntimes));
} else if let Some(skip_to_match) = captures.name("SKIPTO") {
let pattern = match Regex::new(skip_to_match.as_str()) {
Err(_) => {
return Err(CsplitError::InvalidPattern(arg.to_string()));
}
Ok(reg) => reg,
};
let pattern = Regex::new(skip_to_match.as_str())
.map_err(|_| CsplitError::InvalidPattern(arg.to_string()))?;
patterns.push(Pattern::SkipToMatch(pattern, offset, execute_ntimes));
}
} else if let Ok(line_number) = arg.parse::<usize>() {

View file

@ -33,13 +33,13 @@ impl SplitName {
// get the prefix
let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string());
// the width for the split offset
let n_digits = match n_digits_opt {
None => 2,
Some(opt) => match opt.parse::<usize>() {
Ok(digits) => digits,
Err(_) => return Err(CsplitError::InvalidNumber(opt)),
},
};
let n_digits = n_digits_opt
.map(|opt| {
opt.parse::<usize>()
.map_err(|_| CsplitError::InvalidNumber(opt))
})
.transpose()?
.unwrap_or(2);
// translate the custom format into a function
let fn_split_name: Box<dyn Fn(usize) -> String> = match format_opt {
None => Box::new(move |n: usize| -> String {

18
src/uu/env/src/env.rs vendored
View file

@ -82,13 +82,10 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> {
Ini::load_from_file(file)
};
let conf = match conf {
Ok(config) => config,
Err(error) => {
eprintln!("env: error: \"{}\": {}", file, error);
return Err(1);
}
};
let conf = conf.map_err(|error| {
eprintln!("env: error: \"{}\": {}", file, error);
1
})?;
for (_, prop) in &conf {
// ignore all INI section lines (treat them as comments)
@ -256,13 +253,10 @@ fn run_env(args: impl uucore::Args) -> Result<(), i32> {
// FIXME: this should just use execvp() (no fork()) on Unix-like systems
match Command::new(&*prog).args(args).status() {
Ok(exit) => {
if !exit.success() {
return Err(exit.code().unwrap());
}
}
Ok(exit) if !exit.success() => return Err(exit.code().unwrap()),
Err(ref err) if err.kind() == io::ErrorKind::NotFound => return Err(127),
Err(_) => return Err(126),
Ok(_) => (),
}
} else {
// no program provided, so just dump all env vars to stdout

View file

@ -160,10 +160,8 @@ impl AstNode {
if let AstNode::Node { operands, .. } = self {
let mut out = Vec::with_capacity(operands.len());
for operand in operands {
match operand.evaluate() {
Ok(value) => out.push(value),
Err(reason) => return Err(reason),
}
let value = operand.evaluate()?;
out.push(value);
}
Ok(out)
} else {
@ -252,10 +250,8 @@ fn maybe_ast_node(
) -> Result<Box<AstNode>, String> {
let mut operands = Vec::with_capacity(arity);
for _ in 0..arity {
match ast_from_rpn(rpn) {
Err(reason) => return Err(reason),
Ok(operand) => operands.push(operand),
}
let operand = ast_from_rpn(rpn)?;
operands.push(operand);
}
operands.reverse();
Ok(AstNode::new_node(token_idx, op_type, operands))
@ -399,10 +395,12 @@ fn move_till_match_paren(
op_stack: &mut TokenStack,
) -> Result<(), String> {
loop {
match op_stack.pop() {
None => return Err("syntax error (Mismatched close-parenthesis)".to_string()),
Some((_, Token::ParOpen)) => return Ok(()),
Some(other) => out_stack.push(other),
let op = op_stack
.pop()
.ok_or_else(|| "syntax error (Mismatched close-parenthesis)".to_string())?;
match op {
(_, Token::ParOpen) => return Ok(()),
other => out_stack.push(other),
}
}
}
@ -462,22 +460,17 @@ fn infix_operator_and(values: &[String]) -> String {
fn operator_match(values: &[String]) -> Result<String, String> {
assert!(values.len() == 2);
let re = match Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep())
{
Ok(m) => m,
Err(err) => return Err(err.description().to_string()),
};
if re.captures_len() > 0 {
Ok(match re.captures(&values[0]) {
Some(captures) => captures.at(1).unwrap().to_string(),
None => "".to_string(),
})
let re = Regex::with_options(&values[1], RegexOptions::REGEX_OPTION_NONE, Syntax::grep())
.map_err(|err| err.description().to_string())?;
Ok(if re.captures_len() > 0 {
re.captures(&values[0])
.map(|captures| captures.at(1).unwrap())
.unwrap_or("")
.to_string()
} else {
Ok(match re.find(&values[0]) {
Some((start, end)) => (end - start).to_string(),
None => "0".to_string(),
})
}
re.find(&values[0])
.map_or("0".to_string(), |(start, end)| (end - start).to_string())
})
}
fn prefix_operator_length(values: &[String]) -> String {

View file

@ -176,19 +176,11 @@ impl HeadOptions {
options.zeroed = matches.is_present(options::ZERO_NAME);
let mode_and_from_end = if let Some(v) = matches.value_of(options::BYTES_NAME) {
match parse_mode(v, Modes::Bytes) {
Ok(v) => v,
Err(err) => {
return Err(format!("invalid number of bytes: {}", err));
}
}
parse_mode(v, Modes::Bytes)
.map_err(|err| format!("invalid number of bytes: {}", err))?
} else if let Some(v) = matches.value_of(options::LINES_NAME) {
match parse_mode(v, Modes::Lines) {
Ok(v) => v,
Err(err) => {
return Err(format!("invalid number of lines: {}", err));
}
}
parse_mode(v, Modes::Lines)
.map_err(|err| format!("invalid number of lines: {}", err))?
} else {
(Modes::Lines(10), false)
};

View file

@ -94,17 +94,15 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
/// the bool specifies whether to read from the end
pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> {
let mut num_start = 0;
let mut chars = src.char_indices();
let (mut chars, all_but_last) = match chars.next() {
Some((_, c)) => {
if c == '-' {
num_start += 1;
(chars, true)
} else {
(src.char_indices(), false)
}
let (mut chars, all_but_last) = {
let mut chars = src.char_indices();
let (_, c) = chars.next().ok_or(ParseError::Syntax)?;
if c == '-' {
num_start += 1;
(chars, true)
} else {
(src.char_indices(), false)
}
None => return Err(ParseError::Syntax),
};
let mut num_end = 0usize;
let mut last_char = 0 as char;
@ -120,10 +118,11 @@ pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> {
}
let num = if num_count > 0 {
match src[num_start..=num_end].parse::<usize>() {
Ok(n) => Some(n),
Err(_) => return Err(ParseError::Overflow),
}
Some(
src[num_start..=num_end]
.parse::<usize>()
.map_err(|_| ParseError::Overflow)?,
)
} else {
None
};
@ -168,10 +167,7 @@ pub fn parse_num(src: &str) -> Result<(usize, bool), ParseError> {
'y' => base.pow(8),
_ => return Err(ParseError::Syntax),
};
let mul = match usize::try_from(mul) {
Ok(n) => n,
Err(_) => return Err(ParseError::Overflow),
};
let mul = usize::try_from(mul).map_err(|_| ParseError::Overflow)?;
match num.unwrap_or(1).checked_mul(mul) {
Some(n) => Ok((n, all_but_last)),
None => Err(ParseError::Overflow),

View file

@ -299,29 +299,17 @@ fn behavior(matches: &ArgMatches) -> Result<Behavior, i32> {
let considering_dir: bool = MainFunction::Directory == main_function;
let specified_mode: Option<u32> = if matches.is_present(OPT_MODE) {
match matches.value_of(OPT_MODE) {
Some(x) => match mode::parse(x, considering_dir) {
Ok(y) => Some(y),
Err(err) => {
show_error!("Invalid mode string: {}", err);
return Err(1);
}
},
None => {
return Err(1);
}
}
let x = matches.value_of(OPT_MODE).ok_or(1)?;
Some(mode::parse(x, considering_dir).map_err(|err| {
show_error!("Invalid mode string: {}", err);
1
})?)
} else {
None
};
let backup_suffix = if matches.is_present(OPT_SUFFIX) {
match matches.value_of(OPT_SUFFIX) {
Some(x) => x,
None => {
return Err(1);
}
}
matches.value_of(OPT_SUFFIX).ok_or(1)?
} else {
"~"
};

View file

@ -247,7 +247,7 @@ fn nl<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
let mut line_filter: fn(&str, &regex::Regex) -> bool = pass_regex;
for mut l in reader.lines().map(|r| r.unwrap()) {
// Sanitize the string. We want to print the newline ourselves.
if l.chars().last() == Some('\n') {
if l.ends_with('\n') {
l.pop();
}
// Next we iterate through the individual chars to see if this

View file

@ -128,36 +128,27 @@ impl OdOptions {
}
};
let mut skip_bytes = match matches.value_of(options::SKIP_BYTES) {
None => 0,
Some(s) => match parse_number_of_bytes(s) {
Ok(i) => i,
Err(_) => {
return Err(format!("Invalid argument --skip-bytes={}", s));
}
},
};
let mut skip_bytes = matches
.value_of(options::SKIP_BYTES)
.map(|s| {
parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --skip-bytes={}", s))
})
.transpose()?
.unwrap_or(0);
let mut label: Option<usize> = None;
let input_strings = match parse_inputs(&matches) {
Ok(CommandLineInputs::FileNames(v)) => v,
Ok(CommandLineInputs::FileAndOffset((f, s, l))) => {
let parsed_input = parse_inputs(&matches).map_err(|e| format!("Invalid inputs: {}", e))?;
let input_strings = match parsed_input {
CommandLineInputs::FileNames(v) => v,
CommandLineInputs::FileAndOffset((f, s, l)) => {
skip_bytes = s;
label = l;
vec![f]
}
Err(e) => {
return Err(format!("Invalid inputs: {}", e));
}
};
let formats = match parse_format_flags(&args) {
Ok(f) => f,
Err(e) => {
return Err(e);
}
};
let formats = parse_format_flags(&args)?;
let mut line_bytes = match matches.value_of(options::WIDTH) {
None => 16,
@ -174,15 +165,12 @@ impl OdOptions {
let output_duplicates = matches.is_present(options::OUTPUT_DUPLICATES);
let read_bytes = match matches.value_of(options::READ_BYTES) {
None => None,
Some(s) => match parse_number_of_bytes(s) {
Ok(i) => Some(i),
Err(_) => {
return Err(format!("Invalid argument --read-bytes={}", s));
}
},
};
let read_bytes = matches
.value_of(options::READ_BYTES)
.map(|s| {
parse_number_of_bytes(s).map_err(|_| format!("Invalid argument --read-bytes={}", s))
})
.transpose()?;
let radix = match matches.value_of(options::ADDRESS_RADIX) {
None => Radix::Octal,

View file

@ -108,10 +108,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
for arg in arg_iter {
if expect_type_string {
match parse_type_string(arg) {
Ok(v) => formats.extend(v.into_iter()),
Err(e) => return Err(e),
}
let v = parse_type_string(arg)?;
formats.extend(v.into_iter());
expect_type_string = false;
} else if arg.starts_with("--") {
if arg.len() == 2 {
@ -119,10 +117,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
}
if arg.starts_with("--format=") {
let params: String = arg.chars().skip_while(|c| *c != '=').skip(1).collect();
match parse_type_string(&params) {
Ok(v) => formats.extend(v.into_iter()),
Err(e) => return Err(e),
}
let v = parse_type_string(&params)?;
formats.extend(v.into_iter());
}
if arg == "--format" {
expect_type_string = true;
@ -145,10 +141,8 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
}
}
if !format_spec.is_empty() {
match parse_type_string(&format_spec) {
Ok(v) => formats.extend(v.into_iter()),
Err(e) => return Err(e),
}
let v = parse_type_string(&format_spec)?;
formats.extend(v.into_iter());
expect_type_string = false;
}
}

View file

@ -36,16 +36,15 @@ impl<R: Read> Read for PartialReader<R> {
while self.skip > 0 {
let skip_count = cmp::min(self.skip, MAX_SKIP_BUFFER);
match self.inner.read(&mut bytes[..skip_count]) {
Ok(0) => {
match self.inner.read(&mut bytes[..skip_count])? {
0 => {
// this is an error as we still have more to skip
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"tried to skip past end of input",
));
}
Ok(n) => self.skip -= n,
Err(e) => return Err(e),
n => self.skip -= n,
}
}
}

View file

@ -671,8 +671,7 @@ fn build_options(
if start_page > end_page {
return Err(PrError::EncounteredErrors(format!(
"invalid --pages argument '{}:{}'",
start_page,
end_page
start_page, end_page
)));
}
}
@ -999,8 +998,8 @@ fn mpr(paths: &[String], options: &OutputOptions) -> Result<i32, PrError> {
for (_key, file_line_group) in file_line_groups.into_iter() {
for file_line in file_line_group {
if file_line.line_content.is_err() {
return Err(file_line.line_content.unwrap_err().into());
if let Err(e) = file_line.line_content {
return Err(e.into());
}
let new_page_number = file_line.page_number;
if page_counter != new_page_number {

View file

@ -109,17 +109,14 @@ fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Resu
}
fn remove_dir(path: &Path, ignore: bool, verbose: bool) -> Result<(), i32> {
let mut read_dir = match fs::read_dir(path) {
Ok(m) => m,
Err(e) if e.raw_os_error() == Some(ENOTDIR) => {
let mut read_dir = fs::read_dir(path).map_err(|e| {
if e.raw_os_error() == Some(ENOTDIR) {
show_error!("failed to remove '{}': Not a directory", path.display());
return Err(1);
}
Err(e) => {
} else {
show_error!("reading directory '{}': {}", path.display(), e);
return Err(1);
}
};
1
})?;
let mut r = Ok(());

View file

@ -285,14 +285,12 @@ fn parse_range(input_range: &str) -> Result<(usize, usize), String> {
if split.len() != 2 {
Err(format!("invalid input range: '{}'", input_range))
} else {
let begin = match split[0].parse::<usize>() {
Ok(m) => m,
Err(_) => return Err(format!("invalid input range: '{}'", split[0])),
};
let end = match split[1].parse::<usize>() {
Ok(m) => m,
Err(_) => return Err(format!("invalid input range: '{}'", split[1])),
};
let begin = split[0]
.parse::<usize>()
.map_err(|_| format!("invalid input range: '{}'", split[0]))?;
let end = split[1]
.parse::<usize>()
.map_err(|_| format!("invalid input range: '{}'", split[1]))?;
Ok((begin, end + 1))
}
}

View file

@ -152,10 +152,8 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result<BufferType, ProgramO
}
}
x => {
let size = match parse_size(x) {
Some(m) => m,
None => return Err(ProgramOptionsError(format!("invalid mode {}", x))),
};
let size = parse_size(x)
.ok_or_else(|| ProgramOptionsError(format!("invalid mode {}", x)))?;
Ok(BufferType::Size(size))
}
},

View file

@ -101,6 +101,7 @@ pub fn get_groups_gnu(arg_id: Option<u32>) -> IOResult<Vec<gid_t>> {
Ok(sort_groups(groups, egid))
}
#[cfg(all(unix, feature = "process"))]
fn sort_groups(mut groups: Vec<gid_t>, egid: gid_t) -> Vec<gid_t> {
if let Some(index) = groups.iter().position(|&x| x == egid) {
groups[..=index].rotate_right(1);

View file

@ -113,22 +113,14 @@ fn resolve<P: AsRef<Path>>(original: P) -> IOResult<PathBuf> {
));
}
match fs::symlink_metadata(&result) {
Err(e) => return Err(e),
Ok(ref m) if !m.file_type().is_symlink() => break,
Ok(..) => {
followed += 1;
match fs::read_link(&result) {
Ok(path) => {
result.pop();
result.push(path);
}
Err(e) => {
return Err(e);
}
}
}
if !fs::symlink_metadata(&result)?.file_type().is_symlink() {
break;
}
followed += 1;
let path = fs::read_link(&result)?;
result.pop();
result.push(path);
}
Ok(result)
}
@ -193,10 +185,8 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
}
match resolve(&result) {
Err(e) => match can_mode {
CanonicalizeMode::Missing => continue,
_ => return Err(e),
},
Err(_) if can_mode == CanonicalizeMode::Missing => continue,
Err(e) => return Err(e),
Ok(path) => {
result.pop();
result.push(path);
@ -211,15 +201,14 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
}
match resolve(&result) {
Err(e) => {
if can_mode == CanonicalizeMode::Existing {
return Err(e);
}
Err(e) if can_mode == CanonicalizeMode::Existing => {
return Err(e);
}
Ok(path) => {
result.pop();
result.push(path);
}
Err(_) => (),
}
}
Ok(result)

View file

@ -89,19 +89,19 @@ fn parse_levels(mode: &str) -> (u32, usize) {
}
fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> {
match mode.chars().next() {
Some(ch) => match ch {
'+' | '-' | '=' => Ok((ch, 1)),
_ => match default {
Some(ch) => Ok((ch, 0)),
None => Err(format!(
"invalid operator (expected +, -, or =, but found {})",
ch
)),
},
},
None => Err("unexpected end of mode".to_owned()),
}
let ch = mode
.chars()
.next()
.ok_or_else(|| "unexpected end of mode".to_owned())?;
Ok(match ch {
'+' | '-' | '=' => (ch, 1),
_ => {
let ch = default.ok_or_else(|| {
format!("invalid operator (expected +, -, or =, but found {})", ch)
})?;
(ch, 0)
}
})
}
fn parse_change(mode: &str, fperm: u32, considering_dir: bool) -> (u32, usize) {

View file

@ -20,20 +20,18 @@ pub fn from_str(string: &str) -> Result<Duration, String> {
'm' | 'M' => (slice, 60),
'h' | 'H' => (slice, 60 * 60),
'd' | 'D' => (slice, 60 * 60 * 24),
val => {
if !val.is_alphabetic() {
(string, 1)
} else if string == "inf" || string == "infinity" {
val if !val.is_alphabetic() => (string, 1),
_ => {
if string == "inf" || string == "infinity" {
("inf", 1)
} else {
return Err(format!("invalid time interval '{}'", string));
}
}
};
let num = match numstr.parse::<f64>() {
Ok(m) => m,
Err(e) => return Err(format!("invalid time interval '{}': {}", string, e)),
};
let num = numstr
.parse::<f64>()
.map_err(|e| format!("invalid time interval '{}': {}", string, e))?;
const NANOS_PER_SEC: u32 = 1_000_000_000;
let whole_secs = num.trunc();

View file

@ -85,10 +85,9 @@ impl Range {
let mut ranges: Vec<Range> = vec![];
for item in list.split(',') {
match FromStr::from_str(item) {
Ok(range_item) => ranges.push(range_item),
Err(e) => return Err(format!("range '{}' was invalid: {}", item, e)),
}
let range_item = FromStr::from_str(item)
.map_err(|e| format!("range '{}' was invalid: {}", item, e))?;
ranges.push(range_item);
}
ranges.sort();