diff --git a/src/basename/basename.rs b/src/basename/basename.rs index 7949a64e0c3..b1f27e5dcea 100644 --- a/src/basename/basename.rs +++ b/src/basename/basename.rs @@ -89,19 +89,19 @@ fn strip_dir(fullname: &str) -> String { // Convert to path buffer and get last path component let pb = PathBuf::from(path); match pb.components().last() { - Some(c) => c.as_os_str().to_str().unwrap().to_string(), - None => "".to_string() + Some(c) => c.as_os_str().to_str().unwrap().to_owned(), + None => "".to_owned() } } fn strip_suffix(name: &str, suffix: &str) -> String { if name == suffix { - return name.to_string(); + return name.to_owned(); } if name.ends_with(suffix) { - return name[..name.len() - suffix.len()].to_string(); + return name[..name.len() - suffix.len()].to_owned(); } - name.to_string() + name.to_owned() } diff --git a/src/cat/cat.rs b/src/cat/cat.rs index 0d4ff71f0ad..c12eb403552 100644 --- a/src/cat/cat.rs +++ b/src/cat/cat.rs @@ -66,16 +66,16 @@ pub fn uumain(args: Vec) -> i32 { } else { NumberingMode::NumberNone }; - let show_nonprint = matches.opts_present(&["A".to_string(), "e".to_string(), - "t".to_string(), "v".to_string()]); - let show_ends = matches.opts_present(&["E".to_string(), "A".to_string(), - "e".to_string()]); - let show_tabs = matches.opts_present(&["A".to_string(), "T".to_string(), - "t".to_string()]); + let show_nonprint = matches.opts_present(&["A".to_owned(), "e".to_owned(), + "t".to_owned(), "v".to_owned()]); + let show_ends = matches.opts_present(&["E".to_owned(), "A".to_owned(), + "e".to_owned()]); + let show_tabs = matches.opts_present(&["A".to_owned(), "T".to_owned(), + "t".to_owned()]); let squeeze_blank = matches.opt_present("s"); let mut files = matches.free; if files.is_empty() { - files.push("-".to_string()); + files.push("-".to_owned()); } exec(files, number_mode, show_nonprint, show_ends, show_tabs, squeeze_blank); diff --git a/src/chmod/chmod.rs b/src/chmod/chmod.rs index 8f2d1763835..372799e386d 100644 --- a/src/chmod/chmod.rs +++ b/src/chmod/chmod.rs @@ -102,7 +102,7 @@ Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.", fn chmod(files: Vec, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option, cmode: Option<&String>) -> Result<(), i32> { let mut r = Ok(()); - for filename in files.iter() { + for filename in &files { let filename = &filename[..]; let file = Path::new(filename); if file.exists() { @@ -122,7 +122,7 @@ fn chmod(files: Vec, changes: bool, quiet: bool, verbose: bool, preserve // to chmod() and chmod_file(). r = chmod(walk_dir.filter_map(|x| match x { Ok(o) => match o.path().into_os_string().to_str() { - Some(s) => Some(s.to_string()), + Some(s) => Some(s.to_owned()), None => None, }, Err(e) => None, @@ -219,7 +219,7 @@ fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result unreachable!() }) } - Err(err) => Err(err.description().to_string()) + Err(err) => Err(err.description().to_owned()) } } } @@ -273,7 +273,7 @@ fn parse_op(mode: &str, default: Option) -> Result<(char, usize), String> None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch)) } }, - None => Err("unexpected end of mode".to_string()) + None => Err("unexpected end of mode".to_owned()) } } diff --git a/src/chroot/chroot.rs b/src/chroot/chroot.rs index 9057184e1b1..fa7f8bcffa6 100644 --- a/src/chroot/chroot.rs +++ b/src/chroot/chroot.rs @@ -65,7 +65,7 @@ pub fn uumain(args: Vec) -> i32 { if matches.opt_present("V") { version(); return 0 } if matches.opt_present("h") { help_menu(opts); return 0 } - if matches.free.len() == 0 { + if matches.free.is_empty() { println!("Missing operand: NEWROOT"); println!("Try `{} --help` for more information.", NAME); return 1 @@ -191,7 +191,7 @@ fn set_groups_from_str(groups: &str) { fn set_user(user: &str) { if !user.is_empty() { - let user_id = get_pw_from_args(&vec!(user.to_string())).unwrap().pw_uid; + let user_id = get_pw_from_args(&vec!(user.to_owned())).unwrap().pw_uid; let err = unsafe { setuid(user_id as libc::uid_t) }; if err != 0 { crash!(1, "cannot set user to {}: {}", user, Error::last_os_error()) diff --git a/src/cksum/cksum.rs b/src/cksum/cksum.rs index 5f49153a7ef..91c9f23ddb7 100644 --- a/src/cksum/cksum.rs +++ b/src/cksum/cksum.rs @@ -116,7 +116,7 @@ Print CRC and size for each file.", NAME, VERSION); } let mut exit_code = 0; - for fname in files.iter() { + for fname in &files { match cksum(fname.as_ref()) { Ok((crc, size)) => println!("{} {} {}", crc, size, fname), Err(err) => { diff --git a/src/comm/comm.rs b/src/comm/comm.rs index e4ff6501524..deeffa4817c 100644 --- a/src/comm/comm.rs +++ b/src/comm/comm.rs @@ -24,7 +24,7 @@ fn mkdelim(col: usize, opts: &getopts::Matches) -> String { let mut s = String::new(); let delim = match opts.opt_str("output-delimiter") { Some(d) => d.clone(), - None => "\t".to_string(), + None => "\t".to_owned(), }; if col > 1 && !opts.opt_present("1") { @@ -51,9 +51,9 @@ enum LineReader { impl LineReader { fn read_line(&mut self, buf: &mut String) -> io::Result { - match self { - &mut LineReader::Stdin(ref mut r) => r.read_line(buf), - &mut LineReader::FileIn(ref mut r) => r.read_line(buf), + match *self { + LineReader::Stdin(ref mut r) => r.read_line(buf), + LineReader::FileIn(ref mut r) => r.read_line(buf), } } } diff --git a/src/cp/cp.rs b/src/cp/cp.rs index 34c6b38d580..24068e3b222 100644 --- a/src/cp/cp.rs +++ b/src/cp/cp.rs @@ -66,7 +66,7 @@ fn version() { println!("{} {}", NAME, VERSION); } -fn help(usage: &String) { +fn help(usage: &str) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ @@ -82,7 +82,7 @@ fn copy(matches: getopts::Matches) { panic!() } else { // All but the last argument: - matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() + matches.free[..matches.free.len() - 1].iter().cloned().collect() }; let dest = if matches.free.len() < 2 { show_error!("Missing DEST argument. Try --help."); @@ -123,7 +123,7 @@ fn copy(matches: getopts::Matches) { panic!(); } - for src in sources.iter() { + for src in &sources { let source = Path::new(&src); if !source.is_file() { diff --git a/src/cut/buffer.rs b/src/cut/buffer.rs index da700513bc4..a194b6dd5e1 100644 --- a/src/cut/buffer.rs +++ b/src/cut/buffer.rs @@ -77,13 +77,10 @@ impl ByteReader { Err(e) => crash!(1, "read error: {}", e), }; - match filled_buf.iter().position(|byte| *byte == b'\n') { - Some(idx) => { - consume_val = idx + 1; - bytes_consumed += consume_val; - break; - } - _ => () + if let Some(idx) = filled_buf.iter().position(|byte| *byte == b'\n') { + consume_val = idx + 1; + bytes_consumed += consume_val; + break; } consume_val = filled_buf.len(); @@ -94,7 +91,7 @@ impl ByteReader { } self.consume(consume_val); - return bytes_consumed; + bytes_consumed } } diff --git a/src/cut/cut.rs b/src/cut/cut.rs index f4ac7531d66..516990b7cb6 100644 --- a/src/cut/cut.rs +++ b/src/cut/cut.rs @@ -53,7 +53,7 @@ fn list_to_ranges(list: &str, complement: bool) -> Result, String> { } } -fn cut_bytes(reader: R, ranges: &Vec, opts: &Options) -> i32 { +fn cut_bytes(reader: R, ranges: &[Range], opts: &Options) -> i32 { use buffer::Bytes::Select; use buffer::Bytes::Selected::*; @@ -125,7 +125,7 @@ fn cut_bytes(reader: R, ranges: &Vec, opts: &Options) -> i32 { 0 } -fn cut_characters(reader: R, ranges: &Vec, opts: &Options) -> i32 { +fn cut_characters(reader: R, ranges: &[Range], opts: &Options) -> i32 { let mut buf_in = BufReader::new(reader); let mut out = stdout(); let mut buffer = String::new(); @@ -135,7 +135,7 @@ fn cut_characters(reader: R, ranges: &Vec, opts: &Options) -> i3 match buf_in.read_line(&mut buffer) { Ok(n) if n == 0 => break, Err(e) => { - if buffer.len() == 0 { + if buffer.is_empty() { crash!(1, "read error: {}", e); } }, @@ -195,7 +195,7 @@ fn cut_characters(reader: R, ranges: &Vec, opts: &Options) -> i3 0 } -fn cut_fields_delimiter(reader: R, ranges: &Vec, delim: &String, only_delimited: bool, out_delim: &String) -> i32 { +fn cut_fields_delimiter(reader: R, ranges: &[Range], delim: &str, only_delimited: bool, out_delim: &str) -> i32 { let mut buf_in = BufReader::new(reader); let mut out = stdout(); let mut buffer = Vec::new(); @@ -205,7 +205,7 @@ fn cut_fields_delimiter(reader: R, ranges: &Vec, delim: &String, match buf_in.read_until(b'\n', &mut buffer) { Ok(n) if n == 0 => break, Err(e) => { - if buffer.len() == 0 { + if buffer.is_empty() { crash!(1, "read error: {}", e); } }, @@ -273,7 +273,7 @@ fn cut_fields_delimiter(reader: R, ranges: &Vec, delim: &String, 0 } -fn cut_fields(reader: R, ranges: &Vec, opts: &FieldOptions) -> i32 { +fn cut_fields(reader: R, ranges: &[Range], opts: &FieldOptions) -> i32 { match opts.out_delimeter { Some(ref o_delim) => { return cut_fields_delimiter(reader, ranges, &opts.delimiter, @@ -291,7 +291,7 @@ fn cut_fields(reader: R, ranges: &Vec, opts: &FieldOptions) -> i match buf_in.read_until(b'\n', &mut buffer) { Ok(n) if n == 0 => break, Err(e) => { - if buffer.len() == 0 { + if buffer.is_empty() { crash!(1, "read error: {}", e); } }, @@ -362,9 +362,9 @@ fn cut_files(mut filenames: Vec, mode: Mode) -> i32 { let mut stdin_read = false; let mut exit_code = 0; - if filenames.len() == 0 { filenames.push("-".to_string()); } + if filenames.is_empty() { filenames.push("-".to_owned()); } - for filename in filenames.iter() { + for filename in &filenames { if filename == "-" { if stdin_read { continue } @@ -469,8 +469,8 @@ pub fn uumain(args: Vec) -> i32 { { let out_delim = match matches.opt_str("output-delimiter") { Some(s) => { - if s.len() == 0 { - Some("\0".to_string()) + if s.is_empty() { + Some("\0".to_owned()) } else { Some(s) } @@ -483,10 +483,10 @@ pub fn uumain(args: Vec) -> i32 { match matches.opt_str("delimiter") { Some(delim) => { if delim.chars().count() > 1 { - Err("the delimiter must be a single character, or the empty string for null".to_string()) + Err("the delimiter must be a single character, or the empty string for null".to_owned()) } else { - let delim = if delim.len() == 0 { - "\0".to_string() + let delim = if delim.is_empty() { + "\0".to_owned() } else { delim }; @@ -501,7 +501,7 @@ pub fn uumain(args: Vec) -> i32 { } None => Ok(Mode::Fields(ranges, FieldOptions { - delimiter: "\t".to_string(), + delimiter: "\t".to_owned(), out_delimeter: out_delim, only_delimited: only_delimited })) @@ -510,9 +510,9 @@ pub fn uumain(args: Vec) -> i32 { ) } (ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => { - Err("only one type of list may be specified".to_string()) + Err("only one type of list may be specified".to_owned()) } - _ => Err("you must specify a list of bytes, characters, or fields".to_string()) + _ => Err("you must specify a list of bytes, characters, or fields".to_owned()) }; let mode_parse = match mode_parse { @@ -520,9 +520,9 @@ pub fn uumain(args: Vec) -> i32 { Ok(mode) => { match mode { Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("delimiter") => - Err("an input delimiter may be specified only when operating on fields".to_string()), + Err("an input delimiter may be specified only when operating on fields".to_owned()), Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("only-delimited") => - Err("suppressing non-delimited lines makes sense only when operating on fields".to_string()), + Err("suppressing non-delimited lines makes sense only when operating on fields".to_owned()), _ => Ok(mode), } } diff --git a/src/cut/ranges.rs b/src/cut/ranges.rs index a25d0da90f8..528e54959b4 100644 --- a/src/cut/ranges.rs +++ b/src/cut/ranges.rs @@ -97,7 +97,7 @@ impl Range { } } -pub fn complement(ranges: &Vec) -> Vec { +pub fn complement(ranges: &[Range]) -> Vec { use std::usize; let mut complements = Vec::with_capacity(ranges.len() + 1); diff --git a/src/dirname/dirname.rs b/src/dirname/dirname.rs index 60e2df5b87a..631aecca5de 100644 --- a/src/dirname/dirname.rs +++ b/src/dirname/dirname.rs @@ -46,13 +46,10 @@ directory).", NAME, VERSION); return 0; } - let separator = match matches.opt_present("zero") { - true => "\0", - false => "\n" - }; + let separator = if matches.opt_present("zero") {"\0"} else {"\n"}; if !matches.free.is_empty() { - for path in matches.free.iter() { + for path in &matches.free { let p = Path::new(path); match p.parent() { Some(d) => { diff --git a/src/du/du.rs b/src/du/du.rs index 3eec8b226cf..5f91c67f154 100644 --- a/src/du/du.rs +++ b/src/du/du.rs @@ -101,7 +101,7 @@ fn du(path: &PathBuf, mut my_stat: Stat, options: Arc, depth: usize) -> } } - for rx in futures.iter_mut() { + for rx in &mut futures { for stat in rx.recv().unwrap().into_iter().rev() { if !options.separate_dirs && stat.path.parent().unwrap().to_path_buf() == my_stat.path { my_stat.size += stat.size; @@ -236,24 +236,18 @@ ers of 1000).", let options = Options { all: matches.opt_present("all"), - program_name: NAME.to_string(), + program_name: NAME.to_owned(), max_depth: max_depth, total: matches.opt_present("total"), separate_dirs: matches.opt_present("S"), }; - let strs = if matches.free.is_empty() {vec!("./".to_string())} else {matches.free.clone()}; + let strs = if matches.free.is_empty() {vec!("./".to_owned())} else {matches.free.clone()}; let options_arc = Arc::new(options); - let MB = match matches.opt_present("si") { - true => 1000 * 1000, - false => 1024 * 1024, - }; - let KB = match matches.opt_present("si") { - true => 1000, - false => 1024, - }; + let MB = if matches.opt_present("si") {1000 * 1000} else {1024 * 1024}; + let KB = if matches.opt_present("si") {1000} else {1024}; let block_size = match matches.opt_str("block-size") { Some(s) => { @@ -331,10 +325,7 @@ Try '{} --help' for more information.", s, NAME); None => "%Y-%m-%d %H:%M" }; - let line_separator = match matches.opt_present("0") { - true => "\0", - false => "\n", - }; + let line_separator = if matches.opt_present("0") {"\0"} else {"\n"}; let mut grand_total = 0; for path_str in strs.into_iter() { @@ -343,11 +334,12 @@ Try '{} --help' for more information.", s, NAME); let (_, len) = iter.size_hint(); let len = len.unwrap(); for (index, stat) in iter.enumerate() { - let size = match matches.opt_present("apparent-size") { - true => stat.nlink * stat.size, + let size = if matches.opt_present("apparent-size") { + stat.nlink * stat.size + } else { // C's stat is such that each block is assume to be 512 bytes // See: http://linux.die.net/man/2/stat - false => stat.blocks * 512, + stat.blocks * 512 }; if matches.opt_present("time") { let tm = { diff --git a/src/echo/echo.rs b/src/echo/echo.rs index ee89cb61ad3..b1c6b1b2826 100644 --- a/src/echo/echo.rs +++ b/src/echo/echo.rs @@ -29,7 +29,7 @@ struct EchoOptions { } #[inline(always)] -fn to_char(bytes: &Vec, base: u32) -> char { +fn to_char(bytes: &[u8], base: u32) -> char { usize::from_str_radix(from_utf8(bytes.as_ref()).unwrap(), base).unwrap() as u8 as char } @@ -70,7 +70,7 @@ fn convert_str(string: &[u8], index: usize, base: u32) -> (char, usize) { } } - if bytes.len() == 0 { + if bytes.is_empty() { (' ', 0) } else { (to_char(&bytes, base), bytes.len()) @@ -177,65 +177,60 @@ pub fn uumain(args: Vec) -> i32 { if options.escape { let mut prev_was_slash = false; let mut iter = string.chars().enumerate(); - loop { - match iter.next() { - Some((index, c)) => { - if !prev_was_slash { - if c != '\\' { - print!("{}", c); + while let Some((index, c)) = iter.next() { + if !prev_was_slash { + if c != '\\' { + print!("{}", c); + } else { + prev_was_slash = true; + } + } else { + prev_was_slash = false; + match c { + '\\' => print!("\\"), + 'a' => print!("\x07"), + 'b' => print!("\x08"), + 'c' => break, + 'e' => print!("\x1B"), + 'f' => print!("\x0C"), + 'n' => print!("\n"), + 'r' => print!("\r"), + 't' => print!("\t"), + 'v' => print!("\x0B"), + 'x' => { + let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 16); + if num_char_used == 0 { + print!("\\x"); } else { - prev_was_slash = true; + print!("{}", c); + for _ in 0 .. num_char_used { + iter.next(); // consume used characters + } } - } else { - prev_was_slash = false; - match c { - '\\' => print!("\\"), - 'a' => print!("\x07"), - 'b' => print!("\x08"), - 'c' => break, - 'e' => print!("\x1B"), - 'f' => print!("\x0C"), - 'n' => print!("\n"), - 'r' => print!("\r"), - 't' => print!("\t"), - 'v' => print!("\x0B"), - 'x' => { - let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 16); - if num_char_used == 0 { - print!("\\x"); - } else { - print!("{}", c); - for _ in 0 .. num_char_used { - iter.next(); // consume used characters - } - } - }, - '0' => { - let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 8); - if num_char_used == 0 { - print!("\0"); - } else { - print!("{}", c); - for _ in 0 .. num_char_used { - iter.next(); // consume used characters - } - } + }, + '0' => { + let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 8); + if num_char_used == 0 { + print!("\0"); + } else { + print!("{}", c); + for _ in 0 .. num_char_used { + iter.next(); // consume used characters } - _ => { - let (esc_c, num_char_used) = convert_str(string.as_bytes(), index, 8); - if num_char_used == 0 { - print!("\\{}", c); - } else { - print!("{}", esc_c); - for _ in 1 .. num_char_used { - iter.next(); // consume used characters - } - } + } + } + _ => { + let (esc_c, num_char_used) = convert_str(string.as_bytes(), index, 8); + if num_char_used == 0 { + print!("\\{}", c); + } else { + print!("{}", esc_c); + for _ in 1 .. num_char_used { + iter.next(); // consume used characters } } } } - None => break } } } else { diff --git a/src/env/env.rs b/src/env/env.rs index 959a6c35c02..dd4305e8f7c 100644 --- a/src/env/env.rs +++ b/src/env/env.rs @@ -84,11 +84,11 @@ pub fn uumain(args: Vec) -> i32 { match (name, value) { (Some(n), Some(v)) => { - opts.sets.push((n.to_string(), v.to_string())); + opts.sets.push((n.to_owned(), v.to_owned())); } _ => { // read the program now - opts.program.push(opt.to_string()); + opts.program.push(opt.to_owned()); break; } } @@ -104,7 +104,7 @@ pub fn uumain(args: Vec) -> i32 { match var { None => println!("{}: this option requires an argument: {}", NAME, opt), - Some(s) => opts.unsets.push(s.to_string()) + Some(s) => opts.unsets.push(s.to_owned()) } } @@ -137,7 +137,7 @@ pub fn uumain(args: Vec) -> i32 { match var { None => println!("{}: this option requires an argument: {}", NAME, opt), - Some(s) => opts.unsets.push(s.to_string()) + Some(s) => opts.unsets.push(s.to_owned()) } } _ => { @@ -156,12 +156,12 @@ pub fn uumain(args: Vec) -> i32 { match (name, value) { (Some(n), Some(v)) => { // yes - opts.sets.push((n.to_string(), v.to_string())); + opts.sets.push((n.to_owned(), v.to_owned())); wait_cmd = true; } // no, its a program-like opt _ => { - opts.program.push(opt.to_string()); + opts.program.push(opt.clone()); break; } } @@ -172,7 +172,7 @@ pub fn uumain(args: Vec) -> i32 { // read program arguments for opt in iter { - opts.program.push(opt.to_string()); + opts.program.push(opt.clone()); } if opts.ignore_env { @@ -181,11 +181,11 @@ pub fn uumain(args: Vec) -> i32 { } } - for name in opts.unsets.iter() { + for name in &opts.unsets { env::remove_var(name); } - for &(ref name, ref val) in opts.sets.iter() { + for &(ref name, ref val) in &opts.sets { env::set_var(name, val); } diff --git a/src/expand/expand.rs b/src/expand/expand.rs index d24db30aad0..3a45a6586d9 100644 --- a/src/expand/expand.rs +++ b/src/expand/expand.rs @@ -46,9 +46,8 @@ fn tabstops_parse(s: String) -> Vec { crash!(1, "{}\n", "tab size cannot be 0"); } - match nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { - (false, _) => crash!(1, "{}\n", "tab sizes must be ascending"), - _ => {} + if let (false, _) = nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { + crash!(1, "{}\n", "tab sizes must be ascending"); } nums @@ -83,7 +82,7 @@ impl Options { let files = if matches.free.is_empty() { - vec!("-".to_string()) + vec!("-".to_owned()) } else { matches.free }; @@ -168,7 +167,7 @@ fn expand(options: Options) { while match fh.read_until('\n' as u8, &mut buf) { Ok(s) => s > 0, - Err(_) => buf.len() > 0, + Err(_) => buf.is_empty(), } { let mut col = 0; let mut byte = 0; diff --git a/src/expr/expr.rs b/src/expr/expr.rs index 5242fad379a..c78d1263ebc 100644 --- a/src/expr/expr.rs +++ b/src/expr/expr.rs @@ -41,9 +41,7 @@ pub fn uumain(args: Vec) -> i32 { fn process_expr( token_strings: &Vec ) -> Result< String, String > { let maybe_tokens = tokens::strings_to_tokens( &token_strings ); let maybe_ast = syntax_tree::tokens_to_ast( maybe_tokens ); - let maybe_result = evaluate_ast( maybe_ast ); - - maybe_result + evaluate_ast( maybe_ast ) } fn print_expr_ok( expr_result: &String ) -> i32 { diff --git a/src/expr/syntax_tree.rs b/src/expr/syntax_tree.rs index 7921e2d9ab3..ef77c0d62d7 100644 --- a/src/expr/syntax_tree.rs +++ b/src/expr/syntax_tree.rs @@ -30,9 +30,9 @@ impl ASTNode { for _ in 0..depth { print!("\t", ); } - match self { - &ASTNode::Leaf{ ref token_idx, ref value } => println!("Leaf( {} ) at #{} ( evaluate -> {:?} )", value, token_idx, self.evaluate()), - &ASTNode::Node{ ref token_idx, ref op_type, ref operands } => { + match *self { + ASTNode::Leaf{ ref token_idx, ref value } => println!("Leaf( {} ) at #{} ( evaluate -> {:?} )", value, token_idx, self.evaluate()), + ASTNode::Node{ ref token_idx, ref op_type, ref operands } => { println!("Node( {} ) at #{} (evaluate -> {:?})", op_type, token_idx, self.evaluate()); for operand in operands { operand.debug_dump_impl( depth + 1 ); @@ -52,9 +52,9 @@ impl ASTNode { Box::new( ASTNode::Leaf{ token_idx: token_idx, value: value.clone() } ) } pub fn evaluate( &self ) -> Result { - match self { - &ASTNode::Leaf{ ref value, .. } => Ok( value.clone() ), - &ASTNode::Node{ ref op_type, .. } => + match *self { + ASTNode::Leaf{ ref value, .. } => Ok( value.clone() ), + ASTNode::Node{ ref op_type, .. } => match self.operand_values() { Err( reason ) => Err( reason ), Ok( operand_values ) => @@ -64,12 +64,12 @@ impl ASTNode { "*" => infix_operator_two_ints( |a: i64, b: i64| Ok( a * b ), &operand_values ), "/" => infix_operator_two_ints( |a: i64, b: i64| - if b == 0 { Err("division by zero".to_string()) } + if b == 0 { Err("division by zero".to_owned()) } else { Ok( a / b ) }, &operand_values ), "%" => infix_operator_two_ints( |a: i64, b: i64| - if b == 0 { Err("division by zero".to_string()) } + if b == 0 { Err("division by zero".to_owned()) } else { Ok( a % b ) }, &operand_values ), @@ -149,7 +149,7 @@ pub fn tokens_to_ast( maybe_tokens: Result< Vec<(usize, Token)>, String > ) -> R maybe_dump_rpn( &out_stack ); let result = ast_from_rpn( &mut out_stack ); if !out_stack.is_empty() { - Err( "syntax error (fist RPN token does not represent expression AST's root)".to_string() ) + Err( "syntax error (fist RPN token does not represent expression AST's root)".to_owned() ) } else { maybe_dump_ast( &result ); @@ -163,9 +163,9 @@ fn maybe_dump_ast( result: &Result< Box, String > ) { if let Ok( debug_var ) = env::var( "EXPR_DEBUG_AST" ) { if debug_var == "1" { println!("EXPR_DEBUG_AST"); - match result { - &Ok( ref ast ) => ast.debug_dump(), - &Err( ref reason ) => println!("\terr: {:?}", reason), + match *result { + Ok( ref ast ) => ast.debug_dump(), + Err( ref reason ) => println!("\terr: {:?}", reason), } } } @@ -185,7 +185,7 @@ fn maybe_dump_rpn( rpn: &TokenStack ) { fn ast_from_rpn( rpn: &mut TokenStack ) -> Result, String> { match rpn.pop() { - None => Err( "syntax error (premature end of expression)".to_string() ), + None => Err( "syntax error (premature end of expression)".to_owned() ), Some( (token_idx, Token::Value{ value }) ) => Ok( ASTNode::new_leaf( token_idx, &value ) ), @@ -225,18 +225,18 @@ fn move_rest_of_ops_to_out( out_stack: &mut TokenStack, op_stack: &mut TokenStac fn push_token_to_either_stack( token_idx: usize, token: &Token, out_stack: &mut TokenStack, op_stack: &mut TokenStack ) -> Result<(), String> { let result = - match token { - &Token::Value{ .. } => Ok( out_stack.push( (token_idx, token.clone()) ) ), + match *token { + Token::Value{ .. } => Ok( out_stack.push( (token_idx, token.clone()) ) ), - &Token::InfixOp{ .. } => + Token::InfixOp{ .. } => if op_stack.is_empty() { Ok( op_stack.push( (token_idx, token.clone()) ) ) } else { push_op_to_stack( token_idx, token, out_stack, op_stack ) }, - &Token::PrefixOp{ .. } => Ok( op_stack.push( (token_idx, token.clone()) ) ), + Token::PrefixOp{ .. } => Ok( op_stack.push( (token_idx, token.clone()) ) ), - &Token::ParOpen => Ok( op_stack.push( (token_idx, token.clone()) ) ), + Token::ParOpen => Ok( op_stack.push( (token_idx, token.clone()) ) ), - &Token::ParClose => move_till_match_paren( out_stack, op_stack ) + Token::ParClose => move_till_match_paren( out_stack, op_stack ) }; maybe_dump_shunting_yard_step( token_idx, token, out_stack, op_stack, &result ); result diff --git a/src/expr/tokens.rs b/src/expr/tokens.rs index f1c0a65bff9..48c341e1c78 100644 --- a/src/expr/tokens.rs +++ b/src/expr/tokens.rs @@ -52,14 +52,14 @@ impl Token { } fn is_infix_plus( &self ) -> bool { - match self { - &Token::InfixOp{ ref value, .. } => value == "+", + match *self { + Token::InfixOp{ ref value, .. } => value == "+", _ => false } } fn is_a_number( &self ) -> bool { - match self { - &Token::Value{ ref value, .. } => + match *self { + Token::Value{ ref value, .. } => match value.parse::() { Ok( _ ) => true, Err( _ ) => false @@ -68,14 +68,14 @@ impl Token { } } fn is_a_close_paren( &self ) -> bool { - match self { - &Token::ParClose => true, + match *self { + Token::ParClose => true, _ => false, } } } -pub fn strings_to_tokens( strings: &Vec ) -> Result< Vec<(usize, Token)>, String > { +pub fn strings_to_tokens( strings: &[String] ) -> Result< Vec<(usize, Token)>, String > { let mut tokens_acc = Vec::with_capacity( strings.len() ); let mut tok_idx = 1; @@ -122,7 +122,7 @@ pub fn strings_to_tokens( strings: &Vec ) -> Result< Vec<(usize, Token)> Ok( tokens_acc ) } -fn maybe_dump_tokens_acc( tokens_acc: &Vec<(usize, Token)> ) { +fn maybe_dump_tokens_acc( tokens_acc: &[(usize, Token)] ) { use std::env; if let Ok(debug_var) = env::var( "EXPR_DEBUG_TOKENS" ) { @@ -147,8 +147,9 @@ fn push_token_if_not_escaped( acc: &mut Vec<(usize, Token)>, tok_idx: usize, tok let pre_prev = &acc[acc.len() - 2]; ! ( pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren() ) } - else if prev_is_plus { true } - else { false }; + else { + prev_is_plus + }; if should_use_as_escaped { acc.pop(); diff --git a/src/factor/factor.rs b/src/factor/factor.rs index c5efcedf305..91539cc6d0e 100644 --- a/src/factor/factor.rs +++ b/src/factor/factor.rs @@ -145,7 +145,7 @@ fn print_factors(num: u64) { table_division(num, &mut factors); factors.sort(); - for fac in factors.iter() { + for fac in &factors { print!(" {}", fac); } println!(""); @@ -193,7 +193,7 @@ read from standard input.", NAME, VERSION); } } } else { - for num_str in matches.free.iter() { + for num_str in &matches.free { print_factors_str(num_str); } } diff --git a/src/factor/numeric.rs b/src/factor/numeric.rs index 16a0652a14d..4915a189f86 100644 --- a/src/factor/numeric.rs +++ b/src/factor/numeric.rs @@ -17,13 +17,11 @@ pub fn big_add(a: u64, b: u64, m: u64) -> u64 { let msb_mod_m = msb_mod_m % m; let Wrapping(res) = Wrapping(a) + Wrapping(b); - let res = if b <= MAX_U64 - a { + if b <= MAX_U64 - a { res } else { (res + msb_mod_m) % m - }; - - res + } } // computes (a + b) % m using the russian peasant algorithm diff --git a/src/fmt/fmt.rs b/src/fmt/fmt.rs index 550f3dcda80..0eec3faba1b 100644 --- a/src/fmt/fmt.rs +++ b/src/fmt/fmt.rs @@ -189,7 +189,7 @@ pub fn uumain(args: Vec) -> i32 { let mut files = matches.free; if files.is_empty() { - files.push("-".to_string()); + files.push("-".to_owned()); } let mut ostream = BufWriter::new(stdout()); diff --git a/src/fmt/linebreak.rs b/src/fmt/linebreak.rs index a043444fc44..f43fb802213 100644 --- a/src/fmt/linebreak.rs +++ b/src/fmt/linebreak.rs @@ -24,7 +24,6 @@ struct BreakArgs<'a> { } impl<'a> BreakArgs<'a> { - #[inline(always)] fn compute_width<'b>(&self, winfo: &WordInfo<'b>, posn: usize, fresh: bool) -> usize { if fresh { 0 @@ -99,7 +98,6 @@ fn break_simple<'a, T: Iterator>>(iter: T, args: &mut Brea silent_unwrap!(args.ostream.write_all("\n".as_bytes())); } -#[inline(always)] fn accum_words_simple<'a>(args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>) -> (usize, bool) { // compute the length of this word, considering how tabs will expand at this position on the line let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); @@ -310,8 +308,7 @@ fn find_kp_breakpoints<'a, T: Iterator>>(iter: T, args: &B build_best_path(&linebreaks, active_breaks) } -#[inline(always)] -fn build_best_path<'a>(paths: &Vec>, active: &Vec) -> Vec<(&'a WordInfo<'a>, bool)> { +fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> { let mut breakwords = vec!(); // of the active paths, we select the one with the fewest demerits let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { @@ -322,7 +319,7 @@ fn build_best_path<'a>(paths: &Vec>, active: &Vec) -> Vec<( // now, chase the pointers back through the break list, recording // the words at which we should break loop { - let ref next_best = paths[best_idx]; + let next_best = &paths[best_idx]; match next_best.linebreak { None => return breakwords, Some(prev) => { @@ -343,7 +340,6 @@ const DR_MULT: f32 = 600.0; // DL_MULT is penalty multiplier for short words at end of line const DL_MULT: f32 = 300.0; -#[inline(always)] fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) { // how much stretch are we using? let ratio = @@ -377,7 +373,6 @@ fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32 (demerits, ratio) } -#[inline(always)] fn restart_active_breaks<'a>(args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize) -> LineBreak<'a> { let (break_before, line_length) = if active.fresh { @@ -409,7 +404,6 @@ fn restart_active_breaks<'a>(args: &BreakArgs<'a>, active: &LineBreak<'a>, act_i } // Number of spaces to add before a word, based on mode, newline, sentence start. -#[inline(always)] fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { if uniform || newline { if start || (newline && punct) { @@ -424,8 +418,7 @@ fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize // If we're on a fresh line, slen=0 and we slice off leading whitespace. // Otherwise, compute slen and leave whitespace alone. -#[inline(always)] -fn slice_if_fresh<'a>(fresh: bool, word: &'a str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool) -> (usize, &'a str) { +fn slice_if_fresh(fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool) -> (usize, &str) { if fresh { (0, &word[start..]) } else { @@ -434,14 +427,12 @@ fn slice_if_fresh<'a>(fresh: bool, word: &'a str, start: usize, uniform: bool, n } // Write a newline and add the indent. -#[inline(always)] fn write_newline(indent: &str, ostream: &mut BufWriter) { silent_unwrap!(ostream.write_all("\n".as_bytes())); silent_unwrap!(ostream.write_all(indent.as_bytes())); } // Write the word, along with slen spaces. -#[inline(always)] fn write_with_spaces(word: &str, slen: usize, ostream: &mut BufWriter) { if slen == 2 { silent_unwrap!(ostream.write_all(" ".as_bytes())); diff --git a/src/fmt/parasplit.rs b/src/fmt/parasplit.rs index f903b08467e..ca747376b36 100644 --- a/src/fmt/parasplit.rs +++ b/src/fmt/parasplit.rs @@ -15,7 +15,6 @@ use unicode_width::UnicodeWidthChar; use FileOrStdReader; use FmtOptions; -#[inline(always)] fn char_width(c: char) -> usize { if (c as usize) < 0xA0 { // if it is ASCII, call it exactly 1 wide (including control chars) @@ -103,7 +102,7 @@ impl<'a> FileLines<'a> { // we do it this way rather than byte indexing to support unicode whitespace chars let mut i = 0; while (i < line.len()) && line.char_at(i).is_whitespace() { - i = match line.char_range_at(i) { CharRange { ch: _ , next: nxi } => nxi }; + i = match line.char_range_at(i) { CharRange { next: nxi, .. } => nxi }; if line[i..].starts_with(pfx) { return (true, i); } @@ -157,7 +156,7 @@ impl<'a> Iterator for FileLines<'a> { // Err(true) indicates that this was a linebreak, // which is important to know when detecting mail headers if n.chars().all(|c| c.is_whitespace()) { - return Some(Line::NoFormatLine("\n".to_string(), true)); + return Some(Line::NoFormatLine("\n".to_owned(), true)); } // if this line does not match the prefix, @@ -246,10 +245,10 @@ impl<'a> ParagraphStream<'a> { // header field must be nonzero length if colon_posn == 0 { return false; } - return l_slice[..colon_posn].chars().all(|x| match x as usize { + l_slice[..colon_posn].chars().all(|x| match x as usize { y if y < 33 || y > 126 => false, _ => true - }); + }) } } } @@ -263,9 +262,9 @@ impl<'a> Iterator for ParagraphStream<'a> { let noformat = match self.lines.peek() { None => return None, - Some(l) => match l { - &Line::FormatLine(_) => false, - &Line::NoFormatLine(_, _) => true + Some(l) => match *l { + Line::FormatLine(_) => false, + Line::NoFormatLine(_, _) => true } }; @@ -296,14 +295,14 @@ impl<'a> Iterator for ParagraphStream<'a> { match self.lines.peek() { None => break, Some(l) => { - match l { - &Line::FormatLine(ref x) => x, - &Line::NoFormatLine(..) => break + match *l { + Line::FormatLine(ref x) => x, + Line::NoFormatLine(..) => break } } }; - if p_lines.len() == 0 { + if p_lines.is_empty() { // first time through the loop, get things set up // detect mail header if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) { @@ -410,7 +409,7 @@ impl<'a> ParaWords<'a> { pw } - fn create_words<'r>(&'r mut self) { + fn create_words(& mut self) { if self.para.mail_header { // no extra spacing for mail headers; always exactly 1 space // safe to trim_left on every line of a mail header, since the @@ -445,7 +444,7 @@ impl<'a> ParaWords<'a> { } } - pub fn words(&'a self) -> Iter<'a, WordInfo<'a>> { return self.words.iter() } + pub fn words(&'a self) -> Iter<'a, WordInfo<'a>> { self.words.iter() } } struct WordSplit<'a> { @@ -546,7 +545,7 @@ impl<'a> Iterator for WordSplit<'a> { // now record whether this word ends in punctuation self.prev_punct = match self.string.char_range_at_reverse(self.position) { - CharRange { ch, next: _ } => WordSplit::is_punctuation(ch) + CharRange { ch, .. } => WordSplit::is_punctuation(ch) }; let (word, word_start_relative, before_tab, after_tab) = diff --git a/src/fold/fold.rs b/src/fold/fold.rs index 6650d2c9fd9..a5d1da874ab 100644 --- a/src/fold/fold.rs +++ b/src/fold/fold.rs @@ -53,10 +53,7 @@ pub fn uumain(args: Vec) -> i32 { if matches.opt_present("w") { matches.opt_str("w") } else { - match obs_width { - Some(v) => Some(v.to_string()), - None => None, - } + obs_width }; let width = match poss_width { Some(inp_width) => match inp_width.parse::() { @@ -66,7 +63,7 @@ pub fn uumain(args: Vec) -> i32 { None => 80 }; let files = if matches.free.is_empty() { - vec!("-".to_string()) + vec!("-".to_owned()) } else { matches.free }; @@ -82,7 +79,7 @@ fn handle_obsolete(args: &[String]) -> (Vec, Option) { if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let mut v = args.to_vec(); v.remove(i); - return (v, Some(slice[1..].to_string())); + return (v, Some(slice[1..].to_owned())); } } (args.to_vec(), None) @@ -90,7 +87,7 @@ fn handle_obsolete(args: &[String]) -> (Vec, Option) { #[inline] fn fold(filenames: Vec, bytes: bool, spaces: bool, width: usize) { - for filename in filenames.iter() { + for filename in &filenames { let filename: &str = &filename; let mut stdin_buf; let mut file_buf; @@ -168,7 +165,7 @@ fn fold_file(mut file: BufReader, bytes: bool, spaces: bool, width: (slice, "", 0) }; println!("{}", out); - (val.to_string(), ncount) + (val.to_owned(), ncount) }; output = val; count = ncount; diff --git a/src/hashsum/hashsum.rs b/src/hashsum/hashsum.rs index 22faa7cf933..8592dcc28c5 100644 --- a/src/hashsum/hashsum.rs +++ b/src/hashsum/hashsum.rs @@ -124,7 +124,7 @@ pub fn uumain(args: Vec) -> i32 { let strict = matches.opt_present("strict"); let warn = matches.opt_present("warn") && !status; let files = if matches.free.is_empty() { - vec!("-".to_string()) + vec!("-".to_owned()) } else { matches.free }; @@ -158,7 +158,7 @@ Compute and check message digests.", NAME, VERSION, spec); pipe_print!("{}", opts.usage(&msg)); } -fn hashsum<'a>(algoname: &str, mut digest: Box, files: Vec, binary: bool, check: bool, tag: bool, status: bool, quiet: bool, strict: bool, warn: bool) -> Result<(), i32> { +fn hashsum(algoname: &str, mut digest: Box, files: Vec, binary: bool, check: bool, tag: bool, status: bool, quiet: bool, strict: bool, warn: bool) -> Result<(), i32> { let mut bad_format = 0; let mut failed = 0; let binary_marker = if binary { @@ -166,7 +166,7 @@ fn hashsum<'a>(algoname: &str, mut digest: Box, files: Vec, b } else { " " }; - for filename in files.iter() { + for filename in &files { let filename: &str = filename; let stdin_buf; let file_buf; diff --git a/src/head/head.rs b/src/head/head.rs index 3b79e92851c..eca492c7f45 100644 --- a/src/head/head.rs +++ b/src/head/head.rs @@ -130,7 +130,7 @@ pub fn uumain(args: Vec) -> i32 { } else { let mut firstime = true; - for file in files.iter() { + for file in &files { if settings.verbose { if !firstime { pipe_println!(""); } pipe_println!("==> {} <==", file); diff --git a/src/hostname/hostname.rs b/src/hostname/hostname.rs index 1b4969d357d..bd816413ec5 100644 --- a/src/hostname/hostname.rs +++ b/src/hostname/hostname.rs @@ -82,7 +82,7 @@ pub fn uumain(args: Vec) -> i32 { if !hashset.contains(&addr) { let mut ip = format!("{}", addr); if ip.ends_with(":1") { - ip = ip[..ip.len()-2].to_string(); + ip = ip[..ip.len()-2].to_owned(); } output.push_str(&ip); output.push_str(" "); @@ -153,7 +153,7 @@ fn xgethostname() -> String { let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); - str::from_utf8(&name[..last_char]).unwrap().to_string() + str::from_utf8(&name[..last_char]).unwrap().to_owned() } #[cfg(any(target_os = "macos", target_os = "freebsd"))] diff --git a/src/id/id.rs b/src/id/id.rs index 1c1844ee021..71140122b8f 100644 --- a/src/id/id.rs +++ b/src/id/id.rs @@ -196,7 +196,7 @@ fn pretty(possible_pw: Option) { let pw = unsafe { getpwuid(rid) }; let is_same_user = unsafe { - String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() == login + String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()) == login }; if pw.is_null() || is_same_user { @@ -374,11 +374,11 @@ fn id_print(possible_pw: Option, p_euid: bool, p_egid: bool) { } } - if groups.len() > 0 { + if !groups.is_empty() { print!(" groups="); let mut first = true; - for &gr in groups.iter() { + for &gr in &groups { if !first { print!(",") } print!("{}", gr); let group = unsafe { getgrgid(gr) }; diff --git a/src/kill/kill.rs b/src/kill/kill.rs index cc099402b6e..8cab4e2e514 100644 --- a/src/kill/kill.rs +++ b/src/kill/kill.rs @@ -66,7 +66,7 @@ pub fn uumain(args: Vec) -> i32 { }; match mode { - Mode::Kill => return kill(&matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())), matches.free), + Mode::Kill => return kill(&matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_owned())), matches.free), Mode::Table => table(), Mode::List => list(matches.opt_str("list")), Mode::Help => help(&opts), @@ -91,7 +91,7 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { Ok(num) => { if uucore::signals::is_signal(num) { args.remove(i); - return (args, Some(val.to_string())); + return (args, Some(val.to_owned())); } } Err(_)=> break /* getopts will error out for us */ @@ -105,7 +105,7 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { fn table() { let mut name_width = 0; /* Compute the maximum width of a signal name. */ - for s in ALL_SIGNALS.iter() { + for s in &ALL_SIGNALS { if s.name.len() > name_width { name_width = s.name.len() } @@ -122,7 +122,7 @@ fn table() { } fn print_signal(signal_name_or_value: &str) { - for signal in ALL_SIGNALS.iter() { + for signal in &ALL_SIGNALS { if signal.name == signal_name_or_value || (format!("SIG{}", signal.name)) == signal_name_or_value { println!("{}", signal.value); exit!(EXIT_OK as i32) @@ -172,7 +172,7 @@ fn kill(signalname: &str, pids: std::vec::Vec) -> i32 { Some(x) => x, None => crash!(EXIT_ERR, "unknown signal name {}", signalname) }; - for pid in pids.iter() { + for pid in &pids { match pid.parse::() { Ok(x) => { if unsafe { libc::kill(x as pid_t, signal_value as c_int) } != 0 { diff --git a/src/ln/ln.rs b/src/ln/ln.rs index 825a69cee5f..51192ddcac5 100644 --- a/src/ln/ln.rs +++ b/src/ln/ln.rs @@ -112,7 +112,7 @@ pub fn uumain(args: Vec) -> i32 { } } } else { - "~".to_string() + "~".to_owned() }; if matches.opt_present("T") && matches.opt_present("t") { @@ -216,13 +216,10 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting } }; - match link(srcpath, &targetpath, settings) { - Err(e) => { - show_error!("cannot link '{}' to '{}': {}", - targetpath.display(), srcpath.display(), e); - all_successful = false; - }, - _ => {} + if let Err(e) = link(srcpath, &targetpath, settings) { + show_error!("cannot link '{}' to '{}': {}", + targetpath.display(), srcpath.display(), e); + all_successful = false; } } if all_successful { 0 } else { 1 } @@ -231,10 +228,8 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting fn link(src: &PathBuf, dst: &PathBuf, settings: &Settings) -> Result<()> { let mut backup_path = None; - if dst.is_dir() { - if settings.no_target_dir { - try!(fs::remove_dir(dst)); - } + if dst.is_dir() && settings.no_target_dir { + try!(fs::remove_dir(dst)); } if is_symlink(dst) || dst.exists() { @@ -290,8 +285,8 @@ fn read_yes() -> bool { } } -fn simple_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { - let mut p = path.as_os_str().to_str().unwrap().to_string(); +fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { + let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } @@ -307,8 +302,8 @@ fn numbered_backup_path(path: &PathBuf) -> PathBuf { } } -fn existing_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { - let test_path = simple_backup_path(path, &".~1~".to_string()); +fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { + let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); } diff --git a/src/mkdir/mkdir.rs b/src/mkdir/mkdir.rs index 96b07ed15a5..dc05e6ddac2 100644 --- a/src/mkdir/mkdir.rs +++ b/src/mkdir/mkdir.rs @@ -55,17 +55,17 @@ pub fn uumain(args: Vec) -> i32 { // Translate a ~str in octal form to u16, default to 755 // Not tested on Windows - let mode_match = matches.opts_str(&["mode".to_string()]); + let mode_match = matches.opts_str(&["mode".to_owned()]); let mode: u16 = if mode_match.is_some() { let m = mode_match.unwrap(); let res: Option = u16::from_str_radix(&m, 8).ok(); if res.is_some() { - unsafe { std::mem::transmute(res.unwrap()) } + res.unwrap() } else { crash!(1, "no mode given"); } } else { - unsafe { std::mem::transmute(0o755 as u16) } + 0o755 as u16 }; let dirs = matches.free; @@ -88,7 +88,7 @@ fn print_help(opts: &getopts::Options) { fn exec(dirs: Vec, recursive: bool, mode: u16, verbose: bool) -> i32 { let mut status = 0; let empty = Path::new(""); - for dir in dirs.iter() { + for dir in &dirs { let path = Path::new(dir); if recursive { let mut pathbuf = PathBuf::new(); diff --git a/src/mkfifo/mkfifo.rs b/src/mkfifo/mkfifo.rs index 593582670c6..b0b475d4bab 100644 --- a/src/mkfifo/mkfifo.rs +++ b/src/mkfifo/mkfifo.rs @@ -66,7 +66,7 @@ Create a FIFO with the given name.", NAME, VERSION); }; let mut exit_status = 0; - for f in matches.free.iter() { + for f in &matches.free { let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) }; if err == -1 { show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap()); diff --git a/src/mktemp/mktemp.rs b/src/mktemp/mktemp.rs index 6e2cdfea459..ff7e0d22b96 100644 --- a/src/mktemp/mktemp.rs +++ b/src/mktemp/mktemp.rs @@ -88,16 +88,16 @@ pub fn uumain(args: Vec) -> i32 { } else { crash!(1, "Template should end with 'X' when you specify suffix option.") }, - None => (p, r, s.to_string()) + None => (p, r, s.to_owned()) }, - None => ("",0, "".to_string()) + None => ("",0, "".to_owned()) }; if rand < 3 { crash!(1, "Too few 'X's in template") } - if suffix.chars().any(|c| is_separator(c)) { + if suffix.chars().any(is_separator) { crash!(1, "suffix cannot contain any path separators"); } @@ -168,7 +168,7 @@ pub fn dry_exec(mut tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str) -> } tmpdir.push(String::from(buf)); println!("{}", tmpdir.display()); - return 0; + 0 } @@ -203,5 +203,5 @@ fn exec(tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str, make_dir: bool // I call a dengeros function `forget`. forget(tmpfile); - return 0; + 0 } diff --git a/src/mv/mv.rs b/src/mv/mv.rs index 6170746ea8b..54460ae25dc 100644 --- a/src/mv/mv.rs +++ b/src/mv/mv.rs @@ -128,7 +128,7 @@ pub fn uumain(args: Vec) -> i32 { } } } else { - "~".to_string() + "~".to_owned() }; if matches.opt_present("T") && matches.opt_present("t") { @@ -192,8 +192,8 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 { return 1; }, 2 => { - let ref source = files[0]; - let ref target = files[1]; + let source = &files[0]; + let target = &files[1]; if !source.exists() { show_error!("cannot stat ‘{}’: No such file or directory", source.display()); return 1; @@ -219,12 +219,9 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 { return move_files_into_dir(&[source.clone()], target, &b); } - match rename(source, target, &b) { - Err(e) => { - show_error!("{}", e); - return 1; - }, - _ => {} + if let Err(e) = rename(source, target, &b) { + show_error!("{}", e); + return 1; } } _ => { @@ -259,13 +256,10 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) - } }; - match rename(sourcepath, &targetpath, b) { - Err(e) => { - show_error!("mv: cannot move ‘{}’ to ‘{}’: {}", - sourcepath.display(), targetpath.display(), e); - all_successful = false; - }, - _ => {} + if let Err(e) = rename(sourcepath, &targetpath, b) { + show_error!("mv: cannot move ‘{}’ to ‘{}’: {}", + sourcepath.display(), targetpath.display(), e); + all_successful = false; } }; if all_successful { 0 } else { 1 } @@ -326,10 +320,10 @@ fn read_yes() -> bool { } } -fn simple_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { - let mut p = path.as_os_str().to_str().unwrap().to_string(); +fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { + let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); - return PathBuf::from(p); + PathBuf::from(p) } fn numbered_backup_path(path: &PathBuf) -> PathBuf { @@ -343,8 +337,8 @@ fn numbered_backup_path(path: &PathBuf) -> PathBuf { } } -fn existing_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { - let test_path = simple_backup_path(path, &".~1~".to_string()); +fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { + let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); } diff --git a/src/nice/nice.rs b/src/nice/nice.rs index 410da0ebf7a..2d1bf09bca4 100644 --- a/src/nice/nice.rs +++ b/src/nice/nice.rs @@ -73,7 +73,7 @@ process).", NAME, VERSION); let adjustment = match matches.opt_str("adjustment") { Some(nstr) => { - if matches.free.len() == 0 { + if matches.free.is_empty() { show_error!("A command must be given with an adjustment. Try \"{} --help\" for more information.", args[0]); return 125; @@ -87,7 +87,7 @@ process).", NAME, VERSION); } }, None => { - if matches.free.len() == 0 { + if matches.free.is_empty() { println!("{}", niceness); return 0; } diff --git a/src/nl/helper.rs b/src/nl/helper.rs index 2cdd5d9f5ab..f513083569e 100644 --- a/src/nl/helper.rs +++ b/src/nl/helper.rs @@ -10,7 +10,7 @@ fn parse_style(chars: &[char]) -> Result<::NumberingStyle, String> { } else if chars.len() == 1 && chars[0] == 'n' { Ok(::NumberingStyle::NumberForNone) } else if chars.len() > 1 && chars[0] == 'p' { - let s: String = chars[1..].iter().map(|c| *c).collect(); + let s: String = chars[1..].iter().cloned().collect(); match regex::Regex::new(&s) { Ok(re) => Ok(::NumberingStyle::NumberForRegularExpression(re)), Err(_) => Err(String::from("Illegal regular expression")), diff --git a/src/nl/nl.rs b/src/nl/nl.rs index 8426ff4549c..8d54b611547 100644 --- a/src/nl/nl.rs +++ b/src/nl/nl.rs @@ -124,9 +124,9 @@ pub fn uumain(args: Vec) -> i32 { // Update the settings from the command line options, and terminate the // program if some options could not successfully be parsed. let parse_errors = helper::parse_options(&mut settings, &given_options); - if parse_errors.len() > 0 { + if !parse_errors.is_empty() { show_error!("Invalid arguments supplied."); - for message in parse_errors.iter() { + for message in &parse_errors { println!("{}", message); } return 1; @@ -135,7 +135,7 @@ pub fn uumain(args: Vec) -> i32 { let files = given_options.free; let mut read_stdin = files.is_empty(); - for file in files.iter() { + for file in &files { if file == "-" { // If both file names and '-' are specified, we choose to treat first all // regular files, and then read from stdin last. @@ -179,7 +179,7 @@ fn nl (reader: &mut BufReader, settings: &Settings) { let mut line_filter : fn(&str, ®ex::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.len() > 0 && l.chars().rev().next().unwrap() == '\n' { + if !l.is_empty() && l.chars().rev().next().unwrap() == '\n' { l.pop(); } // Next we iterate through the individual chars to see if this diff --git a/src/nohup/nohup.rs b/src/nohup/nohup.rs index 3f5aa49776f..6484d5c029a 100644 --- a/src/nohup/nohup.rs +++ b/src/nohup/nohup.rs @@ -54,7 +54,7 @@ pub fn uumain(args: Vec) -> i32 { if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 } - if matches.free.len() == 0 { + if matches.free.is_empty() { show_error!("Missing operand: COMMAND"); println!("Try `{} --help` for more information.", NAME); return 1 diff --git a/src/paste/paste.rs b/src/paste/paste.rs index 021d25c43f1..7e4eb6af07a 100644 --- a/src/paste/paste.rs +++ b/src/paste/paste.rs @@ -49,7 +49,7 @@ FILE, separated by TABs, to standard output.", NAME, VERSION); println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); - let delimiters = matches.opt_str("delimiters").unwrap_or("\t".to_string()); + let delimiters = matches.opt_str("delimiters").unwrap_or("\t".to_owned()); paste(matches.free, serial, delimiters); } @@ -72,7 +72,7 @@ fn paste(filenames: Vec, serial: bool, delimiters: String) { let mut delim_count = 0; if serial { - for file in files.iter_mut() { + for file in &mut files { let mut output = String::new(); loop { let mut line = String::new(); diff --git a/src/printenv/printenv.rs b/src/printenv/printenv.rs index 0fa2ff9ba0a..10ba49e4e3a 100644 --- a/src/printenv/printenv.rs +++ b/src/printenv/printenv.rs @@ -66,12 +66,9 @@ pub fn exec(args: Vec, separator: &str) { return; } - for env_var in args.iter() { - match env::var(env_var) { - Ok(var) => { - print!("{}{}", var, separator); - } - _ => () + for env_var in &args { + if let Ok(var) = env::var(env_var) { + print!("{}{}", var, separator); } } } diff --git a/src/ptx/ptx.rs b/src/ptx/ptx.rs index 6fd44ee1101..c12a2d5ad6c 100644 --- a/src/ptx/ptx.rs +++ b/src/ptx/ptx.rs @@ -60,9 +60,9 @@ impl Default for Config { input_ref : false, right_ref : false, ignore_case : false, - macro_name : "xx".to_string(), - trunc_str : "/".to_string(), - context_regex : "\\w+".to_string(), + macro_name : "xx".to_owned(), + trunc_str : "/".to_owned(), + context_regex : "\\w+".to_owned(), line_width : 72, gap_size : 3 } @@ -109,9 +109,9 @@ impl WordFilter { if matches.opt_present("W") { matches.opt_str("W").expect("parsing options failed!") } else if config.gnu_ext { - "\\w+".to_string() + "\\w+".to_owned() } else { - "[^ \t\n]+".to_string() + "[^ \t\n]+".to_owned() }; WordFilter { only_specified: o, @@ -153,7 +153,7 @@ fn get_config(matches: &Matches) -> Config { if matches.opt_present("G") { config.gnu_ext = false; config.format = OutFormat::Roff; - config.context_regex = "[^ \t\n]+".to_string(); + config.context_regex = "[^ \t\n]+".to_owned(); } else { crash!(1, "GNU extensions not implemented yet"); } @@ -166,11 +166,11 @@ fn get_config(matches: &Matches) -> Config { config.ignore_case = matches.opt_present("f"); if matches.opt_present("M") { config.macro_name = - matches.opt_str("M").expect(err_msg).to_string(); + matches.opt_str("M").expect(err_msg); } if matches.opt_present("F") { config.trunc_str = - matches.opt_str("F").expect(err_msg).to_string(); + matches.opt_str("F").expect(err_msg); } if matches.opt_present("w") { let width_str = matches.opt_str("w").expect(err_msg); @@ -191,7 +191,7 @@ fn get_config(matches: &Matches) -> Config { config } -fn read_input(input_files: &Vec, config: &Config) -> +fn read_input(input_files: &[String], config: &Config) -> HashMap, usize)> { let mut file_map : HashMap, usize)> = HashMap::new(); @@ -219,7 +219,7 @@ fn read_input(input_files: &Vec, config: &Config) -> let lines: Vec = reader.lines().map(|x| crash_if_err!(1, x)) .collect(); let size = lines.len(); - file_map.insert(filename.to_string(), (lines, lines_so_far)); + file_map.insert(filename.to_owned(), (lines, lines_so_far)); lines_so_far += size } file_map @@ -234,7 +234,7 @@ fn create_word_set(config: &Config, filter: &WordFilter, for (file, lines) in file_map.iter() { let mut count: usize = 0; let offs = lines.1; - for line in (lines.0).iter() { + for line in &lines.0 { // if -r, exclude reference from word set let (ref_beg, ref_end) = match ref_reg.find(line) { Some(x) => x, @@ -245,7 +245,7 @@ fn create_word_set(config: &Config, filter: &WordFilter, if config.input_ref && ((beg, end) == (ref_beg, ref_end)) { continue; } - let mut word = line[beg .. end].to_string(); + let mut word = line[beg .. end].to_owned(); if filter.only_specified && !(filter.only_set.contains(&word)) { continue; @@ -272,7 +272,7 @@ fn create_word_set(config: &Config, filter: &WordFilter, word_set } -fn get_reference(config: &Config, word_ref: &WordRef, line: &String) -> +fn get_reference(config: &Config, word_ref: &WordRef, line: &str) -> String { if config.auto_ref { format!("{}:{}", word_ref.filename, word_ref.local_line_nr + 1) @@ -288,12 +288,12 @@ fn get_reference(config: &Config, word_ref: &WordRef, line: &String) -> } } -fn assert_str_integrity(s: &Vec, beg: usize, end: usize) { +fn assert_str_integrity(s: &[char], beg: usize, end: usize) { assert!(beg <= end); assert!(end <= s.len()); } -fn trim_broken_word_left(s: &Vec, beg: usize, end: usize) -> usize { +fn trim_broken_word_left(s: &[char], beg: usize, end: usize) -> usize { assert_str_integrity(s, beg, end); if beg == end || beg == 0 || s[beg].is_whitespace() || s[beg-1].is_whitespace() { @@ -306,7 +306,7 @@ fn trim_broken_word_left(s: &Vec, beg: usize, end: usize) -> usize { b } -fn trim_broken_word_right(s: &Vec, beg: usize, end: usize) -> usize { +fn trim_broken_word_right(s: &[char], beg: usize, end: usize) -> usize { assert_str_integrity(s, beg, end); if beg == end || end == s.len() || s[end-1].is_whitespace() || s[end].is_whitespace() { @@ -319,7 +319,7 @@ fn trim_broken_word_right(s: &Vec, beg: usize, end: usize) -> usize { e } -fn trim_idx(s: &Vec, beg: usize, end: usize) -> (usize, usize) { +fn trim_idx(s: &[char], beg: usize, end: usize) -> (usize, usize) { assert_str_integrity(s, beg, end); let mut b = beg; let mut e = end; @@ -332,11 +332,11 @@ fn trim_idx(s: &Vec, beg: usize, end: usize) -> (usize, usize) { (b,e) } -fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String, +fn get_output_chunks(all_before: &str, keyword: &str, all_after: &str, config: &Config) -> (String, String, String, String) { - assert_eq!(all_before.trim().to_string(), *all_before); - assert_eq!(keyword.trim().to_string(), *keyword); - assert_eq!(all_after.trim().to_string(), *all_after); + assert_eq!(all_before.trim().to_owned(), *all_before); + assert_eq!(keyword.trim().to_owned(), *keyword); + assert_eq!(all_after.trim().to_owned(), *all_after); let mut head = String::new(); let mut before = String::new(); let mut after = String::new(); @@ -398,7 +398,7 @@ fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String, } // add space before "after" if needed - if after.len() > 0 { + if !after.is_empty() { after = format!(" {}", after); } @@ -407,7 +407,7 @@ fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String, fn tex_mapper(x: char) -> String { match x { - '\\' => "\\backslash{}".to_string(), + '\\' => "\\backslash{}".to_owned(), '$' | '%' | '#' | '&' | '_' => format!("\\{}", x), '}' | '{' => format!("$\\{}$", x), _ => x.to_string() @@ -416,14 +416,14 @@ fn tex_mapper(x: char) -> String { fn adjust_tex_str(context: &str) -> String { let ws_reg = Regex::new(r"[\t\n\v\f\r ]").unwrap(); - let mut fix: String = ws_reg.replace_all(context, " ").trim().to_string(); + let mut fix: String = ws_reg.replace_all(context, " ").trim().to_owned(); let mapped_chunks: Vec = fix.chars().map(tex_mapper).collect(); fix = mapped_chunks.join(""); fix } -fn format_tex_line(config: &Config, word_ref: &WordRef, line: &String, - reference: &String) -> String { +fn format_tex_line(config: &Config, word_ref: &WordRef, line: &str, + reference: &str) -> String { let mut output = String::new(); output.push_str(&format!("\\{} ", config.macro_name)); let all_before = if config.input_ref { @@ -449,7 +449,7 @@ fn format_tex_line(config: &Config, word_ref: &WordRef, line: &String, fn adjust_roff_str(context: &str) -> String { let ws_reg = Regex::new(r"[\t\n\v\f\r]").unwrap(); - ws_reg.replace_all(context, " ").replace("\"", "\"\"").trim().to_string() + ws_reg.replace_all(context, " ").replace("\"", "\"\"").trim().to_owned() } fn format_roff_line(config: &Config, word_ref: &WordRef, line: &str, @@ -478,7 +478,7 @@ fn format_roff_line(config: &Config, word_ref: &WordRef, line: &str, fn write_traditional_output(config: &Config, file_map: &HashMap,usize)>, - words: &BTreeSet, output_filename: &String) { + words: &BTreeSet, output_filename: &str) { let mut writer: BufWriter> = BufWriter::new( if output_filename == "-" { Box::new(stdout()) @@ -555,7 +555,7 @@ pub fn uumain(args: Vec) -> i32 { let output_file = if !config.gnu_ext && matches.free.len() == 2 { matches.free[1].clone() } else { - "-".to_string() + "-".to_owned() }; write_traditional_output(&config, &file_map, &word_set, &output_file); 0 diff --git a/src/readlink/readlink.rs b/src/readlink/readlink.rs index 39d0921999d..7c9ca77c8ac 100644 --- a/src/readlink/readlink.rs +++ b/src/readlink/readlink.rs @@ -75,18 +75,16 @@ pub fn uumain(args: Vec) -> i32 { } let files = matches.free; - if files.len() == 0 { + if files.is_empty() { crash!(1, "missing operand\nTry {} --help for more information", NAME); } - if no_newline && files.len() > 1 { - if !silent { - eprintln!("{}: ignoring --no-newline with multiple arguments", NAME); - no_newline = false; - } + if no_newline && files.len() > 1 && !silent { + eprintln!("{}: ignoring --no-newline with multiple arguments", NAME); + no_newline = false; } - for f in files.iter() { + for f in &files { let p = PathBuf::from(f); if can_mode == CanonicalizeMode::None { match fs::read_link(&p) { diff --git a/src/realpath/realpath.rs b/src/realpath/realpath.rs index 6316bbe751f..d8a41bdb896 100644 --- a/src/realpath/realpath.rs +++ b/src/realpath/realpath.rs @@ -44,7 +44,7 @@ pub fn uumain(args: Vec) -> i32 { if matches.opt_present("V") { version(); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 } - if matches.free.len() == 0 { + if matches.free.is_empty() { show_error!("Missing operand: FILENAME, at least one is required"); println!("Try `{} --help` for more information.", NAME); return 1 @@ -54,7 +54,7 @@ pub fn uumain(args: Vec) -> i32 { let zero = matches.opt_present("z"); let quiet = matches.opt_present("q"); let mut retcode = 0; - for path in matches.free.iter() { + for path in &matches.free { if !resolve_path(path, strip, zero, quiet) { retcode = 1 }; diff --git a/src/relpath/relpath.rs b/src/relpath/relpath.rs index 2c965888fc7..9c67bacedf8 100644 --- a/src/relpath/relpath.rs +++ b/src/relpath/relpath.rs @@ -42,7 +42,7 @@ pub fn uumain(args: Vec) -> i32 { if matches.opt_present("V") { version(); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 } - if matches.free.len() == 0 { + if matches.free.is_empty() { show_error!("Missing operand: TO"); println!("Try `{} --help` for more information.", NAME); return 1 diff --git a/src/rm/rm.rs b/src/rm/rm.rs index ecdcc6a2361..69cf6d7d747 100644 --- a/src/rm/rm.rs +++ b/src/rm/rm.rs @@ -126,19 +126,16 @@ pub fn uumain(args: Vec) -> i32 { fn remove(files: Vec, force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) -> bool { let mut had_err = false; - for filename in files.iter() { + for filename in &files { let filename = &filename[..]; let file = Path::new(filename); if file.exists() { if file.is_dir() { if recursive && (filename != "/" || !preserve_root) { if interactive != InteractiveMode::InteractiveAlways { - match fs::remove_dir_all(file) { - Err(e) => { - had_err = true; - show_error!("could not remove '{}': {}", filename, e); - }, - _ => (), + if let Err(e) = fs::remove_dir_all(file) { + had_err = true; + show_error!("could not remove '{}': {}", filename, e); }; } else { let mut dirs: VecDeque = VecDeque::new(); @@ -185,7 +182,7 @@ fn remove(files: Vec, force: bool, interactive: InteractiveMode, one_fs: }, }; - for f in files.iter() { + for f in &files { had_err = remove_file(f.as_path(), interactive, verbose).bitor(had_err); } diff --git a/src/rmdir/rmdir.rs b/src/rmdir/rmdir.rs index 5f978f541a5..04da57639b8 100644 --- a/src/rmdir/rmdir.rs +++ b/src/rmdir/rmdir.rs @@ -69,18 +69,13 @@ Remove the DIRECTORY(ies), if they are empty.", NAME, VERSION); fn remove(dirs: Vec, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32> { let mut r = Ok(()); - for dir in dirs.iter() { + for dir in &dirs { let path = Path::new(&dir[..]); r = remove_dir(&path, ignore, verbose).and(r); if parents { let mut p = path; - loop { - let new_p = match p.parent() { - Some(p) => p, - None => break, - }; + while let Some(new_p) = p.parent() { p = new_p; - match p.as_os_str().to_str() { None => break, Some(s) => match s { diff --git a/src/seq/seq.rs b/src/seq/seq.rs index 2b97b3d8308..9c1a454176c 100644 --- a/src/seq/seq.rs +++ b/src/seq/seq.rs @@ -148,7 +148,7 @@ fn print_version() { pub fn uumain(args: Vec) -> i32 { let mut options = SeqOptions { - separator: "\n".to_string(), + separator: "\n".to_owned(), terminator: None, widths: false }; @@ -209,7 +209,6 @@ pub fn uumain(args: Vec) -> i32 { 0 } -#[inline(always)] fn done_printing(next: f64, step: f64, last: f64) -> bool { if step >= 0f64 { next > last diff --git a/src/shred/shred.rs b/src/shred/shred.rs index 8911cf86cb2..15d83f7105b 100644 --- a/src/shred/shred.rs +++ b/src/shred/shred.rs @@ -352,7 +352,7 @@ fn wipe_file(path_str: &str, n_passes: usize, remove: bool, let remainder = n_passes % PATTERNS.len(); // How many do we get through on our last time through? for _ in 0..n_full_arrays { - for p in PATTERNS.iter() { + for p in &PATTERNS { pass_sequence.push(PassType::Pattern(*p)); } } diff --git a/src/shuf/shuf.rs b/src/shuf/shuf.rs index bc33a4e9ec0..54bab2bc06d 100644 --- a/src/shuf/shuf.rs +++ b/src/shuf/shuf.rs @@ -79,8 +79,8 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION); if echo { Mode::Echo } else { - if matches.free.len() == 0 { - matches.free.push("-".to_string()); + if matches.free.is_empty() { + matches.free.push("-".to_owned()); } else if matches.free.len() > 1 { show_error!("extra operand '{}'", &matches.free[1][..]); } @@ -212,7 +212,7 @@ fn shuf_bytes(input: &mut Vec<&[u8]>, repeat: bool, count: usize, sep: u8, outpu drop(len); let mut count = count; - while count > 0 && input.len() > 0 { + while count > 0 && !input.is_empty() { let mut r = input.len(); while r >= input.len() { r = rng.next_usize() % len_mod; @@ -238,7 +238,7 @@ fn shuf_bytes(input: &mut Vec<&[u8]>, repeat: bool, count: usize, sep: u8, outpu fn parse_range(input_range: String) -> Result<(usize, usize), String> { let split: Vec<&str> = input_range.split('-').collect(); if split.len() != 2 { - Err("invalid range format".to_string()) + Err("invalid range format".to_owned()) } else { let begin = match split[0].parse::() { Ok(m) => m, @@ -259,9 +259,9 @@ enum WrappedRng { impl WrappedRng { fn next_usize(&mut self) -> usize { - match self { - &mut WrappedRng::RngFile(ref mut r) => r.next_u32() as usize, - &mut WrappedRng::RngDefault(ref mut r) => r.next_u32() as usize, + match *self { + WrappedRng::RngFile(ref mut r) => r.next_u32() as usize, + WrappedRng::RngDefault(ref mut r) => r.next_u32() as usize, } } } diff --git a/src/sort/sort.rs b/src/sort/sort.rs index d18430daa5e..3dbae4c162f 100644 --- a/src/sort/sort.rs +++ b/src/sort/sort.rs @@ -69,7 +69,7 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION); let mut files = matches.free; if files.is_empty() { /* if no file, default to stdin */ - files.push("-".to_string()); + files.push("-".to_owned()); } exec(files, numeric, human_readable, reverse); @@ -78,7 +78,7 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION); } fn exec(files: Vec, numeric: bool, human_readable: bool, reverse: bool) { - for path in files.iter() { + for path in &files { let (reader, _) = match open(path) { Some(x) => x, None => continue, @@ -114,7 +114,7 @@ fn exec(files: Vec, numeric: bool, human_readable: bool, reverse: bool) } /// Parse the beginning string into an f64, returning -inf instead of NaN on errors. -fn permissive_f64_parse(a: &String) -> f64{ +fn permissive_f64_parse(a: &str) -> f64{ //Maybe should be split on non-digit, but then 10e100 won't parse properly. //On the flip side, this will give NEG_INFINITY for "1,234", which might be OK //because there's no way to handle both CSV and thousands separators without a new flag. @@ -135,13 +135,13 @@ fn numeric_compare(a: &String, b: &String) -> Ordering { //f64::cmp isn't implemented because NaN messes with it //but we sidestep that with permissive_f64_parse so just fake it if fa > fb { - return Ordering::Greater; + Ordering::Greater } else if fa < fb { - return Ordering::Less; + Ordering::Less } else { - return Ordering::Equal; + Ordering::Equal } } @@ -162,7 +162,7 @@ fn human_readable_convert(a: &String) -> f64 { 'P' => 1E15, _ => 1f64 }; - return int_part * suffix; + int_part * suffix } /// Compare two strings as if they are human readable sizes. @@ -171,18 +171,17 @@ fn human_readable_size_compare(a: &String, b: &String) -> Ordering { let fa = human_readable_convert(a); let fb = human_readable_convert(b); if fa > fb { - return Ordering::Greater; + Ordering::Greater } else if fa < fb { - return Ordering::Less; + Ordering::Less } else { - return Ordering::Equal; + Ordering::Equal } } -#[inline(always)] fn print_sorted>(iter: T) where S: std::fmt::Display { for line in iter { println!("{}", line); @@ -190,7 +189,7 @@ fn print_sorted>(iter: T) where S: std::fmt::Display { } // from cat.rs -fn open<'a>(path: &str) -> Option<(Box, bool)> { +fn open(path: &str) -> Option<(Box, bool)> { if path == "-" { let stdin = stdin(); return Some((Box::new(stdin) as Box, is_stdin_interactive())); diff --git a/src/split/split.rs b/src/split/split.rs index 704fd9b2754..42df0486beb 100644 --- a/src/split/split.rs +++ b/src/split/split.rs @@ -60,16 +60,16 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is } let mut settings = Settings { - prefix: "".to_string(), + prefix: "".to_owned(), numeric_suffix: false, suffix_length: 0, - input: "".to_string(), - strategy: "".to_string(), - strategy_param: "".to_string(), + input: "".to_owned(), + strategy: "".to_owned(), + strategy_param: "".to_owned(), verbose: false, }; - settings.numeric_suffix = if matches.opt_present("d") { true } else { false }; + settings.numeric_suffix = matches.opt_present("d"); settings.suffix_length = match matches.opt_str("a") { Some(n) => match n.parse() { @@ -79,16 +79,16 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is None => 2 }; - settings.verbose = if matches.opt_present("verbose") { true } else { false }; + settings.verbose = matches.opt_present("verbose"); - settings.strategy = "l".to_string(); - settings.strategy_param = "1000".to_string(); + settings.strategy = "l".to_owned(); + settings.strategy_param = "1000".to_owned(); let strategies = vec!["b", "C", "l"]; - for e in strategies.iter() { + for e in &strategies { match matches.opt_str(*e) { Some(a) => { if settings.strategy == "l" { - settings.strategy = e.to_string(); + settings.strategy = (*e).to_owned(); settings.strategy_param = a; } else { crash!(1, "{}: cannot split in more than one way", NAME) @@ -100,9 +100,9 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is let mut v = matches.free.iter(); let (input, prefix) = match (v.next(), v.next()) { - (Some(a), None) => (a.to_string(), "x".to_string()), - (Some(a), Some(b)) => (a.to_string(), b.to_string()), - (None, _) => ("-".to_string(), "x".to_string()), + (Some(a), None) => (a.to_owned(), "x".to_owned()), + (Some(a), Some(b)) => (a.clone(), b.clone()), + (None, _) => ("-".to_owned(), "x".to_owned()), }; settings.input = input; settings.prefix = prefix; @@ -179,7 +179,7 @@ impl ByteSplitter { _ => crash!(1, "invalid number of bytes") }; let n = if suffix.is_alphabetic() { - match strategy_param.iter().map(|c| *c).collect::().parse::() { + match strategy_param.iter().cloned().collect::().parse::() { Ok(a) => a, Err(e) => crash!(1, "invalid number of bytes: {}", e) } @@ -192,7 +192,7 @@ impl ByteSplitter { Box::new(ByteSplitter { saved_bytes_to_write: n * multiplier, bytes_to_write: n * multiplier, - break_on_line_end: if settings.strategy == "b" { false } else { true }, + break_on_line_end: settings.strategy == "b", require_whole_line: false, }) as Box } @@ -206,7 +206,7 @@ impl Splitter for ByteSplitter { self.bytes_to_write = self.saved_bytes_to_write; control.request_new_file = true; self.require_whole_line = false; - return line[0..0].to_string(); + return line[0..0].to_owned(); } self.bytes_to_write -= n; if n == 0 { @@ -216,13 +216,13 @@ impl Splitter for ByteSplitter { if self.break_on_line_end && n == line.chars().count() { self.require_whole_line = self.break_on_line_end; } - line[..n].to_string() + line[..n].to_owned() } } // (1, 3) -> "aab" fn str_prefix(i: usize, width: usize) -> String { - let mut c = "".to_string(); + let mut c = "".to_owned(); let mut n = i; let mut w = width; while w > 0 { @@ -237,7 +237,7 @@ fn str_prefix(i: usize, width: usize) -> String { // (1, 3) -> "001" fn num_prefix(i: usize, width: usize) -> String { - let mut c = "".to_string(); + let mut c = "".to_owned(); let mut n = i; let mut w = width; while w > 0 { @@ -267,11 +267,11 @@ fn split(settings: &Settings) -> i32 { match settings.strategy.as_ref() { "l" => LineSplitter::new(settings), "b" | "C" => ByteSplitter::new(settings), - a @ _ => crash!(1, "strategy {} not supported", a) + a => crash!(1, "strategy {} not supported", a) }; let mut control = SplitControl { - current_line: "".to_string(), // Request new line + current_line: "".to_owned(), // Request new line request_new_file: true, // Request new file }; @@ -310,7 +310,7 @@ fn split(settings: &Settings) -> i32 { let advance = consumed.chars().count(); let clone = control.current_line.clone(); let sl = clone; - control.current_line = sl[advance..sl.chars().count()].to_string(); + control.current_line = sl[advance..sl.chars().count()].to_owned(); } 0 } diff --git a/src/stdbuf/stdbuf.rs b/src/stdbuf/stdbuf.rs index ac967039ead..bf0921b5589 100644 --- a/src/stdbuf/stdbuf.rs +++ b/src/stdbuf/stdbuf.rs @@ -93,7 +93,7 @@ fn print_usage(opts: &Options) { fn parse_size(size: &str) -> Option { let ext = size.trim_left_matches(|c: char| c.is_digit(10)); let num = size.trim_right_matches(|c: char| c.is_alphabetic()); - let mut recovered = num.to_string(); + let mut recovered = num.to_owned(); recovered.push_str(ext); if recovered != size { return None; @@ -196,19 +196,19 @@ fn exe_path() -> io::Result { fn get_preload_env() -> (String, String) { let (preload, extension) = preload_strings(); - let mut libstdbuf = LIBSTDBUF.to_string(); + let mut libstdbuf = LIBSTDBUF.to_owned(); libstdbuf.push_str(extension); // First search for library in directory of executable. let mut path = exe_path().unwrap_or_else(|_| crash!(1, "Impossible to fetch the path of this executable.")); path.push(libstdbuf.clone()); if path.exists() { match path.as_os_str().to_str() { - Some(s) => { return (preload.to_string(), s.to_string()); }, + Some(s) => { return (preload.to_owned(), s.to_owned()); }, None => crash!(1, "Error while converting path.") }; } // We assume library is in LD_LIBRARY_PATH/ DYLD_LIBRARY_PATH. - (preload.to_string(), libstdbuf) + (preload.to_owned(), libstdbuf) } pub fn uumain(args: Vec) -> i32 { @@ -243,7 +243,7 @@ pub fn uumain(args: Vec) -> i32 { if command_idx == -1 { crash!(125, "Invalid options\nTry 'stdbuf --help' for more information."); } - let ref command_name = args[command_idx as usize]; + let command_name = &args[command_idx as usize]; let mut command = Command::new(command_name); let (preload_env, libstdbuf) = get_preload_env(); command.args(&args[(command_idx as usize) + 1 ..]).env(preload_env, libstdbuf); diff --git a/src/sum/sum.rs b/src/sum/sum.rs index e3fac0d8956..2b8db82c028 100644 --- a/src/sum/sum.rs +++ b/src/sum/sum.rs @@ -106,7 +106,7 @@ Checksum and count the blocks in a file.", NAME, VERSION); let sysv = matches.opt_present("sysv"); let files = if matches.free.is_empty() { - vec!["-".to_string()] + vec!["-".to_owned()] } else { matches.free }; @@ -117,7 +117,7 @@ Checksum and count the blocks in a file.", NAME, VERSION); files.len() > 1 }; - for file in files.iter() { + for file in &files { let reader = match open(file) { Ok(f) => f, _ => crash!(1, "unable to open file") diff --git a/src/tac/tac.rs b/src/tac/tac.rs index fdbbccdd6ef..53d4bb03476 100644 --- a/src/tac/tac.rs +++ b/src/tac/tac.rs @@ -50,16 +50,16 @@ Write each file to standard output, last line first.", NAME, VERSION); let regex = matches.opt_present("r"); let separator = match matches.opt_str("s") { Some(m) => { - if m.len() == 0 { + if m.is_empty() { crash!(1, "separator cannot be empty") } else { m } } - None => "\n".to_string() + None => "\n".to_owned() }; let files = if matches.free.is_empty() { - vec!("-".to_string()) + vec!("-".to_owned()) } else { matches.free }; @@ -74,7 +74,7 @@ fn tac(filenames: Vec, before: bool, _: bool, separator: &str) { let sbytes = separator.as_bytes(); let slen = sbytes.len(); - for filename in filenames.iter() { + for filename in &filenames { let mut file = BufReader::new( if filename == "-" { Box::new(stdin()) as Box @@ -115,7 +115,7 @@ fn tac(filenames: Vec, before: bool, _: bool, separator: &str) { drop(i); // if there isn't a separator at the end of the file, fake it - if offsets.len() == 0 || *offsets.last().unwrap() < data.len() - slen { + if offsets.is_empty() || *offsets.last().unwrap() < data.len() - slen { offsets.push(data.len()); } diff --git a/src/tail/tail.rs b/src/tail/tail.rs index 6c3502c061c..e6bab3a5d57 100644 --- a/src/tail/tail.rs +++ b/src/tail/tail.rs @@ -144,7 +144,7 @@ pub fn uumain(args: Vec) -> i32 { multiple = true; } - for file in files.iter() { + for file in &files { if multiple { if !firstime { println!(""); } println!("==> {} <==", file); @@ -280,7 +280,7 @@ fn tail(reader: &mut BufReader, settings: &Settings) { } } let mut stdout = stdout(); - for datum in ringbuf.iter() { + for datum in &ringbuf { print_string(&mut stdout, datum); } }, @@ -311,7 +311,7 @@ fn tail(reader: &mut BufReader, settings: &Settings) { } } let mut stdout = stdout(); - for datum in ringbuf.iter() { + for datum in &ringbuf { print_byte(&mut stdout, datum); } } @@ -339,7 +339,7 @@ fn print_byte(stdout: &mut T, ch: &u8) { } #[inline] -fn print_string(_: &mut T, s: &String) { +fn print_string(_: &mut T, s: &str) { print!("{}", s); } diff --git a/src/tee/tee.rs b/src/tee/tee.rs index 56bc1925513..68c2c1b57a0 100644 --- a/src/tee/tee.rs +++ b/src/tee/tee.rs @@ -37,7 +37,7 @@ struct Options { files: Vec } -fn options(args: &Vec) -> Result { +fn options(args: &[String]) -> Result { let mut opts = getopts::Options::new(); opts.optflag("a", "append", "append to the given FILEs, do not overwrite"); @@ -54,12 +54,12 @@ fn options(args: &Vec) -> Result { version, NAME, arguments, opts.usage(brief), comment); let mut names: Vec = m.free.clone().into_iter().collect(); - names.push("-".to_string()); + names.push("-".to_owned()); let to_print = if m.opt_present("help") { Some(help) } else if m.opt_present("version") { Some(version) } else { None }; Ok(Options { - program: NAME.to_string(), + program: NAME.to_owned(), append: m.opt_present("append"), ignore_interrupts: m.opt_present("ignore-interrupts"), print_and_exit: to_print, @@ -108,14 +108,14 @@ struct MultiWriter { impl Write for MultiWriter { fn write(&mut self, buf: &[u8]) -> Result { - for writer in self.writers.iter_mut() { + for writer in &mut self.writers { try!(writer.write_all(buf)); } Ok(buf.len()) } fn flush(&mut self) -> Result<()> { - for writer in self.writers.iter_mut() { + for writer in &mut self.writers { try!(writer.flush()); } Ok(()) diff --git a/src/test/test.rs b/src/test/test.rs index 17b7821b86a..6a348862732 100644 --- a/src/test/test.rs +++ b/src/test/test.rs @@ -24,7 +24,7 @@ pub fn uumain(_: Vec) -> i32 { let args = args_os().collect::>(); // This is completely disregarding valid windows paths that aren't valid unicode let args = args.iter().map(|a| a.to_str().unwrap().as_bytes()).collect::>(); - if args.len() == 0 { + if args.is_empty() { return 2; } let args = @@ -145,7 +145,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().ok()) - .map(|i| unsafe { isatty(i) == 1 }).unwrap_or(false) + .map_or(false, |i| unsafe { isatty(i) == 1 }) } fn dispatch(args: &mut &[&[u8]], error: &mut bool) -> bool { @@ -347,7 +347,7 @@ fn path(path: &[u8], cond: PathCondition) -> bool { } else if gid == stat.st_gid { stat.st_mode & ((p as mode_t) << 3) != 0 } else { - stat.st_mode & ((p as mode_t) << 0) != 0 + stat.st_mode & ((p as mode_t)) != 0 } }; diff --git a/src/timeout/timeout.rs b/src/timeout/timeout.rs index 2a35f89a67e..fae55f87ee6 100644 --- a/src/timeout/timeout.rs +++ b/src/timeout/timeout.rs @@ -137,7 +137,7 @@ fn timeout(cmdname: &str, args: &[String], duration: f64, signal: usize, kill_af return_if_err!(ERR_EXIT_STATUS, process.wait()); 137 }, - Err(_) => return 124, + Err(_) => 124, } }, Err(_) => { diff --git a/src/touch/touch.rs b/src/touch/touch.rs index c7e70f3a567..b96f61a7709 100644 --- a/src/touch/touch.rs +++ b/src/touch/touch.rs @@ -83,16 +83,16 @@ pub fn uumain(args: Vec) -> i32 { return 0; } - if matches.opt_present("date") && matches.opts_present(&["reference".to_string(), "t".to_string()]) || - matches.opt_present("reference") && matches.opts_present(&["date".to_string(), "t".to_string()]) || - matches.opt_present("t") && matches.opts_present(&["date".to_string(), "reference".to_string()]) { + if matches.opt_present("date") && matches.opts_present(&["reference".to_owned(), "t".to_owned()]) || + matches.opt_present("reference") && matches.opts_present(&["date".to_owned(), "t".to_owned()]) || + matches.opt_present("t") && matches.opts_present(&["date".to_owned(), "reference".to_owned()]) { panic!("Invalid options: cannot specify reference time from more than one source"); } let (mut atime, mut mtime) = if matches.opt_present("reference") { stat(&matches.opt_str("reference").unwrap()[..], !matches.opt_present("no-dereference")) - } else if matches.opts_present(&["date".to_string(), "t".to_string()]) { + } else if matches.opts_present(&["date".to_owned(), "t".to_owned()]) { let timestamp = if matches.opt_present("date") { parse_date(matches.opt_str("date").unwrap().as_ref()) } else { @@ -104,54 +104,50 @@ pub fn uumain(args: Vec) -> i32 { (now, now) }; - for filename in matches.free.iter() { + for filename in &matches.free { let path = &filename[..]; if !Path::new(path).exists() { // no-dereference included here for compatibility - if matches.opts_present(&["no-create".to_string(), "no-dereference".to_string()]) { + if matches.opts_present(&["no-create".to_owned(), "no-dereference".to_owned()]) { continue; } - match File::create(path) { - Err(e) => { - show_warning!("cannot touch '{}': {}", path, e); - continue; - }, - _ => (), + if let Err(e) = File::create(path) { + show_warning!("cannot touch '{}': {}", path, e); + continue; }; // Minor optimization: if no reference time was specified, we're done. - if !matches.opts_present(&["date".to_string(), "reference".to_string(), "t".to_string()]) { + if !matches.opts_present(&["date".to_owned(), "reference".to_owned(), "t".to_owned()]) { continue; } } // If changing "only" atime or mtime, grab the existing value of the other. // Note that "-a" and "-m" may be passed together; this is not an xor. - if matches.opts_present(&["a".to_string(), "m".to_string(), "time".to_string()]) { + if matches.opts_present(&["a".to_owned(), "m".to_owned(), "time".to_owned()]) { let st = stat(path, !matches.opt_present("no-dereference")); let time = matches.opt_strs("time"); if !(matches.opt_present("a") || - time.contains(&"access".to_string()) || - time.contains(&"atime".to_string()) || - time.contains(&"use".to_string())) { + time.contains(&"access".to_owned()) || + time.contains(&"atime".to_owned()) || + time.contains(&"use".to_owned())) { atime = st.0; } if !(matches.opt_present("m") || - time.contains(&"modify".to_string()) || - time.contains(&"mtime".to_string())) { + time.contains(&"modify".to_owned()) || + time.contains(&"mtime".to_owned())) { mtime = st.1; } } // this follows symlinks and thus does not work correctly for the -h flag // need to use lutimes() c function on supported platforms - match filetime::set_file_times(path, atime, mtime) { - Err(e) => show_warning!("cannot touch '{}': {}", path, e), - _ => (), + if let Err(e) = filetime::set_file_times(path, atime, mtime) { + show_warning!("cannot touch '{}': {}", path, e); }; } @@ -188,10 +184,10 @@ fn parse_date(str: &str) -> FileTime { fn parse_timestamp(s: &str) -> FileTime { let now = time::now(); let (format, ts) = match s.chars().count() { - 15 => ("%Y%m%d%H%M.%S", s.to_string()), - 12 => ("%Y%m%d%H%M", s.to_string()), - 13 => ("%y%m%d%H%M.%S", s.to_string()), - 10 => ("%y%m%d%H%M", s.to_string()), + 15 => ("%Y%m%d%H%M.%S", s.to_owned()), + 12 => ("%Y%m%d%H%M", s.to_owned()), + 13 => ("%y%m%d%H%M.%S", s.to_owned()), + 10 => ("%y%m%d%H%M", s.to_owned()), 11 => ("%Y%m%d%H%M.%S", format!("{}{}", now.tm_year + 1900, s)), 8 => ("%Y%m%d%H%M", format!("{}{}", now.tm_year + 1900, s)), _ => panic!("Unknown timestamp format") diff --git a/src/tr/expand.rs b/src/tr/expand.rs index fd8f885ff15..e5d4d8da02f 100644 --- a/src/tr/expand.rs +++ b/src/tr/expand.rs @@ -81,9 +81,8 @@ impl<'a> Iterator for ExpandSet<'a> { // while the Range has elements, try to return chars from it // but make sure that they actually turn out to be Chars! while let Some(n) = self.range.next() { - match from_u32(n) { - Some(c) => return Some(c), - _ => (), + if let Some(c) = from_u32(n) { + return Some(c); } } diff --git a/src/tr/tr.rs b/src/tr/tr.rs index 096716ccb37..f30553753b1 100644 --- a/src/tr/tr.rs +++ b/src/tr/tr.rs @@ -32,7 +32,7 @@ static NAME: &'static str = "tr"; static VERSION: &'static str = env!("CARGO_PKG_VERSION"); const BUFFER_LEN: usize = 1024; -fn delete<'a>(set: ExpandSet<'a>, complement: bool) { +fn delete(set: ExpandSet, complement: bool) { let mut bset = BitSet::new(); let mut stdout = stdout(); let mut buf = String::with_capacity(BUFFER_LEN + 4); @@ -59,7 +59,7 @@ fn delete<'a>(set: ExpandSet<'a>, complement: bool) { safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); } } - if buf.len() > 0 { + if !buf.is_empty() { safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); pipe_flush!(); } @@ -95,7 +95,7 @@ fn tr<'a>(set1: ExpandSet<'a>, mut set2: ExpandSet<'a>) { } } } - if buf.len() > 0 { + if !buf.is_empty() { safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); pipe_flush!(); } @@ -137,13 +137,13 @@ pub fn uumain(args: Vec) -> i32 { return 0; } - if matches.free.len() == 0 { + if matches.free.is_empty() { usage(&opts); return 1; } let dflag = matches.opt_present("d"); - let cflag = matches.opts_present(&["c".to_string(), "C".to_string()]); + let cflag = matches.opts_present(&["c".to_owned(), "C".to_owned()]); let sets = matches.free; if cflag && !dflag { diff --git a/src/truncate/truncate.rs b/src/truncate/truncate.rs index fe38ef403d4..bd906d61f52 100644 --- a/src/truncate/truncate.rs +++ b/src/truncate/truncate.rs @@ -115,7 +115,7 @@ fn truncate(no_create: bool, _: bool, reference: Option, size: Option parse_size(size.unwrap().as_ref()) }; - for filename in filenames.iter() { + for filename in &filenames { let path = Path::new(filename); match OpenOptions::new().read(true).write(true).create(!no_create).open(path) { Ok(file) => { @@ -135,7 +135,7 @@ fn truncate(no_create: bool, _: bool, reference: Option, size: Option fsize - fsize % refsize, TruncateMode::RoundUp => fsize + fsize % refsize }; - let _ = match file.set_len(tsize) { + match file.set_len(tsize) { Ok(_) => {}, Err(f) => { crash!(1, "{}", f.to_string()) @@ -163,7 +163,6 @@ fn parse_size(size: &str) -> (u64, TruncateMode) { let bytes = { let mut slice = if mode == TruncateMode::Reference { - let size: &str = size; size } else { &size[1..] @@ -175,7 +174,7 @@ fn parse_size(size: &str) -> (u64, TruncateMode) { } } slice - }.to_string(); + }.to_owned(); let mut number: u64 = match bytes.parse() { Ok(num) => num, Err(e) => { diff --git a/src/tsort/tsort.rs b/src/tsort/tsort.rs index 8b2d3859056..59e8602e16d 100644 --- a/src/tsort/tsort.rs +++ b/src/tsort/tsort.rs @@ -54,9 +54,9 @@ pub fn uumain(args: Vec) -> i32 { let input = if files.len() > 1 { crash!(1, "{}, extra operand '{}'", NAME, matches.free[1]); } else if files.is_empty() { - "-".to_string() + "-".to_owned() } else { - files[0].to_string() + files[0].clone() }; let mut stdin_buf; @@ -82,8 +82,8 @@ pub fn uumain(args: Vec) -> i32 { let mut line = String::new(); match reader.read_line(&mut line) { Ok(_) => { - let tokens: Vec = line.trim_right().split_whitespace().map(|s| s.to_string()).collect(); - if tokens.len() == 0 { + let tokens: Vec = line.trim_right().split_whitespace().map(|s| s.to_owned()).collect(); + if tokens.is_empty() { break } for ab in tokens.chunks(2) { @@ -103,7 +103,7 @@ pub fn uumain(args: Vec) -> i32 { crash!(1, "{}, input contains a loop:", input); } - for x in g.result.iter() { + for x in &g.result { println!("{}", x); } @@ -127,11 +127,11 @@ impl Graph { } } - fn has_node(&self, n: &String) -> bool { + fn has_node(&self, n: &str) -> bool { self.in_edges.contains_key(n) } - fn has_edge(&self, from: &String, to: &String) -> bool { + fn has_edge(&self, from: &str, to: &str) -> bool { self.in_edges.get(to).unwrap().contains(from) } @@ -159,7 +159,7 @@ impl Graph { // O(|V|+|E|) fn run_tsort(&mut self) { let mut start_nodes = vec!(); - for (n, edges) in self.in_edges.iter() { + for (n, edges) in &self.in_edges { if edges.is_empty() { start_nodes.push(n.clone()); } @@ -185,7 +185,7 @@ impl Graph { } fn is_acyclic(&self) -> bool { - for (_, edges) in self.out_edges.iter() { + for (_, edges) in &self.out_edges { if !edges.is_empty() { return false } diff --git a/src/tty/tty.rs b/src/tty/tty.rs index 25dcd43e267..8a3b851cbd0 100644 --- a/src/tty/tty.rs +++ b/src/tty/tty.rs @@ -57,7 +57,7 @@ pub fn uumain(args: Vec) -> i32 { if !ptr.is_null() { String::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).to_string() } else { - "".to_string() + "".to_owned() } }; diff --git a/src/uname/uname.rs b/src/uname/uname.rs index ef67e522b6e..a59d90f0642 100644 --- a/src/uname/uname.rs +++ b/src/uname/uname.rs @@ -81,7 +81,7 @@ pub fn uumain(args: Vec) -> i32 { let uname = unsafe { getuname() }; let mut output = String::new(); if matches.opt_present("sysname") || matches.opt_present("all") - || !matches.opts_present(&["nodename".to_string(), "release".to_string(), "version".to_string(), "machine".to_string()]) { + || !matches.opts_present(&["nodename".to_owned(), "release".to_owned(), "version".to_owned(), "machine".to_owned()]) { output.push_str(uname.sysname.as_ref()); output.push_str(" "); } diff --git a/src/unexpand/unexpand.rs b/src/unexpand/unexpand.rs index 9e369897fc5..3f66ab46fc4 100644 --- a/src/unexpand/unexpand.rs +++ b/src/unexpand/unexpand.rs @@ -45,9 +45,8 @@ fn tabstops_parse(s: String) -> Vec { crash!(1, "{}\n", "tab size cannot be 0"); } - match nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { - (false, _) => crash!(1, "{}\n", "tab sizes must be ascending"), - _ => {} + if let (false, _) = nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { + crash!(1, "{}\n", "tab sizes must be ascending"); } nums @@ -73,7 +72,7 @@ impl Options { let files = if matches.free.is_empty() { - vec!("-".to_string()) + vec!("-".to_owned()) } else { matches.free }; @@ -191,7 +190,7 @@ fn unexpand(options: Options) { while match fh.read_until('\n' as u8, &mut buf) { Ok(s) => s > 0, - Err(_) => buf.len() > 0, + Err(_) => !buf.is_empty(), } { let mut byte = 0; // offset into the buffer let mut col = 0; // the current column diff --git a/src/uniq/uniq.rs b/src/uniq/uniq.rs index 546b3ad607e..f0e51e8723c 100644 --- a/src/uniq/uniq.rs +++ b/src/uniq/uniq.rs @@ -58,7 +58,7 @@ impl Uniq { } } - fn skip_fields(&self, line: &String) -> String { + fn skip_fields(&self, line: &str) -> String { match self.skip_fields { Some(skip_fields) => if line.split_whitespace().count() > skip_fields { @@ -73,15 +73,15 @@ impl Uniq { } field = field + 1; } - line[i..].to_string() + line[i..].to_owned() } else { - "".to_string() + "".to_owned() }, - None => line[..].to_string() + None => line[..].to_owned() } } - fn cmp_key(&self, line: &String) -> String { + fn cmp_key(&self, line: &str) -> String { let len = line.len(); if len > 0 { let slice_start = match self.slice_start { @@ -99,11 +99,11 @@ impl Uniq { _ => c, }).collect() } else { - line.clone() + line.to_owned() } } - fn print_lines(&self, writer: &mut BufWriter, lines: &Vec, print_delimiter: bool) -> bool { + fn print_lines(&self, writer: &mut BufWriter, lines: &[String], print_delimiter: bool) -> bool { let mut first_line_printed = false; let mut count = if self.all_repeated { 1 } else { lines.len() }; if lines.len() == 1 && !self.repeats_only @@ -122,7 +122,7 @@ impl Uniq { first_line_printed } - fn print_line(&self, writer: &mut BufWriter, line: &String, count: usize, print_delimiter: bool) { + fn print_line(&self, writer: &mut BufWriter, line: &str, count: usize, print_delimiter: bool) { if print_delimiter { crash_if_err!(1, writer.write_all(&['\n' as u8])); } @@ -183,8 +183,8 @@ pub fn uumain(args: Vec) -> i32 { println!("{} {}", NAME, VERSION); } else { let (in_file_name, out_file_name) = match matches.free.len() { - 0 => ("-".to_string(), "-".to_string()), - 1 => (matches.free[0].clone(), "-".to_string()), + 0 => ("-".to_owned(), "-".to_owned()), + 1 => (matches.free[0].clone(), "-".to_owned()), 2 => (matches.free[0].clone(), matches.free[1].clone()), _ => { crash!(1, "Extra operand: {}", matches.free[2]); @@ -196,13 +196,13 @@ pub fn uumain(args: Vec) -> i32 { all_repeated: matches.opt_present("all-repeated"), delimiters: match matches.opt_default("all-repeated", "none") { Some(ref opt_arg) if opt_arg != "none" => { - let rep_args = ["prepend".to_string(), "separate".to_string()]; + let rep_args = ["prepend".to_owned(), "separate".to_owned()]; if !rep_args.contains(opt_arg) { crash!(1, "Incorrect argument for all-repeated: {}", opt_arg.clone()); } opt_arg.clone() }, - _ => "".to_string() + _ => "".to_owned() }, show_counts: matches.opt_present("count"), skip_fields: opt_parsed("skip-fields", &matches), diff --git a/src/unlink/unlink.rs b/src/unlink/unlink.rs index f74a3bd430d..781090a0cfa 100644 --- a/src/unlink/unlink.rs +++ b/src/unlink/unlink.rs @@ -52,7 +52,7 @@ pub fn uumain(args: Vec) -> i32 { return 0; } - if matches.free.len() == 0 { + if matches.free.is_empty() { crash!(1, "missing operand\nTry '{0} --help' for more information.", NAME); } else if matches.free.len() > 1 { crash!(1, "extra operand: '{1}'\nTry '{0} --help' for more information.", NAME, matches.free[1]); diff --git a/src/uptime/uptime.rs b/src/uptime/uptime.rs index de990eb4ecc..71e9f9cffea 100644 --- a/src/uptime/uptime.rs +++ b/src/uptime/uptime.rs @@ -66,7 +66,7 @@ pub fn uumain(args: Vec) -> i32 { println!("{} {}", NAME, VERSION); return 0; } - if matches.opt_present("help") || matches.free.len() > 0 { + if matches.opt_present("help") || !matches.free.is_empty() { println!("{} {}", NAME, VERSION); println!(""); println!("Usage:"); diff --git a/src/users/users.rs b/src/users/users.rs index 391fc3a063a..86081d76abc 100644 --- a/src/users/users.rs +++ b/src/users/users.rs @@ -74,7 +74,7 @@ pub fn uumain(args: Vec) -> i32 { return 0; } - let filename = if matches.free.len() > 0 { + let filename = if !matches.free.is_empty() { matches.free[0].as_ref() } else { DEFAULT_FILE @@ -111,7 +111,7 @@ fn exec(filename: &str) { endutxent(); } - if users.len() > 0 { + if !users.is_empty() { users.sort(); println!("{}", users.join(" ")); } diff --git a/src/uucore/c_types.rs b/src/uucore/c_types.rs index cdc8b3649af..477927ba089 100644 --- a/src/uucore/c_types.rs +++ b/src/uucore/c_types.rs @@ -109,7 +109,7 @@ extern { pub fn getgroupcount(name: *const c_char, gid: gid_t) -> int32_t; } -pub fn get_pw_from_args(free: &Vec) -> Option { +pub fn get_pw_from_args(free: &[String]) -> Option { if free.len() == 1 { let username = &free[0][..]; @@ -219,7 +219,7 @@ pub fn group(possible_pw: Option, nflag: bool) { Err(errno) => crash!(1, "failed to get group list (errno={})", errno), Ok(groups) => { - for &g in groups.iter() { + for &g in &groups { if nflag { let group = unsafe { getgrgid(g) }; if !group.is_null() { diff --git a/src/uucore/fs.rs b/src/uucore/fs.rs index 682abe00c39..19a77e10972 100644 --- a/src/uucore/fs.rs +++ b/src/uucore/fs.rs @@ -82,7 +82,7 @@ pub fn canonicalize>(original: P, can_mode: CanonicalizeMode) -> } // Resolve the symlinks where possible - if parts.len() > 0 { + if !parts.is_empty() { for part in parts[..parts.len()-1].iter() { result.push(part); diff --git a/src/uucore/parse_time.rs b/src/uucore/parse_time.rs index 608601fe152..2315edb9827 100644 --- a/src/uucore/parse_time.rs +++ b/src/uucore/parse_time.rs @@ -10,7 +10,7 @@ pub fn from_str(string: &str) -> Result { let len = string.len(); if len == 0 { - return Err("empty string".to_string()) + return Err("empty string".to_owned()) } let slice = &string[..len - 1]; let (numstr, times) = match string.chars().next_back().unwrap() { diff --git a/src/uucore/signals.rs b/src/uucore/signals.rs index 62db82f1be1..db360975afa 100644 --- a/src/uucore/signals.rs +++ b/src/uucore/signals.rs @@ -141,7 +141,7 @@ pub fn signal_by_name_or_value(signal_name_or_value: &str) -> Option { if signal_name_or_value == "0" { return Some(0); } - for signal in ALL_SIGNALS.iter() { + for signal in &ALL_SIGNALS { let long_name = format!("SIG{}", signal.name); if signal.name == signal_name_or_value || (signal_name_or_value == signal.value.to_string()) || (long_name == signal_name_or_value) { return Some(signal.value); diff --git a/src/uutils/uutils.rs b/src/uutils/uutils.rs index f4724d2f40b..bbe58b98528 100644 --- a/src/uutils/uutils.rs +++ b/src/uutils/uutils.rs @@ -28,7 +28,7 @@ fn usage(cmap: &UtilityMap) { println!("Currently defined functions:"); let mut utils: Vec<&str> = cmap.keys().map(|&s| s).collect(); utils.sort(); - for util in utils.iter() { + for util in utils { println!("\t{}", util); } } @@ -83,7 +83,7 @@ fn main() { let util = &args[1][..]; match umap.get(util) { Some(&uumain) => { - std::process::exit(uumain(vec![util.to_string(), "--help".to_string()])); + std::process::exit(uumain(vec![util.to_owned(), "--help".to_owned()])); } None => { println!("{}: applet not found", util); diff --git a/src/wc/wc.rs b/src/wc/wc.rs index 602b2d383da..42106826d24 100644 --- a/src/wc/wc.rs +++ b/src/wc/wc.rs @@ -104,7 +104,7 @@ pub fn uumain(args: Vec) -> i32 { } if matches.free.is_empty() { - matches.free.push("-".to_string()); + matches.free.push("-".to_owned()); } let settings = Settings::new(&matches); @@ -139,7 +139,7 @@ fn wc(files: Vec, settings: &Settings) -> StdResult<(), i32> { let mut results = vec!(); let mut max_width: usize = 0; - for path in files.iter() { + for path in &files { let mut reader = try!(open(&path[..])); let mut line_count: usize = 0; @@ -153,9 +153,9 @@ fn wc(files: Vec, settings: &Settings) -> StdResult<(), i32> { // hence the option wrapped in a result here while match reader.read_until(LF, &mut raw_line) { Ok(n) if n > 0 => true, - Err(ref e) if raw_line.len() > 0 => { + Err(ref e) if !raw_line.is_empty() => { show_warning!("Error while reading {}: {}", path, e); - raw_line.len() > 0 + !raw_line.is_empty() }, _ => false, } { @@ -190,7 +190,7 @@ fn wc(files: Vec, settings: &Settings) -> StdResult<(), i32> { } results.push(Result { - title: path.to_string(), + title: path.clone(), bytes: byte_count, chars: char_count, lines: line_count, @@ -211,13 +211,13 @@ fn wc(files: Vec, settings: &Settings) -> StdResult<(), i32> { max_width = total_byte_count.to_string().len() + 1; } - for result in results.iter() { + for result in &results { print_stats(settings, &result, max_width); } if files.len() > 1 { let result = Result { - title: "total".to_string(), + title: "total".to_owned(), bytes: total_byte_count, chars: total_char_count, lines: total_line_count, diff --git a/src/yes/yes.rs b/src/yes/yes.rs index 2bc3e75dcc4..adfd9136548 100644 --- a/src/yes/yes.rs +++ b/src/yes/yes.rs @@ -47,7 +47,7 @@ pub fn uumain(args: Vec) -> i32 { return 0; } let string = if matches.free.is_empty() { - "y".to_string() + "y".to_owned() } else { matches.free.join(" ") };