From 5af66753afdcd601035fef5f3edd3091d70eb756 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 11:04:36 +0100 Subject: [PATCH 01/10] remove needless borrows --- src/bin/coreutils.rs | 2 +- src/uu/cat/src/cat.rs | 4 ++-- src/uu/chcon/src/errors.rs | 4 ++-- src/uu/factor/sieve.rs | 2 +- src/uu/pathchk/src/pathchk.rs | 18 +++++++++--------- .../num_format/formatters/float_common.rs | 2 +- tests/by-util/test_tail.rs | 12 ++++++------ 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/bin/coreutils.rs b/src/bin/coreutils.rs index e83b6f697..ddebaae18 100644 --- a/src/bin/coreutils.rs +++ b/src/bin/coreutils.rs @@ -64,7 +64,7 @@ fn main() { // * prefix/stem may be any string ending in a non-alphanumeric character let util_name = if let Some(util) = utils.keys().find(|util| { binary_as_util.ends_with(*util) - && !(&binary_as_util[..binary_as_util.len() - (*util).len()]) + && !binary_as_util[..binary_as_util.len() - (*util).len()] .ends_with(char::is_alphanumeric) }) { // prefixed util => replace 0th (aka, executable name) argument diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index 3f17124f8..4b113f880 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -479,7 +479,7 @@ fn write_lines( if !state.at_line_start || !options.squeeze_blank || !state.one_blank_kept { state.one_blank_kept = true; if state.at_line_start && options.number == NumberingMode::All { - write!(&mut writer, "{0:6}\t", state.line_number)?; + write!(writer, "{0:6}\t", state.line_number)?; state.line_number += 1; } writer.write_all(options.end_of_line().as_bytes())?; @@ -498,7 +498,7 @@ fn write_lines( } state.one_blank_kept = false; if state.at_line_start && options.number != NumberingMode::None { - write!(&mut writer, "{0:6}\t", state.line_number)?; + write!(writer, "{0:6}\t", state.line_number)?; state.line_number += 1; } diff --git a/src/uu/chcon/src/errors.rs b/src/uu/chcon/src/errors.rs index 2d8f72e67..8a1678a85 100644 --- a/src/uu/chcon/src/errors.rs +++ b/src/uu/chcon/src/errors.rs @@ -64,10 +64,10 @@ impl Error { pub(crate) fn report_full_error(mut err: &dyn std::error::Error) -> String { let mut desc = String::with_capacity(256); - write!(&mut desc, "{}", err).unwrap(); + write!(desc, "{}", err).unwrap(); while let Some(source) = err.source() { err = source; - write!(&mut desc, ". {}", err).unwrap(); + write!(desc, ". {}", err).unwrap(); } desc } diff --git a/src/uu/factor/sieve.rs b/src/uu/factor/sieve.rs index 492c8159f..f783c2d98 100644 --- a/src/uu/factor/sieve.rs +++ b/src/uu/factor/sieve.rs @@ -74,7 +74,7 @@ impl Sieve { #[allow(dead_code)] #[inline] pub fn odd_primes() -> PrimeSieve { - (&INIT_PRIMES[1..]).iter().copied().chain(Sieve::new()) + INIT_PRIMES[1..].iter().copied().chain(Sieve::new()) } } diff --git a/src/uu/pathchk/src/pathchk.rs b/src/uu/pathchk/src/pathchk.rs index df77c42f6..5fb75366d 100644 --- a/src/uu/pathchk/src/pathchk.rs +++ b/src/uu/pathchk/src/pathchk.rs @@ -132,7 +132,7 @@ fn check_basic(path: &[String]) -> bool { // path length if total_len > POSIX_PATH_MAX { writeln!( - &mut std::io::stderr(), + std::io::stderr(), "limit {} exceeded by length {} of file name {}", POSIX_PATH_MAX, total_len, @@ -140,7 +140,7 @@ fn check_basic(path: &[String]) -> bool { ); return false; } else if total_len == 0 { - writeln!(&mut std::io::stderr(), "empty file name"); + writeln!(std::io::stderr(), "empty file name"); return false; } // components: character portability and length @@ -148,7 +148,7 @@ fn check_basic(path: &[String]) -> bool { let component_len = p.len(); if component_len > POSIX_NAME_MAX { writeln!( - &mut std::io::stderr(), + std::io::stderr(), "limit {} exceeded by length {} of file name component {}", POSIX_NAME_MAX, component_len, @@ -170,7 +170,7 @@ fn check_extra(path: &[String]) -> bool { for p in path { if p.starts_with('-') { writeln!( - &mut std::io::stderr(), + std::io::stderr(), "leading hyphen in file name component {}", p.quote() ); @@ -179,7 +179,7 @@ fn check_extra(path: &[String]) -> bool { } // path length if path.join("/").is_empty() { - writeln!(&mut std::io::stderr(), "empty file name"); + writeln!(std::io::stderr(), "empty file name"); return false; } true @@ -192,7 +192,7 @@ fn check_default(path: &[String]) -> bool { // path length if total_len > libc::PATH_MAX as usize { writeln!( - &mut std::io::stderr(), + std::io::stderr(), "limit {} exceeded by length {} of file name {}", libc::PATH_MAX, total_len, @@ -205,7 +205,7 @@ fn check_default(path: &[String]) -> bool { let component_len = p.len(); if component_len > libc::FILENAME_MAX as usize { writeln!( - &mut std::io::stderr(), + std::io::stderr(), "limit {} exceeded by length {} of file name component {}", libc::FILENAME_MAX, component_len, @@ -227,7 +227,7 @@ fn check_searchable(path: &str) -> bool { if e.kind() == ErrorKind::NotFound { true } else { - writeln!(&mut std::io::stderr(), "{}", e); + writeln!(std::io::stderr(), "{}", e); false } } @@ -241,7 +241,7 @@ fn check_portable_chars(path_segment: &str) -> bool { if !VALID_CHARS.contains(ch) { let invalid = path_segment[i..].chars().next().unwrap(); writeln!( - &mut std::io::stderr(), + std::io::stderr(), "nonportable character '{}' in file name component {}", invalid, path_segment.quote() diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs index 97009b586..95b0e34e6 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs @@ -186,7 +186,7 @@ fn round_terminal_digit( if position < after_dec.len() { let digit_at_pos: char; { - digit_at_pos = (&after_dec[position..=position]).chars().next().expect(""); + digit_at_pos = after_dec[position..=position].chars().next().expect(""); } if let '5'..='9' = digit_at_pos { let (new_after_dec, finished_in_dec) = _round_str_from(&after_dec, position); diff --git a/tests/by-util/test_tail.rs b/tests/by-util/test_tail.rs index edb8066d6..dcdb2e9dc 100644 --- a/tests/by-util/test_tail.rs +++ b/tests/by-util/test_tail.rs @@ -205,13 +205,13 @@ fn test_single_big_args() { let mut big_input = at.make_file(FILE); for i in 0..LINES { - writeln!(&mut big_input, "Line {}", i).expect("Could not write to FILE"); + writeln!(big_input, "Line {}", i).expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (LINES - N_ARG)..LINES { - writeln!(&mut big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); + writeln!(big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); @@ -254,14 +254,14 @@ fn test_bytes_big() { let mut big_input = at.make_file(FILE); for i in 0..BYTES { let digit = from_digit((i % 10) as u32, 10).unwrap(); - write!(&mut big_input, "{}", digit).expect("Could not write to FILE"); + write!(big_input, "{}", digit).expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (BYTES - N_ARG)..BYTES { let digit = from_digit((i % 10) as u32, 10).unwrap(); - write!(&mut big_expected, "{}", digit).expect("Could not write to EXPECTED_FILE"); + write!(big_expected, "{}", digit).expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); @@ -290,13 +290,13 @@ fn test_lines_with_size_suffix() { let mut big_input = at.make_file(FILE); for i in 0..LINES { - writeln!(&mut big_input, "Line {}", i).expect("Could not write to FILE"); + writeln!(big_input, "Line {}", i).expect("Could not write to FILE"); } big_input.flush().expect("Could not flush FILE"); let mut big_expected = at.make_file(EXPECTED_FILE); for i in (LINES - N_ARG)..LINES { - writeln!(&mut big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); + writeln!(big_expected, "Line {}", i).expect("Could not write to EXPECTED_FILE"); } big_expected.flush().expect("Could not flush EXPECTED_FILE"); From f2074140ec9f85075a2936dea3b25afe5eda1ed9 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 11:07:40 +0100 Subject: [PATCH 02/10] use 'char' instead of 'str' for single character patterns --- src/uu/pinky/src/pinky.rs | 4 ++-- src/uucore/src/lib/features/fs.rs | 2 +- tests/by-util/test_pinky.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/uu/pinky/src/pinky.rs b/src/uu/pinky/src/pinky.rs index 274976075..ce98e0cfb 100644 --- a/src/uu/pinky/src/pinky.rs +++ b/src/uu/pinky/src/pinky.rs @@ -275,7 +275,7 @@ impl Pinky { if let Some(n) = gecos.find(',') { gecos.truncate(n + 1); } - print!(" {:<19.19}", gecos.replace("&", &pw.name.capitalize())); + print!(" {:<19.19}", gecos.replace('&', &pw.name.capitalize())); } else { print!(" {:19}", " ???"); } @@ -339,7 +339,7 @@ impl Pinky { for u in &self.names { print!("Login name: {:<28}In real life: ", u); if let Ok(pw) = Passwd::locate(u.as_str()) { - println!(" {}", pw.user_info.replace("&", &pw.name.capitalize())); + println!(" {}", pw.user_info.replace('&', &pw.name.capitalize())); if self.include_home_and_shell { print!("Directory: {:<29}", pw.user_dir); println!("Shell: {}", pw.user_shell); diff --git a/src/uucore/src/lib/features/fs.rs b/src/uucore/src/lib/features/fs.rs index ef3dd6adf..680f0f72b 100644 --- a/src/uucore/src/lib/features/fs.rs +++ b/src/uucore/src/lib/features/fs.rs @@ -505,7 +505,7 @@ mod tests { let normalized = normalize_path(path); assert_eq!( test.test - .replace("/", std::path::MAIN_SEPARATOR.to_string().as_str()), + .replace('/', std::path::MAIN_SEPARATOR.to_string().as_str()), normalized.to_str().expect("Path is not valid utf-8!") ); } diff --git a/tests/by-util/test_pinky.rs b/tests/by-util/test_pinky.rs index 05525e927..274b72d65 100644 --- a/tests/by-util/test_pinky.rs +++ b/tests/by-util/test_pinky.rs @@ -24,7 +24,7 @@ fn test_capitalize() { fn test_long_format() { let login = "root"; let pw: Passwd = Passwd::locate(login).unwrap(); - let real_name = pw.user_info.replace("&", &pw.name.capitalize()); + let real_name = pw.user_info.replace('&', &pw.name.capitalize()); let ts = TestScenario::new(util_name!()); ts.ucmd().arg("-l").arg(login).succeeds().stdout_is(format!( "Login name: {:<28}In real life: {}\nDirectory: {:<29}Shell: {}\n\n", From 191e29f951b5ba94588d18a7a3488e266c0f13e1 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 11:09:50 +0100 Subject: [PATCH 03/10] simplify some boolean operations --- tests/by-util/test_od.rs | 6 +++--- tests/common/util.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/by-util/test_od.rs b/tests/by-util/test_od.rs index 6c167b325..a6a81d1d6 100644 --- a/tests/by-util/test_od.rs +++ b/tests/by-util/test_od.rs @@ -37,7 +37,7 @@ fn test_file() { let mut f = File::create(&file).unwrap(); // spell-checker:disable-next-line assert!( - !f.write_all(b"abcdefghijklmnopqrstuvwxyz\n").is_err(), + f.write_all(b"abcdefghijklmnopqrstuvwxyz\n").is_ok(), "Test setup failed - could not write file" ); } @@ -78,7 +78,7 @@ fn test_2files() { for &(path, data) in &[(&file1, "abcdefghijklmnop"), (&file2, "qrstuvwxyz\n")] { let mut f = File::create(&path).unwrap(); assert!( - !f.write_all(data.as_bytes()).is_err(), + f.write_all(data.as_bytes()).is_ok(), "Test setup failed - could not write file" ); } @@ -130,7 +130,7 @@ fn test_from_mixed() { for &(path, data) in &[(&file1, data1), (&file3, data3)] { let mut f = File::create(&path).unwrap(); assert!( - !f.write_all(data.as_bytes()).is_err(), + f.write_all(data.as_bytes()).is_ok(), "Test setup failed - could not write file" ); } diff --git a/tests/common/util.rs b/tests/common/util.rs index 79fe4d5d7..0b44851db 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -982,7 +982,7 @@ impl UCommand { /// provides standard input to feed in to the command when spawned pub fn pipe_in>>(&mut self, input: T) -> &mut UCommand { assert!( - !self.bytes_into_stdin.is_some(), + self.bytes_into_stdin.is_none(), "{}", MULTIPLE_STDIN_MEANINGLESS ); @@ -1000,7 +1000,7 @@ impl UCommand { /// This is typically useful to test non-standard workflows /// like feeding something to a command that does not read it pub fn ignore_stdin_write_error(&mut self) -> &mut UCommand { - assert!(!self.bytes_into_stdin.is_none(), "{}", NO_STDIN_MEANINGLESS); + assert!(self.bytes_into_stdin.is_some(), "{}", NO_STDIN_MEANINGLESS); self.ignore_stdin_write_error = true; self } From 8bb6c4effaa66f8f8cc6f573a7a6670416ed6fe1 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 11:13:02 +0100 Subject: [PATCH 04/10] use pointer args --- src/uu/ls/src/ls.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index 2647e77ba..d7bbdae9d 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -1473,7 +1473,7 @@ fn list(locs: Vec<&Path>, config: Config) -> UResult<()> { Ok(()) } -fn sort_entries(entries: &mut Vec, config: &Config, out: &mut BufWriter) { +fn sort_entries(entries: &mut [PathData], config: &Config, out: &mut BufWriter) { match config.sort { Sort::Time => entries.sort_by_key(|k| { Reverse( From f4c6ea0ee8ab05231a5652962dbfdd0aee3bb6b0 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 11:14:56 +0100 Subject: [PATCH 05/10] remove unnecessary 'to_owned' --- tests/by-util/test_cat.rs | 2 +- tests/by-util/test_mv.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/by-util/test_cat.rs b/tests/by-util/test_cat.rs index 26d929c82..64a511656 100644 --- a/tests/by-util/test_cat.rs +++ b/tests/by-util/test_cat.rs @@ -172,7 +172,7 @@ fn test_piped_to_dev_full() { .set_stdout(dev_full) .pipe_in_fixture("alpha.txt") .fails() - .stderr_contains(&"No space left on device".to_owned()); + .stderr_contains("No space left on device"); } } } diff --git a/tests/by-util/test_mv.rs b/tests/by-util/test_mv.rs index 9fccc90a2..89f4043f8 100644 --- a/tests/by-util/test_mv.rs +++ b/tests/by-util/test_mv.rs @@ -263,7 +263,7 @@ fn test_mv_same_file_dot_dir() { ucmd.arg(".") .arg(".") .fails() - .stderr_is("mv: '.' and '.' are the same file\n".to_string()); + .stderr_is("mv: '.' and '.' are the same file\n"); } #[test] From a2d5f06be40fc317e02301140735481643b4e5b4 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 13:07:20 +0100 Subject: [PATCH 06/10] remove needless pass by value --- src/uu/base32/src/base_common.rs | 2 +- src/uu/cat/src/cat.rs | 6 +- src/uu/chmod/src/chmod.rs | 6 +- src/uu/cp/src/cp.rs | 8 +-- src/uu/csplit/src/csplit.rs | 22 +++--- src/uu/cut/src/cut.rs | 4 +- src/uu/cut/src/searcher.rs | 12 ++-- src/uu/dd/src/dd.rs | 16 ++--- .../src/dd_unit_tests/block_unblock_tests.rs | 70 +++++++++---------- src/uu/dircolors/src/dircolors.rs | 6 +- src/uu/du/src/du.rs | 6 +- src/uu/echo/src/echo.rs | 5 +- src/uu/expand/src/expand.rs | 14 ++-- src/uu/fold/src/fold.rs | 6 +- src/uu/id/src/id.rs | 4 +- src/uu/install/src/install.rs | 12 ++-- src/uu/ls/src/ls.rs | 24 +++---- src/uu/ls/src/quoting_style.rs | 52 +++++++------- src/uu/mktemp/src/mktemp.rs | 6 +- src/uu/mv/src/mv.rs | 14 ++-- src/uu/numfmt/src/numfmt.rs | 18 ++--- src/uu/od/src/od.rs | 16 ++--- src/uu/od/src/parse_inputs.rs | 4 +- src/uu/paste/src/paste.rs | 6 +- src/uu/pr/src/pr.rs | 16 ++--- src/uu/rm/src/rm.rs | 12 ++-- src/uu/runcon/src/runcon.rs | 6 +- src/uu/seq/src/seq.rs | 16 ++--- src/uu/sleep/src/sleep.rs | 6 +- src/uu/sort/src/check.rs | 8 +-- src/uu/sort/src/ext_sort.rs | 14 ++-- src/uu/sort/src/merge.rs | 4 +- src/uu/sort/src/numeric_str_cmp.rs | 32 ++++----- src/uu/sort/src/sort.rs | 8 +-- src/uu/split/src/split.rs | 6 +- src/uu/stat/src/stat.rs | 12 ++-- src/uu/stdbuf/src/stdbuf.rs | 8 +-- src/uu/tac/src/tac.rs | 6 +- src/uu/tee/src/tee.rs | 4 +- src/uu/test/src/test.rs | 42 +++++------ src/uu/timeout/src/timeout.rs | 4 +- src/uu/tr/src/convert.rs | 4 +- src/uu/tr/src/tr.rs | 2 +- src/uu/truncate/src/truncate.rs | 16 ++--- src/uu/unexpand/src/unexpand.rs | 14 ++-- src/uu/uniq/src/uniq.rs | 12 ++-- src/uu/wc/src/wc.rs | 8 +-- src/uucore/src/lib/features/encoding.rs | 4 +- src/uucore/src/lib/features/fsext.rs | 16 ++--- .../num_format/formatters/base_conv/mod.rs | 6 +- .../num_format/formatters/base_conv/tests.rs | 2 +- .../tokenize/num_format/num_format.rs | 4 +- tests/by-util/test_basename.rs | 10 +-- tests/by-util/test_chmod.rs | 8 +-- tests/common/util.rs | 14 ++-- 55 files changed, 332 insertions(+), 331 deletions(-) diff --git a/src/uu/base32/src/base_common.rs b/src/uu/base32/src/base_common.rs index e90777abc..35295a295 100644 --- a/src/uu/base32/src/base_common.rs +++ b/src/uu/base32/src/base_common.rs @@ -153,7 +153,7 @@ pub fn handle_input( if !decode { match data.encode() { Ok(s) => { - wrap_print(&data, s); + wrap_print(&data, &s); Ok(()) } Err(_) => Err(USimpleError::new( diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index 4b113f880..e7fd31497 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -236,7 +236,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { show_tabs, squeeze_blank, }; - cat_files(files, &options) + cat_files(&files, &options) } pub fn uu_app<'a>() -> App<'a> { @@ -365,7 +365,7 @@ fn cat_path( } } -fn cat_files(files: Vec, options: &OutputOptions) -> UResult<()> { +fn cat_files(files: &[String], options: &OutputOptions) -> UResult<()> { let out_info = FileInformation::from_file(&std::io::stdout()); let mut state = OutputState { @@ -376,7 +376,7 @@ fn cat_files(files: Vec, options: &OutputOptions) -> UResult<()> { }; let mut error_messages: Vec = Vec::new(); - for path in &files { + for path in files { if let Err(err) = cat_path(path, options, &mut state, out_info.as_ref()) { error_messages.push(format!("{}: {}", path.maybe_quote(), err)); } diff --git a/src/uu/chmod/src/chmod.rs b/src/uu/chmod/src/chmod.rs index 9cf108eeb..9b14c867f 100644 --- a/src/uu/chmod/src/chmod.rs +++ b/src/uu/chmod/src/chmod.rs @@ -118,7 +118,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { cmode, }; - chmoder.chmod(files) + chmoder.chmod(&files) } pub fn uu_app<'a>() -> App<'a> { @@ -193,10 +193,10 @@ struct Chmoder { } impl Chmoder { - fn chmod(&self, files: Vec) -> UResult<()> { + fn chmod(&self, files: &[String]) -> UResult<()> { let mut r = Ok(()); - for filename in &files { + for filename in files { let filename = &filename[..]; let file = Path::new(filename); if !file.exists() { diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index d005bd718..a0d62295e 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -752,7 +752,7 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec, source: &std::path::Path, - dest: std::path::PathBuf, + dest: &std::path::Path, found_hard_link: &mut bool, ) -> CopyResult<()> { // Redox does not currently support hard links @@ -805,7 +805,7 @@ fn preserve_hardlinks( for hard_link in hard_links.iter() { if hard_link.1 == inode { - std::fs::hard_link(hard_link.0.clone(), dest.clone()).unwrap(); + std::fs::hard_link(hard_link.0.clone(), dest).unwrap(); *found_hard_link = true; } } @@ -849,7 +849,7 @@ fn copy(sources: &[Source], target: &TargetSlice, options: &Options) -> CopyResu let mut found_hard_link = false; if preserve_hard_links { let dest = construct_dest_path(source, target, &target_type, options)?; - preserve_hardlinks(&mut hard_links, source, dest, &mut found_hard_link)?; + preserve_hardlinks(&mut hard_links, source, &dest, &mut found_hard_link)?; } if !found_hard_link { if let Err(error) = @@ -1031,7 +1031,7 @@ fn copy_directory( let mut found_hard_link = false; let source = path.to_path_buf(); let dest = local_to_target.as_path().to_path_buf(); - preserve_hardlinks(&mut hard_links, &source, dest, &mut found_hard_link)?; + preserve_hardlinks(&mut hard_links, &source, &dest, &mut found_hard_link)?; if !found_hard_link { match copy_file( path.as_path(), diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index 3d7136dcd..6f79b69f2 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -108,9 +108,9 @@ where input_iter.rewind_buffer(); if let Some((_, line)) = input_iter.next() { split_writer.new_writer()?; - split_writer.writeln(line?)?; + split_writer.writeln(&line?)?; for (_, line) in input_iter { - split_writer.writeln(line?)?; + split_writer.writeln(&line?)?; } split_writer.finish_split(); } @@ -250,7 +250,7 @@ impl<'a> SplitWriter<'a> { /// # Errors /// /// Some [`io::Error`] may occur when attempting to write the line. - fn writeln(&mut self, line: String) -> io::Result<()> { + fn writeln(&mut self, line: &str) -> io::Result<()> { if !self.dev_null { match self.current_writer { Some(ref mut current_writer) => { @@ -343,7 +343,7 @@ impl<'a> SplitWriter<'a> { } Ordering::Greater => (), } - self.writeln(l)?; + self.writeln(&l)?; } self.finish_split(); ret @@ -373,7 +373,7 @@ impl<'a> SplitWriter<'a> { // The offset is zero or positive, no need for a buffer on the lines read. // NOTE: drain the buffer of input_iter, no match should be done within. for line in input_iter.drain_buffer() { - self.writeln(line)?; + self.writeln(&line)?; } // retain the matching line input_iter.set_size_of_buffer(1); @@ -390,7 +390,7 @@ impl<'a> SplitWriter<'a> { ); } // a positive offset, some more lines need to be added to the current split - (false, _) => self.writeln(l)?, + (false, _) => self.writeln(&l)?, _ => (), }; offset -= 1; @@ -399,7 +399,7 @@ impl<'a> SplitWriter<'a> { while offset > 0 { match input_iter.next() { Some((_, line)) => { - self.writeln(line?)?; + self.writeln(&line?)?; } None => { self.finish_split(); @@ -413,7 +413,7 @@ impl<'a> SplitWriter<'a> { self.finish_split(); return Ok(()); } - self.writeln(l)?; + self.writeln(&l)?; } } else { // With a negative offset we use a buffer to keep the lines within the offset. @@ -427,7 +427,7 @@ impl<'a> SplitWriter<'a> { let l = line?; if regex.is_match(&l) { for line in input_iter.shrink_buffer_to_size() { - self.writeln(line)?; + self.writeln(&line)?; } if !self.options.suppress_matched { // add 1 to the buffer size to make place for the matched line @@ -444,12 +444,12 @@ impl<'a> SplitWriter<'a> { return Ok(()); } if let Some(line) = input_iter.add_line_to_buffer(ln, l) { - self.writeln(line)?; + self.writeln(&line)?; } } // no match, drain the buffer into the current split for line in input_iter.drain_buffer() { - self.writeln(line)?; + self.writeln(&line)?; } } diff --git a/src/uu/cut/src/cut.rs b/src/uu/cut/src/cut.rs index 8ad5fd230..1c9470370 100644 --- a/src/uu/cut/src/cut.rs +++ b/src/uu/cut/src/cut.rs @@ -340,7 +340,7 @@ fn cut_fields(reader: R, ranges: &[Range], opts: &FieldOptions) -> URes Ok(()) } -fn cut_files(mut filenames: Vec, mode: Mode) -> UResult<()> { +fn cut_files(mut filenames: Vec, mode: &Mode) -> UResult<()> { let mut stdin_read = false; if filenames.is_empty() { @@ -527,7 +527,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .collect(); match mode_parse { - Ok(mode) => cut_files(files, mode), + Ok(mode) => cut_files(files, &mode), Err(e) => Err(USimpleError::new(1, e)), } } diff --git a/src/uu/cut/src/searcher.rs b/src/uu/cut/src/searcher.rs index 5fe4a723b..d8a040451 100644 --- a/src/uu/cut/src/searcher.rs +++ b/src/uu/cut/src/searcher.rs @@ -72,7 +72,7 @@ mod tests { assert_eq!(vec![] as Vec, items); } - fn test_multibyte(line: &[u8], expected: Vec) { + fn test_multibyte(line: &[u8], expected: &[usize]) { let iter = Searcher::new(line, NEEDLE); let items: Vec = iter.collect(); assert_eq!(expected, items); @@ -80,26 +80,26 @@ mod tests { #[test] fn test_multibyte_normal() { - test_multibyte("...ab...ab...".as_bytes(), vec![3, 8]); + test_multibyte("...ab...ab...".as_bytes(), &[3, 8]); } #[test] fn test_multibyte_needle_head_at_end() { - test_multibyte("a".as_bytes(), vec![]); + test_multibyte("a".as_bytes(), &[]); } #[test] fn test_multibyte_starting_needle() { - test_multibyte("ab...ab...".as_bytes(), vec![0, 5]); + test_multibyte("ab...ab...".as_bytes(), &[0, 5]); } #[test] fn test_multibyte_trailing_needle() { - test_multibyte("...ab...ab".as_bytes(), vec![3, 8]); + test_multibyte("...ab...ab".as_bytes(), &[3, 8]); } #[test] fn test_multibyte_first_byte_false_match() { - test_multibyte("aA..aCaC..ab..aD".as_bytes(), vec![10]); + test_multibyte("aA..aCaC..ab..aD".as_bytes(), &[10]); } } diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 29fe0dccf..a62ef34d2 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -322,7 +322,7 @@ impl Output where Self: OutputTrait, { - fn write_blocks(&mut self, buf: Vec) -> io::Result { + fn write_blocks(&mut self, buf: &[u8]) -> io::Result { let mut writes_complete = 0; let mut writes_partial = 0; let mut bytes_total = 0; @@ -381,7 +381,7 @@ where ) => break, (rstat_update, buf) => { let wstat_update = self - .write_blocks(buf) + .write_blocks(&buf) .map_err_context(|| "failed to write output".to_string())?; rstat += rstat_update; @@ -560,7 +560,7 @@ impl Write for Output { /// Splits the content of buf into cbs-length blocks /// Appends padding as specified by conv=block and cbs=N /// Expects ascii encoded data -fn block(buf: Vec, cbs: usize, rstat: &mut ReadStat) -> Vec> { +fn block(buf: &[u8], cbs: usize, rstat: &mut ReadStat) -> Vec> { let mut blocks = buf .split(|&e| e == NEWLINE) .map(|split| split.to_vec()) @@ -586,7 +586,7 @@ fn block(buf: Vec, cbs: usize, rstat: &mut ReadStat) -> Vec> { /// Trims padding from each cbs-length partition of buf /// as specified by conv=unblock and cbs=N /// Expects ascii encoded data -fn unblock(buf: Vec, cbs: usize) -> Vec { +fn unblock(buf: &[u8], cbs: usize) -> Vec { buf.chunks(cbs).fold(Vec::new(), |mut acc, block| { if let Some(last_char_idx) = block.iter().rposition(|&e| e != SPACE) { // Include text up to last space. @@ -643,7 +643,7 @@ fn conv_block_unblock_helper( // ascii input so perform the block first let cbs = i.cflags.block.unwrap(); - let mut blocks = block(buf, cbs, rstat); + let mut blocks = block(&buf, cbs, rstat); if let Some(ct) = i.cflags.ctable { for buf in blocks.iter_mut() { @@ -662,14 +662,14 @@ fn conv_block_unblock_helper( apply_conversion(&mut buf, ct); } - let blocks = block(buf, cbs, rstat).into_iter().flatten().collect(); + let blocks = block(&buf, cbs, rstat).into_iter().flatten().collect(); Ok(blocks) } else if should_unblock_then_conv(i) { // ascii input so perform the unblock first let cbs = i.cflags.unblock.unwrap(); - let mut buf = unblock(buf, cbs); + let mut buf = unblock(&buf, cbs); if let Some(ct) = i.cflags.ctable { apply_conversion(&mut buf, ct); @@ -684,7 +684,7 @@ fn conv_block_unblock_helper( apply_conversion(&mut buf, ct); } - let buf = unblock(buf, cbs); + let buf = unblock(&buf, cbs); Ok(buf) } else { diff --git a/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs b/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs index e2cfa77d0..919ddbb9c 100644 --- a/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs +++ b/src/uu/dd/src/dd_unit_tests/block_unblock_tests.rs @@ -63,8 +63,8 @@ macro_rules! make_unblock_test ( #[test] fn block_test_no_nl() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8]; - let res = block(buf, 4, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8]; + let res = block(&buf, 4, &mut rs); assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]); } @@ -72,8 +72,8 @@ fn block_test_no_nl() { #[test] fn block_test_no_nl_short_record() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8]; - let res = block(buf, 8, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8]; + let res = block(&buf, 8, &mut rs); assert_eq!( res, @@ -84,8 +84,8 @@ fn block_test_no_nl_short_record() { #[test] fn block_test_no_nl_trunc() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8]; - let res = block(buf, 4, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8, 4u8]; + let res = block(&buf, 4, &mut rs); // Commented section(s) should be truncated and appear for reference only. assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8 /*, 4u8*/],]); @@ -95,10 +95,10 @@ fn block_test_no_nl_trunc() { #[test] fn block_test_nl_gt_cbs_trunc() { let mut rs = ReadStat::default(); - let buf = vec![ + let buf = [ 0u8, 1u8, 2u8, 3u8, 4u8, NEWLINE, 0u8, 1u8, 2u8, 3u8, 4u8, NEWLINE, 5u8, 6u8, 7u8, 8u8, ]; - let res = block(buf, 4, &mut rs); + let res = block(&buf, 4, &mut rs); assert_eq!( res, @@ -117,8 +117,8 @@ fn block_test_nl_gt_cbs_trunc() { #[test] fn block_test_surrounded_nl() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8]; - let res = block(buf, 8, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8]; + let res = block(&buf, 8, &mut rs); assert_eq!( res, @@ -132,10 +132,10 @@ fn block_test_surrounded_nl() { #[test] fn block_test_multiple_nl_same_cbs_block() { let mut rs = ReadStat::default(); - let buf = vec![ + let buf = [ 0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, NEWLINE, 5u8, 6u8, 7u8, 8u8, 9u8, ]; - let res = block(buf, 8, &mut rs); + let res = block(&buf, 8, &mut rs); assert_eq!( res, @@ -150,10 +150,10 @@ fn block_test_multiple_nl_same_cbs_block() { #[test] fn block_test_multiple_nl_diff_cbs_block() { let mut rs = ReadStat::default(); - let buf = vec![ + let buf = [ 0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, NEWLINE, 8u8, 9u8, ]; - let res = block(buf, 8, &mut rs); + let res = block(&buf, 8, &mut rs); assert_eq!( res, @@ -168,8 +168,8 @@ fn block_test_multiple_nl_diff_cbs_block() { #[test] fn block_test_end_nl_diff_cbs_block() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE]; - let res = block(buf, 4, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE]; + let res = block(&buf, 4, &mut rs); assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]); } @@ -177,8 +177,8 @@ fn block_test_end_nl_diff_cbs_block() { #[test] fn block_test_end_nl_same_cbs_block() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, NEWLINE]; - let res = block(buf, 4, &mut rs); + let buf = [0u8, 1u8, 2u8, NEWLINE]; + let res = block(&buf, 4, &mut rs); assert_eq!(res, vec![vec![0u8, 1u8, 2u8, SPACE]]); } @@ -186,8 +186,8 @@ fn block_test_end_nl_same_cbs_block() { #[test] fn block_test_double_end_nl() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, NEWLINE, NEWLINE]; - let res = block(buf, 4, &mut rs); + let buf = [0u8, 1u8, 2u8, NEWLINE, NEWLINE]; + let res = block(&buf, 4, &mut rs); assert_eq!( res, @@ -198,8 +198,8 @@ fn block_test_double_end_nl() { #[test] fn block_test_start_nl() { let mut rs = ReadStat::default(); - let buf = vec![NEWLINE, 0u8, 1u8, 2u8, 3u8]; - let res = block(buf, 4, &mut rs); + let buf = [NEWLINE, 0u8, 1u8, 2u8, 3u8]; + let res = block(&buf, 4, &mut rs); assert_eq!( res, @@ -210,8 +210,8 @@ fn block_test_start_nl() { #[test] fn block_test_double_surrounded_nl_no_trunc() { let mut rs = ReadStat::default(); - let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8]; - let res = block(buf, 8, &mut rs); + let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8]; + let res = block(&buf, 8, &mut rs); assert_eq!( res, @@ -226,10 +226,10 @@ fn block_test_double_surrounded_nl_no_trunc() { #[test] fn block_test_double_surrounded_nl_double_trunc() { let mut rs = ReadStat::default(); - let buf = vec![ + let buf = [ 0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8, ]; - let res = block(buf, 4, &mut rs); + let res = block(&buf, 4, &mut rs); assert_eq!( res, @@ -272,24 +272,24 @@ make_block_test!( #[test] fn unblock_test_full_cbs() { - let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8]; - let res = unblock(buf, 8); + let buf = [0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8]; + let res = unblock(&buf, 8); assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, NEWLINE],); } #[test] fn unblock_test_all_space() { - let buf = vec![SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE]; - let res = unblock(buf, 8); + let buf = [SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE]; + let res = unblock(&buf, 8); assert_eq!(res, vec![NEWLINE],); } #[test] fn unblock_test_decoy_spaces() { - let buf = vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8]; - let res = unblock(buf, 8); + let buf = [0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8]; + let res = unblock(&buf, 8); assert_eq!( res, @@ -299,8 +299,8 @@ fn unblock_test_decoy_spaces() { #[test] fn unblock_test_strip_single_cbs() { - let buf = vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE]; - let res = unblock(buf, 8); + let buf = [0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE]; + let res = unblock(&buf, 8); assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, NEWLINE],); } @@ -317,7 +317,7 @@ fn unblock_test_strip_multi_cbs() { .flatten() .collect::>(); - let res = unblock(buf, 8); + let res = unblock(&buf, 8); let exp = vec![ vec![0u8, NEWLINE], diff --git a/src/uu/dircolors/src/dircolors.rs b/src/uu/dircolors/src/dircolors.rs index b0e81f817..2fee24e5b 100644 --- a/src/uu/dircolors/src/dircolors.rs +++ b/src/uu/dircolors/src/dircolors.rs @@ -127,7 +127,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let result; if files.is_empty() { - result = parse(INTERNAL_DB.lines(), out_format, "") + result = parse(INTERNAL_DB.lines(), &out_format, "") } else { if files.len() > 1 { return Err(UUsageError::new( @@ -138,7 +138,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match File::open(files[0]) { Ok(f) => { let fin = BufReader::new(f); - result = parse(fin.lines().filter_map(Result::ok), out_format, files[0]) + result = parse(fin.lines().filter_map(Result::ok), &out_format, files[0]) } Err(e) => { return Err(USimpleError::new( @@ -259,7 +259,7 @@ enum ParseState { use std::collections::HashMap; use uucore::InvalidEncodingHandling; -fn parse(lines: T, fmt: OutputFmt, fp: &str) -> Result +fn parse(lines: T, fmt: &OutputFmt, fp: &str) -> Result where T: IntoIterator, T::Item: Borrow, diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index d92ead173..71d335b1e 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -247,7 +247,7 @@ fn get_file_info(path: &Path) -> Option { fn read_block_size(s: Option<&str>) -> usize { if let Some(s) = s { parse_size(s) - .unwrap_or_else(|e| crash!(1, "{}", format_error_message(e, s, options::BLOCK_SIZE))) + .unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::BLOCK_SIZE))) } else { for env_var in &["DU_BLOCK_SIZE", "BLOCK_SIZE", "BLOCKSIZE"] { if let Ok(env_size) = env::var(env_var) { @@ -493,7 +493,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let threshold = matches.value_of(options::THRESHOLD).map(|s| { Threshold::from_str(s) - .unwrap_or_else(|e| crash!(1, "{}", format_error_message(e, s, options::THRESHOLD))) + .unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::THRESHOLD))) }); let multiplier: u64 = if matches.is_present(options::SI) { @@ -831,7 +831,7 @@ impl Threshold { } } -fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String { +fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String { // NOTE: // GNU's du echos affected flag, -B or --block-size (-t or --threshold), depending user's selection // GNU's du does distinguish between "invalid (suffix in) argument" diff --git a/src/uu/echo/src/echo.rs b/src/uu/echo/src/echo.rs index db2744804..35606be71 100644 --- a/src/uu/echo/src/echo.rs +++ b/src/uu/echo/src/echo.rs @@ -125,7 +125,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { None => vec!["".to_string()], }; - execute(no_newline, escaped, values).map_err_context(|| "could not write to stdout".to_string()) + execute(no_newline, escaped, &values) + .map_err_context(|| "could not write to stdout".to_string()) } pub fn uu_app<'a>() -> App<'a> { @@ -162,7 +163,7 @@ pub fn uu_app<'a>() -> App<'a> { .arg(Arg::new(options::STRING).multiple_occurrences(true)) } -fn execute(no_newline: bool, escaped: bool, free: Vec) -> io::Result<()> { +fn execute(no_newline: bool, escaped: bool, free: &[String]) -> io::Result<()> { let stdout = io::stdout(); let mut output = stdout.lock(); diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 81ebb1269..429bc1cc7 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -67,7 +67,7 @@ fn is_space_or_comma(c: char) -> bool { /// in the list. This mode defines the strategy to use for computing the /// number of spaces to use for columns beyond the end of the tab stop /// list specified here. -fn tabstops_parse(s: String) -> (RemainingMode, Vec) { +fn tabstops_parse(s: &str) -> (RemainingMode, Vec) { // Leading commas and spaces are ignored. let s = s.trim_start_matches(is_space_or_comma); @@ -135,7 +135,7 @@ struct Options { impl Options { fn new(matches: &ArgMatches) -> Options { let (remaining_mode, tabstops) = match matches.value_of(options::TABS) { - Some(s) => tabstops_parse(s.to_string()), + Some(s) => tabstops_parse(s), None => (RemainingMode::None, vec![DEFAULT_TABSTOP]), }; @@ -176,7 +176,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let usage = usage(); let matches = uu_app().override_usage(&usage[..]).get_matches_from(args); - expand(Options::new(&matches)).map_err_context(|| "failed to write output".to_string()) + expand(&Options::new(&matches)).map_err_context(|| "failed to write output".to_string()) } pub fn uu_app<'a>() -> App<'a> { @@ -212,12 +212,12 @@ pub fn uu_app<'a>() -> App<'a> { ) } -fn open(path: String) -> BufReader> { +fn open(path: &str) -> BufReader> { let file_buf; if path == "-" { BufReader::new(Box::new(stdin()) as Box) } else { - file_buf = match File::open(&path[..]) { + file_buf = match File::open(path) { Ok(a) => a, Err(e) => crash!(1, "{}: {}\n", path.maybe_quote(), e), }; @@ -271,14 +271,14 @@ enum CharType { Other, } -fn expand(options: Options) -> std::io::Result<()> { +fn expand(options: &Options) -> std::io::Result<()> { use self::CharType::*; let mut output = BufWriter::new(stdout()); let ts = options.tabstops.as_ref(); let mut buf = Vec::new(); - for file in options.files.into_iter() { + for file in options.files.iter() { let mut fh = open(file); while match fh.read_until(b'\n', &mut buf) { diff --git a/src/uu/fold/src/fold.rs b/src/uu/fold/src/fold.rs index 0fcaf30b8..667de122e 100644 --- a/src/uu/fold/src/fold.rs +++ b/src/uu/fold/src/fold.rs @@ -60,7 +60,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { None => vec!["-".to_owned()], }; - fold(files, bytes, spaces, width) + fold(&files, bytes, spaces, width) } pub fn uu_app<'a>() -> App<'a> { @@ -115,8 +115,8 @@ fn handle_obsolete(args: &[String]) -> (Vec, Option) { (args.to_vec(), None) } -fn fold(filenames: Vec, bytes: bool, spaces: bool, width: usize) -> UResult<()> { - for filename in &filenames { +fn fold(filenames: &[String], bytes: bool, spaces: bool, width: usize) -> UResult<()> { + for filename in filenames { let filename: &str = filename; let mut stdin_buf; let mut file_buf; diff --git a/src/uu/id/src/id.rs b/src/uu/id/src/id.rs index 293be0b49..b8132e688 100644 --- a/src/uu/id/src/id.rs +++ b/src/uu/id/src/id.rs @@ -335,7 +335,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } if default_format { - id_print(&mut state, groups); + id_print(&mut state, &groups); } print!("{}", line_ending); @@ -556,7 +556,7 @@ fn auditid() { println!("asid={}", auditinfo.ai_asid); } -fn id_print(state: &mut State, groups: Vec) { +fn id_print(state: &mut State, groups: &[u32]) { let uid = state.ids.as_ref().unwrap().uid; let gid = state.ids.as_ref().unwrap().gid; let euid = state.ids.as_ref().unwrap().euid; diff --git a/src/uu/install/src/install.rs b/src/uu/install/src/install.rs index 9aca5fb64..31e6d374c 100644 --- a/src/uu/install/src/install.rs +++ b/src/uu/install/src/install.rs @@ -187,8 +187,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let behavior = behavior(&matches)?; match behavior.main_function { - MainFunction::Directory => directory(paths, behavior), - MainFunction::Standard => standard(paths, behavior), + MainFunction::Directory => directory(&paths, &behavior), + MainFunction::Standard => standard(paths, &behavior), } } @@ -391,7 +391,7 @@ fn behavior(matches: &ArgMatches) -> UResult { /// /// Returns a Result type with the Err variant containing the error message. /// -fn directory(paths: Vec, b: Behavior) -> UResult<()> { +fn directory(paths: &[String], b: &Behavior) -> UResult<()> { if paths.is_empty() { Err(InstallError::DirNeedsArg().into()) } else { @@ -444,7 +444,7 @@ fn is_new_file_path(path: &Path) -> bool { /// /// Returns a Result type with the Err variant containing the error message. /// -fn standard(mut paths: Vec, b: Behavior) -> UResult<()> { +fn standard(mut paths: Vec, b: &Behavior) -> UResult<()> { let target: PathBuf = b .target_dir .clone() @@ -454,7 +454,7 @@ fn standard(mut paths: Vec, b: Behavior) -> UResult<()> { let sources = &paths.iter().map(PathBuf::from).collect::>(); if sources.len() > 1 || (target.exists() && target.is_dir()) { - copy_files_into_dir(sources, &target, &b) + copy_files_into_dir(sources, &target, b) } else { if let Some(parent) = target.parent() { if !parent.exists() && b.create_leading { @@ -471,7 +471,7 @@ fn standard(mut paths: Vec, b: Behavior) -> UResult<()> { } if target.is_file() || is_new_file_path(&target) { - copy(&sources[0], &target, &b) + copy(&sources[0], &target, b) } else { Err(InstallError::InvalidTarget(target).into()) } diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index d7bbdae9d..0b5bcbb23 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -710,7 +710,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .map(|v| v.map(Path::new).collect()) .unwrap_or_else(|| vec![Path::new(".")]); - list(locs, config) + list(locs, &config) } pub fn uu_app<'a>() -> App<'a> { @@ -1407,14 +1407,14 @@ impl PathData { } } -fn list(locs: Vec<&Path>, config: Config) -> UResult<()> { +fn list(locs: Vec<&Path>, config: &Config) -> UResult<()> { let mut files = Vec::::new(); let mut dirs = Vec::::new(); let mut out = BufWriter::new(stdout()); let initial_locs_len = locs.len(); for loc in locs { - let path_data = PathData::new(PathBuf::from(loc), None, None, &config, true); + let path_data = PathData::new(PathBuf::from(loc), None, None, config, true); // Getting metadata here is no big deal as it's just the CWD // and we really just want to know if the strings exist as files/dirs @@ -1441,10 +1441,10 @@ fn list(locs: Vec<&Path>, config: Config) -> UResult<()> { } } - sort_entries(&mut files, &config, &mut out); - sort_entries(&mut dirs, &config, &mut out); + sort_entries(&mut files, config, &mut out); + sort_entries(&mut dirs, config, &mut out); - display_items(&files, &config, &mut out); + display_items(&files, config, &mut out); for (pos, path_data) in dirs.iter().enumerate() { // Do read_dir call here to match GNU semantics by printing @@ -1467,7 +1467,7 @@ fn list(locs: Vec<&Path>, config: Config) -> UResult<()> { let _ = writeln!(out, "\n{}:", path_data.p_buf.display()); } } - enter_directory(path_data, read_dir, &config, &mut out); + enter_directory(path_data, read_dir, config, &mut out); } Ok(()) @@ -1749,7 +1749,7 @@ fn display_items(items: &[PathData], config: &Config, out: &mut BufWriter, ) { @@ -2251,7 +2251,7 @@ fn display_date(metadata: &Metadata, config: &Config) -> String { // 3. The human-readable format uses powers for 1024, but does not display the "i" // that is commonly used to denote Kibi, Mebi, etc. // 4. Kibi and Kilo are denoted differently ("k" and "K", respectively) -fn format_prefixed(prefixed: NumberPrefix) -> String { +fn format_prefixed(prefixed: &NumberPrefix) -> String { match prefixed { NumberPrefix::Standalone(bytes) => bytes.to_string(), NumberPrefix::Prefixed(prefix, bytes) => { @@ -2304,8 +2304,8 @@ fn display_size(size: u64, config: &Config) -> String { // NOTE: The human-readable behavior deviates from the GNU ls. // The GNU ls uses binary prefixes by default. match config.size_format { - SizeFormat::Binary => format_prefixed(NumberPrefix::binary(size as f64)), - SizeFormat::Decimal => format_prefixed(NumberPrefix::decimal(size as f64)), + SizeFormat::Binary => format_prefixed(&NumberPrefix::binary(size as f64)), + SizeFormat::Decimal => format_prefixed(&NumberPrefix::decimal(size as f64)), SizeFormat::Bytes => size.to_string(), } } diff --git a/src/uu/ls/src/quoting_style.rs b/src/uu/ls/src/quoting_style.rs index 149733cf9..c7c64cc6c 100644 --- a/src/uu/ls/src/quoting_style.rs +++ b/src/uu/ls/src/quoting_style.rs @@ -363,7 +363,7 @@ mod tests { } } - fn check_names(name: &str, map: Vec<(&str, &str)>) { + fn check_names(name: &str, map: &[(&str, &str)]) { assert_eq!( map.iter() .map(|(_, style)| escape_name(name.as_ref(), &get_style(style))) @@ -378,7 +378,7 @@ mod tests { fn test_simple_names() { check_names( "one_two", - vec![ + &[ ("one_two", "literal"), ("one_two", "literal-show"), ("one_two", "escape"), @@ -397,7 +397,7 @@ mod tests { fn test_spaces() { check_names( "one two", - vec![ + &[ ("one two", "literal"), ("one two", "literal-show"), ("one\\ two", "escape"), @@ -413,7 +413,7 @@ mod tests { check_names( " one", - vec![ + &[ (" one", "literal"), (" one", "literal-show"), ("\\ one", "escape"), @@ -433,7 +433,7 @@ mod tests { // One double quote check_names( "one\"two", - vec![ + &[ ("one\"two", "literal"), ("one\"two", "literal-show"), ("one\"two", "escape"), @@ -450,7 +450,7 @@ mod tests { // One single quote check_names( "one\'two", - vec![ + &[ ("one'two", "literal"), ("one'two", "literal-show"), ("one'two", "escape"), @@ -467,7 +467,7 @@ mod tests { // One single quote and one double quote check_names( "one'two\"three", - vec![ + &[ ("one'two\"three", "literal"), ("one'two\"three", "literal-show"), ("one'two\"three", "escape"), @@ -484,7 +484,7 @@ mod tests { // Consecutive quotes check_names( "one''two\"\"three", - vec![ + &[ ("one''two\"\"three", "literal"), ("one''two\"\"three", "literal-show"), ("one''two\"\"three", "escape"), @@ -504,7 +504,7 @@ mod tests { // A simple newline check_names( "one\ntwo", - vec![ + &[ ("one?two", "literal"), ("one\ntwo", "literal-show"), ("one\\ntwo", "escape"), @@ -521,7 +521,7 @@ mod tests { // A control character followed by a special shell character check_names( "one\n&two", - vec![ + &[ ("one?&two", "literal"), ("one\n&two", "literal-show"), ("one\\n&two", "escape"), @@ -539,7 +539,7 @@ mod tests { // no importance for file names. check_names( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F", - vec![ + &[ ("????????????????", "literal"), ( "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F", @@ -577,7 +577,7 @@ mod tests { // The last 16 control characters. check_names( "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", - vec![ + &[ ("????????????????", "literal"), ( "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F", @@ -615,7 +615,7 @@ mod tests { // DEL check_names( "\x7F", - vec![ + &[ ("?", "literal"), ("\x7F", "literal-show"), ("\\177", "escape"), @@ -637,7 +637,7 @@ mod tests { // in other tests) check_names( "one?two", - vec![ + &[ ("one?two", "literal"), ("one?two", "literal-show"), ("one?two", "escape"), @@ -657,7 +657,7 @@ mod tests { // Escaped in C-style, but not in Shell-style escaping check_names( "one\\two", - vec![ + &[ ("one\\two", "literal"), ("one\\two", "literal-show"), ("one\\\\two", "escape"), @@ -672,34 +672,34 @@ mod tests { #[test] fn test_tilde_and_hash() { - check_names("~", vec![("'~'", "shell"), ("'~'", "shell-escape")]); + check_names("~", &[("'~'", "shell"), ("'~'", "shell-escape")]); check_names( "~name", - vec![("'~name'", "shell"), ("'~name'", "shell-escape")], + &[("'~name'", "shell"), ("'~name'", "shell-escape")], ); check_names( "some~name", - vec![("some~name", "shell"), ("some~name", "shell-escape")], + &[("some~name", "shell"), ("some~name", "shell-escape")], ); - check_names("name~", vec![("name~", "shell"), ("name~", "shell-escape")]); + check_names("name~", &[("name~", "shell"), ("name~", "shell-escape")]); - check_names("#", vec![("'#'", "shell"), ("'#'", "shell-escape")]); + check_names("#", &[("'#'", "shell"), ("'#'", "shell-escape")]); check_names( "#name", - vec![("'#name'", "shell"), ("'#name'", "shell-escape")], + &[("'#name'", "shell"), ("'#name'", "shell-escape")], ); check_names( "some#name", - vec![("some#name", "shell"), ("some#name", "shell-escape")], + &[("some#name", "shell"), ("some#name", "shell-escape")], ); - check_names("name#", vec![("name#", "shell"), ("name#", "shell-escape")]); + check_names("name#", &[("name#", "shell"), ("name#", "shell-escape")]); } #[test] fn test_special_chars_in_double_quotes() { check_names( "can'$t", - vec![ + &[ ("'can'\\''$t'", "shell"), ("'can'\\''$t'", "shell-always"), ("'can'\\''$t'", "shell-escape"), @@ -709,7 +709,7 @@ mod tests { check_names( "can'`t", - vec![ + &[ ("'can'\\''`t'", "shell"), ("'can'\\''`t'", "shell-always"), ("'can'\\''`t'", "shell-escape"), @@ -719,7 +719,7 @@ mod tests { check_names( "can'\\t", - vec![ + &[ ("'can'\\''\\t'", "shell"), ("'can'\\''\\t'", "shell-always"), ("'can'\\''\\t'", "shell-escape"), diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index e0679a3e4..83a567c4b 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -16,7 +16,7 @@ use std::env; use std::error::Error; use std::fmt::Display; use std::iter; -use std::path::{is_separator, PathBuf}; +use std::path::{is_separator, Path, PathBuf}; use rand::Rng; use tempfile::Builder; @@ -124,7 +124,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let res = if dry_run { dry_exec(tmpdir, prefix, rand, suffix) } else { - exec(tmpdir, prefix, rand, suffix, make_dir) + exec(&tmpdir, prefix, rand, suffix, make_dir) }; if suppress_file_err { @@ -249,7 +249,7 @@ pub fn dry_exec(mut tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str) -> println_verbatim(tmpdir).map_err_context(|| "failed to print directory name".to_owned()) } -fn exec(dir: PathBuf, prefix: &str, rand: usize, suffix: &str, make_dir: bool) -> UResult<()> { +fn exec(dir: &Path, prefix: &str, rand: usize, suffix: &str, make_dir: bool) -> UResult<()> { let context = || { format!( "failed to create file via template '{}{}{}'", diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index be305d82c..9c672782b 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -116,7 +116,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { strip_slashes: matches.is_present(OPT_STRIP_TRAILING_SLASHES), }; - exec(&files[..], behavior) + exec(&files[..], &behavior) } pub fn uu_app<'a>() -> App<'a> { @@ -207,7 +207,7 @@ fn determine_overwrite_mode(matches: &ArgMatches) -> OverwriteMode { } } -fn exec(files: &[OsString], b: Behavior) -> UResult<()> { +fn exec(files: &[OsString], b: &Behavior) -> UResult<()> { let paths: Vec = { let paths = files.iter().map(Path::new); @@ -222,7 +222,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> { }; if let Some(ref name) = b.target_dir { - return move_files_into_dir(&paths, &PathBuf::from(name), &b); + return move_files_into_dir(&paths, &PathBuf::from(name), b); } match paths.len() { /* case 0/1 are not possible thanks to clap */ @@ -256,12 +256,12 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> { if !source.is_dir() { Err(MvError::DirectoryToNonDirectory(target.quote().to_string()).into()) } else { - rename(source, target, &b).map_err_context(|| { + rename(source, target, b).map_err_context(|| { format!("cannot move {} to {}", source.quote(), target.quote()) }) } } else { - move_files_into_dir(&[source.clone()], target, &b) + move_files_into_dir(&[source.clone()], target, b) } } else if target.exists() && source.is_dir() { Err(MvError::NonDirectoryToDirectory( @@ -270,7 +270,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> { ) .into()) } else { - rename(source, target, &b).map_err(|e| USimpleError::new(1, format!("{}", e))) + rename(source, target, b).map_err(|e| USimpleError::new(1, format!("{}", e))) } } _ => { @@ -281,7 +281,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> { )); } let target_dir = paths.last().unwrap(); - move_files_into_dir(&paths[..paths.len() - 1], target_dir, &b) + move_files_into_dir(&paths[..paths.len() - 1], target_dir, b) } } } diff --git a/src/uu/numfmt/src/numfmt.rs b/src/uu/numfmt/src/numfmt.rs index 189bc945c..c2b956fa3 100644 --- a/src/uu/numfmt/src/numfmt.rs +++ b/src/uu/numfmt/src/numfmt.rs @@ -55,9 +55,9 @@ fn usage() -> String { format!("{0} [OPTION]... [NUMBER]...", uucore::execution_phrase()) } -fn handle_args<'a>(args: impl Iterator, options: NumfmtOptions) -> UResult<()> { +fn handle_args<'a>(args: impl Iterator, options: &NumfmtOptions) -> UResult<()> { for l in args { - match format_and_print(l, &options) { + match format_and_print(l, options) { Ok(_) => Ok(()), Err(e) => Err(NumfmtError::FormattingError(e.to_string())), }?; @@ -66,7 +66,7 @@ fn handle_args<'a>(args: impl Iterator, options: NumfmtOptions) Ok(()) } -fn handle_buffer(input: R, options: NumfmtOptions) -> UResult<()> +fn handle_buffer(input: R, options: &NumfmtOptions) -> UResult<()> where R: BufRead, { @@ -77,7 +77,7 @@ where println!("{}", l); Ok(()) } - Ok(l) => match format_and_print(&l, &options) { + Ok(l) => match format_and_print(&l, options) { Ok(_) => Ok(()), Err(e) => Err(NumfmtError::FormattingError(e.to_string())), }, @@ -173,11 +173,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let options = parse_options(&matches).map_err(NumfmtError::IllegalArgument)?; let result = match matches.values_of(options::NUMBER) { - Some(values) => handle_args(values, options), + Some(values) => handle_args(values, &options), None => { let stdin = std::io::stdin(); let mut locked_stdin = stdin.lock(); - handle_buffer(&mut locked_stdin, options) + handle_buffer(&mut locked_stdin, &options) } }; @@ -304,7 +304,7 @@ mod tests { #[test] fn broken_buffer_returns_io_error() { let mock_buffer = MockBuffer {}; - let result = handle_buffer(BufReader::new(mock_buffer), get_valid_options()) + let result = handle_buffer(BufReader::new(mock_buffer), &get_valid_options()) .expect_err("returned Ok after receiving IO error"); let result_debug = format!("{:?}", result); let result_display = format!("{}", result); @@ -316,7 +316,7 @@ mod tests { #[test] fn non_numeric_returns_formatting_error() { let input_value = b"135\nhello"; - let result = handle_buffer(BufReader::new(&input_value[..]), get_valid_options()) + let result = handle_buffer(BufReader::new(&input_value[..]), &get_valid_options()) .expect_err("returned Ok after receiving improperly formatted input"); let result_debug = format!("{:?}", result); let result_display = format!("{}", result); @@ -331,7 +331,7 @@ mod tests { #[test] fn valid_input_returns_ok() { let input_value = b"165\n100\n300\n500"; - let result = handle_buffer(BufReader::new(&input_value[..]), get_valid_options()); + let result = handle_buffer(BufReader::new(&input_value[..]), &get_valid_options()); assert!(result.is_ok(), "did not return Ok for valid input"); } } diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index ad3fad5e9..d1be3dfc7 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -121,7 +121,7 @@ struct OdOptions { } impl OdOptions { - fn new(matches: ArgMatches, args: Vec) -> UResult { + fn new(matches: &ArgMatches, args: &[String]) -> UResult { let byte_order = match matches.value_of(options::ENDIAN) { None => ByteOrder::Native, Some("little") => ByteOrder::Little, @@ -141,7 +141,7 @@ impl OdOptions { Err(e) => { return Err(USimpleError::new( 1, - format_error_message(e, s, options::SKIP_BYTES), + format_error_message(&e, s, options::SKIP_BYTES), )) } }, @@ -149,7 +149,7 @@ impl OdOptions { let mut label: Option = None; - let parsed_input = parse_inputs(&matches) + let parsed_input = parse_inputs(matches) .map_err(|e| USimpleError::new(1, format!("Invalid inputs: {}", e)))?; let input_strings = match parsed_input { CommandLineInputs::FileNames(v) => v, @@ -160,7 +160,7 @@ impl OdOptions { } }; - let formats = parse_format_flags(&args).map_err(|e| USimpleError::new(1, e))?; + let formats = parse_format_flags(args).map_err(|e| USimpleError::new(1, e))?; let mut line_bytes = match matches.value_of(options::WIDTH) { None => 16, @@ -173,7 +173,7 @@ impl OdOptions { Err(e) => { return Err(USimpleError::new( 1, - format_error_message(e, s, options::WIDTH), + format_error_message(&e, s, options::WIDTH), )) } } @@ -198,7 +198,7 @@ impl OdOptions { Err(e) => { return Err(USimpleError::new( 1, - format_error_message(e, s, options::READ_BYTES), + format_error_message(&e, s, options::READ_BYTES), )) } }, @@ -260,7 +260,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .clone() // Clone to reuse clap_opts to print help .get_matches_from(args.clone()); - let od_options = OdOptions::new(clap_matches, args)?; + let od_options = OdOptions::new(&clap_matches, &args)?; let mut input_offset = InputOffset::new(od_options.radix, od_options.skip_bytes, od_options.label); @@ -664,7 +664,7 @@ fn open_input_peek_reader( PeekReader::new(pr) } -fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String { +fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String { // NOTE: // GNU's od echos affected flag, -N or --read-bytes (-j or --skip-bytes, etc.), depending user's selection // GNU's od does distinguish between "invalid (suffix in) argument" diff --git a/src/uu/od/src/parse_inputs.rs b/src/uu/od/src/parse_inputs.rs index a5634c0aa..9d64fc732 100644 --- a/src/uu/od/src/parse_inputs.rs +++ b/src/uu/od/src/parse_inputs.rs @@ -46,7 +46,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result @@ -91,7 +91,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result) -> Result { +pub fn parse_inputs_traditional(input_strings: &[&str]) -> Result { match input_strings.len() { 0 => Ok(CommandLineInputs::FileNames(vec!["-".to_string()])), 1 => { diff --git a/src/uu/paste/src/paste.rs b/src/uu/paste/src/paste.rs index 4bf2a4417..0792da458 100644 --- a/src/uu/paste/src/paste.rs +++ b/src/uu/paste/src/paste.rs @@ -39,7 +39,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); let serial = matches.is_present(options::SERIAL); - let delimiters = matches.value_of(options::DELIMITER).unwrap().to_owned(); + let delimiters = matches.value_of(options::DELIMITER).unwrap(); let files = matches .values_of(options::FILE) .unwrap() @@ -76,7 +76,7 @@ pub fn uu_app<'a>() -> App<'a> { ) } -fn paste(filenames: Vec, serial: bool, delimiters: String) -> UResult<()> { +fn paste(filenames: Vec, serial: bool, delimiters: &str) -> UResult<()> { let mut files = vec![]; for name in filenames { let file = if name == "-" { @@ -146,7 +146,7 @@ fn paste(filenames: Vec, serial: bool, delimiters: String) -> UResult<() // Unescape all special characters // TODO: this will need work to conform to GNU implementation -fn unescape(s: String) -> String { +fn unescape(s: &str) -> String { s.replace("\\n", "\n") .replace("\\t", "\t") .replace("\\\\", "\\") diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 601851ed8..561998b36 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -409,11 +409,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { }; for file_group in file_groups { - let result_options = build_options(&matches, &file_group, args.join(" ")); + let result_options = build_options(&matches, &file_group, &args.join(" ")); let options = match result_options { Ok(options) => options, Err(err) => { - print_error(&matches, err); + print_error(&matches, &err); return Err(1.into()); } }; @@ -426,7 +426,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let status = match cmd_result { Err(error) => { - print_error(&matches, error); + print_error(&matches, &error); 1 } _ => 0, @@ -465,7 +465,7 @@ fn recreate_arguments(args: &[String]) -> Vec { .collect() } -fn print_error(matches: &Matches, err: PrError) { +fn print_error(matches: &Matches, err: &PrError) { if !matches.opt_present(options::SUPPRESS_PRINTING_ERROR) { eprintln!("{}", err); } @@ -531,7 +531,7 @@ fn parse_usize(matches: &Matches, opt: &str) -> Option> { fn build_options( matches: &Matches, paths: &[String], - free_args: String, + free_args: &str, ) -> Result { let form_feed_used = matches.opt_present(options::FORM_FEED_OPTION) || matches.opt_present(options::FORM_FEED_OPTION_SMALL); @@ -617,7 +617,7 @@ fn build_options( // +page option is less priority than --pages let page_plus_re = Regex::new(r"\s*\+(\d+:*\d*)\s*").unwrap(); - let start_page_in_plus_option = match page_plus_re.captures(&free_args).map(|i| { + let start_page_in_plus_option = match page_plus_re.captures(free_args).map(|i| { let unparsed_num = i.get(1).unwrap().as_str().trim(); let x: Vec<_> = unparsed_num.split(':').collect(); x[0].to_string().parse::().map_err(|_e| { @@ -629,7 +629,7 @@ fn build_options( }; let end_page_in_plus_option = match page_plus_re - .captures(&free_args) + .captures(free_args) .map(|i| i.get(1).unwrap().as_str().trim()) .filter(|i| i.contains(':')) .map(|unparsed_num| { @@ -747,7 +747,7 @@ fn build_options( let re_col = Regex::new(r"\s*-(\d+)\s*").unwrap(); - let start_column_option = match re_col.captures(&free_args).map(|i| { + let start_column_option = match re_col.captures(free_args).map(|i| { let unparsed_num = i.get(1).unwrap().as_str().trim(); unparsed_num.parse::().map_err(|_e| { PrError::EncounteredErrors(format!("invalid {} argument {}", "-", unparsed_num.quote())) diff --git a/src/uu/rm/src/rm.rs b/src/uu/rm/src/rm.rs index cf2522b39..71351f8e0 100644 --- a/src/uu/rm/src/rm.rs +++ b/src/uu/rm/src/rm.rs @@ -138,7 +138,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } } - if remove(files, options) { + if remove(&files, &options) { return Err(1.into()); } } @@ -236,19 +236,19 @@ pub fn uu_app<'a>() -> App<'a> { } // TODO: implement one-file-system (this may get partially implemented in walkdir) -fn remove(files: Vec, options: Options) -> bool { +fn remove(files: &[String], options: &Options) -> bool { let mut had_err = false; - for filename in &files { + for filename in files { let file = Path::new(filename); had_err = match file.symlink_metadata() { Ok(metadata) => { if metadata.is_dir() { - handle_dir(file, &options) + handle_dir(file, options) } else if is_symlink_dir(&metadata) { - remove_dir(file, &options) + remove_dir(file, options) } else { - remove_file(file, &options) + remove_file(file, options) } } Err(_e) => { diff --git a/src/uu/runcon/src/runcon.rs b/src/uu/runcon/src/runcon.rs index 4b8e6e3bd..9b8cf412a 100644 --- a/src/uu/runcon/src/runcon.rs +++ b/src/uu/runcon/src/runcon.rs @@ -73,7 +73,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { CommandLineMode::Print => print_current_context().map_err(|e| RunconError::new(e).into()), CommandLineMode::PlainContext { context, command } => { get_plain_context(context) - .and_then(set_next_exec_context) + .and_then(|ctx| set_next_exec_context(&ctx)) .map_err(RunconError::new)?; // On successful execution, the following call never returns, // and this process image is replaced. @@ -97,7 +97,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { range.as_deref(), command, ) - .and_then(set_next_exec_context) + .and_then(|ctx| set_next_exec_context(&ctx)) .map_err(RunconError::new)?; // On successful execution, the following call never returns, // and this process image is replaced. @@ -277,7 +277,7 @@ fn print_current_context() -> Result<()> { Ok(()) } -fn set_next_exec_context(context: OpaqueSecurityContext) -> Result<()> { +fn set_next_exec_context(context: &OpaqueSecurityContext) -> Result<()> { let c_context = context .to_c_string() .map_err(|r| Error::from_selinux("Creating new context", r))?; diff --git a/src/uu/seq/src/seq.rs b/src/uu/seq/src/seq.rs index 7f6043398..af961a493 100644 --- a/src/uu/seq/src/seq.rs +++ b/src/uu/seq/src/seq.rs @@ -115,8 +115,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let last = last.round_towards(&first); print_seq_integers( (first, increment, last), - options.separator, - options.terminator, + &options.separator, + &options.terminator, options.widths, padding, options.format, @@ -129,8 +129,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { last.into_extended_big_decimal(), ), largest_dec, - options.separator, - options.terminator, + &options.separator, + &options.terminator, options.widths, padding, options.format, @@ -265,8 +265,8 @@ fn write_value_int( fn print_seq( range: RangeFloat, largest_dec: usize, - separator: String, - terminator: String, + separator: &str, + terminator: &str, pad: bool, padding: usize, format: Option<&str>, @@ -336,8 +336,8 @@ fn print_seq( /// numbers). Only set this to `true` if `first` is actually zero. fn print_seq_integers( range: RangeInt, - separator: String, - terminator: String, + separator: &str, + terminator: &str, pad: bool, padding: usize, format: Option<&str>, diff --git a/src/uu/sleep/src/sleep.rs b/src/uu/sleep/src/sleep.rs index fccb4be46..8545c40c9 100644 --- a/src/uu/sleep/src/sleep.rs +++ b/src/uu/sleep/src/sleep.rs @@ -38,8 +38,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().override_usage(&usage[..]).get_matches_from(args); if let Some(values) = matches.values_of(options::NUMBER) { - let numbers = values.collect(); - return sleep(numbers); + let numbers = values.collect::>(); + return sleep(&numbers); } Ok(()) @@ -61,7 +61,7 @@ pub fn uu_app<'a>() -> App<'a> { ) } -fn sleep(args: Vec<&str>) -> UResult<()> { +fn sleep(args: &[&str]) -> UResult<()> { let sleep_dur = args.iter().try_fold( Duration::new(0, 0), diff --git a/src/uu/sort/src/check.rs b/src/uu/sort/src/check.rs index 5be752be0..3f02a4c31 100644 --- a/src/uu/sort/src/check.rs +++ b/src/uu/sort/src/check.rs @@ -40,7 +40,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { let (loaded_sender, loaded_receiver) = sync_channel(2); thread::spawn({ let settings = settings.clone(); - move || reader(file, recycled_receiver, loaded_sender, &settings) + move || reader(file, &recycled_receiver, &loaded_sender, &settings) }); for _ in 0..2 { let _ = recycled_sender.send(RecycledChunk::new(if settings.buffer_size < 100 * 1024 { @@ -102,14 +102,14 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { /// The function running on the reader thread. fn reader( mut file: Box, - receiver: Receiver, - sender: SyncSender, + receiver: &Receiver, + sender: &SyncSender, settings: &GlobalSettings, ) -> UResult<()> { let mut carry_over = vec![]; for recycled_chunk in receiver.iter() { let should_continue = chunks::read( - &sender, + sender, recycled_chunk, None, &mut carry_over, diff --git a/src/uu/sort/src/ext_sort.rs b/src/uu/sort/src/ext_sort.rs index bf332e4e8..4bef20625 100644 --- a/src/uu/sort/src/ext_sort.rs +++ b/src/uu/sort/src/ext_sort.rs @@ -50,13 +50,13 @@ pub fn ext_sort( let (recycled_sender, recycled_receiver) = std::sync::mpsc::sync_channel(1); thread::spawn({ let settings = settings.clone(); - move || sorter(recycled_receiver, sorted_sender, settings) + move || sorter(&recycled_receiver, &sorted_sender, &settings) }); if settings.compress_prog.is_some() { reader_writer::<_, WriteableCompressedTmpFile>( files, settings, - sorted_receiver, + &sorted_receiver, recycled_sender, output, tmp_dir, @@ -65,7 +65,7 @@ pub fn ext_sort( reader_writer::<_, WriteablePlainTmpFile>( files, settings, - sorted_receiver, + &sorted_receiver, recycled_sender, output, tmp_dir, @@ -79,7 +79,7 @@ fn reader_writer< >( files: F, settings: &GlobalSettings, - receiver: Receiver, + receiver: &Receiver, sender: SyncSender, output: Output, tmp_dir: &mut TmpDirWrapper, @@ -156,10 +156,10 @@ fn reader_writer< } /// The function that is executed on the sorter thread. -fn sorter(receiver: Receiver, sender: SyncSender, settings: GlobalSettings) { +fn sorter(receiver: &Receiver, sender: &SyncSender, settings: &GlobalSettings) { while let Ok(mut payload) = receiver.recv() { payload.with_contents_mut(|contents| { - sort_by(&mut contents.lines, &settings, &contents.line_data) + sort_by(&mut contents.lines, settings, &contents.line_data) }); if sender.send(payload).is_err() { // The receiver has gone away, likely because the other thread hit an error. @@ -187,7 +187,7 @@ fn read_write_loop( separator: u8, buffer_size: usize, settings: &GlobalSettings, - receiver: Receiver, + receiver: &Receiver, sender: SyncSender, ) -> UResult> { let mut file = files.next().unwrap()?; diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 934d1c208..8350cdf30 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -166,7 +166,7 @@ fn merge_without_limit>>( let settings = settings.clone(); move || { reader( - request_receiver, + &request_receiver, &mut reader_files, &settings, if settings.zero_terminated { @@ -210,7 +210,7 @@ struct ReaderFile { /// The function running on the reader thread. fn reader( - recycled_receiver: Receiver<(usize, RecycledChunk)>, + recycled_receiver: &Receiver<(usize, RecycledChunk)>, files: &mut [Option>], settings: &GlobalSettings, separator: u8, diff --git a/src/uu/sort/src/numeric_str_cmp.rs b/src/uu/sort/src/numeric_str_cmp.rs index d753c2d9d..d60159775 100644 --- a/src/uu/sort/src/numeric_str_cmp.rs +++ b/src/uu/sort/src/numeric_str_cmp.rs @@ -52,7 +52,7 @@ impl NumInfo { /// an empty range (idx..idx) is returned so that idx is the char after the last zero. /// If the input is not a number (which has to be treated as zero), the returned empty range /// will be 0..0. - pub fn parse(num: &str, parse_settings: NumInfoParseSettings) -> (Self, Range) { + pub fn parse(num: &str, parse_settings: &NumInfoParseSettings) -> (Self, Range) { let mut exponent = -1; let mut had_decimal_pt = false; let mut had_digit = false; @@ -80,7 +80,7 @@ impl NumInfo { continue; } - if Self::is_invalid_char(char, &mut had_decimal_pt, &parse_settings) { + if Self::is_invalid_char(char, &mut had_decimal_pt, parse_settings) { return if let Some(start) = start { let has_si_unit = parse_settings.accept_si_units && matches!(char, 'K' | 'k' | 'M' | 'G' | 'T' | 'P' | 'E' | 'Z' | 'Y'); @@ -270,7 +270,7 @@ mod tests { fn parses_exp() { let n = "1"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 0, @@ -281,7 +281,7 @@ mod tests { ); let n = "100"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 2, @@ -294,7 +294,7 @@ mod tests { assert_eq!( NumInfo::parse( n, - NumInfoParseSettings { + &NumInfoParseSettings { thousands_separator: Some(','), ..Default::default() } @@ -309,7 +309,7 @@ mod tests { ); let n = "1,000"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 0, @@ -320,7 +320,7 @@ mod tests { ); let n = "1000.00"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 3, @@ -334,7 +334,7 @@ mod tests { fn parses_negative_exp() { let n = "0.00005"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: -5, @@ -345,7 +345,7 @@ mod tests { ); let n = "00000.00005"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: -5, @@ -360,7 +360,7 @@ mod tests { fn parses_sign() { let n = "5"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 0, @@ -371,7 +371,7 @@ mod tests { ); let n = "-5"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 0, @@ -382,7 +382,7 @@ mod tests { ); let n = " -5"; assert_eq!( - NumInfo::parse(n, Default::default()), + NumInfo::parse(n, &Default::default()), ( NumInfo { exponent: 0, @@ -394,8 +394,8 @@ mod tests { } fn test_helper(a: &str, b: &str, expected: Ordering) { - let (a_info, a_range) = NumInfo::parse(a, Default::default()); - let (b_info, b_range) = NumInfo::parse(b, Default::default()); + let (a_info, a_range) = NumInfo::parse(a, &Default::default()); + let (b_info, b_range) = NumInfo::parse(b, &Default::default()); let ordering = numeric_str_cmp( (&a[a_range.to_owned()], &a_info), (&b[b_range.to_owned()], &b_info), @@ -470,7 +470,7 @@ mod tests { } #[test] fn single_minus() { - let info = NumInfo::parse("-", Default::default()); + let info = NumInfo::parse("-", &Default::default()); assert_eq!( info, ( @@ -486,7 +486,7 @@ mod tests { fn invalid_with_unit() { let info = NumInfo::parse( "-K", - NumInfoParseSettings { + &NumInfoParseSettings { accept_si_units: true, ..Default::default() }, diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index faafbba1c..e7d7bb03f 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -578,7 +578,7 @@ impl<'a> Line<'a> { // find out which range is used for numeric comparisons let (_, num_range) = NumInfo::parse( &self.line[selection.clone()], - NumInfoParseSettings { + &NumInfoParseSettings { accept_si_units: selector.settings.mode == SortMode::HumanNumeric, ..Default::default() }, @@ -927,7 +927,7 @@ impl FieldSelector { // Parse NumInfo for this number. let (info, num_range) = NumInfo::parse( range, - NumInfoParseSettings { + &NumInfoParseSettings { accept_si_units: self.settings.mode == SortMode::HumanNumeric, ..Default::default() }, @@ -1156,7 +1156,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .value_of(options::BUF_SIZE) .map_or(Ok(DEFAULT_BUF_SIZE), |s| { GlobalSettings::parse_byte_count(s).map_err(|e| { - USimpleError::new(2, format_error_message(e, s, options::BUF_SIZE)) + USimpleError::new(2, format_error_message(&e, s, options::BUF_SIZE)) }) })?; @@ -1829,7 +1829,7 @@ fn open(path: impl AsRef) -> UResult> { } } -fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String { +fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String { // NOTE: // GNU's sort echos affected flag, -S or --buffer-size, depending user's selection // GNU's sort does distinguish between "invalid (suffix in) argument" diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index dbc17da70..d83408ce6 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -62,7 +62,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .after_help(&long_usage[..]) .get_matches_from(args); let settings = Settings::from(matches)?; - split(settings) + split(&settings) } pub fn uu_app<'a>() -> App<'a> { @@ -436,7 +436,7 @@ where .map_err_context(|| "I/O error".to_string()) } -fn split(settings: Settings) -> UResult<()> { +fn split(settings: &Settings) -> UResult<()> { let mut reader = BufReader::new(if settings.input == "-" { Box::new(stdin()) as Box } else { @@ -450,7 +450,7 @@ fn split(settings: Settings) -> UResult<()> { }); if let Strategy::Number(num_chunks) = settings.strategy { - return split_into_n_chunks_by_byte(&settings, &mut reader, num_chunks); + return split_into_n_chunks_by_byte(settings, &mut reader, num_chunks); } let mut splitter: Box = match settings.strategy { diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index 933b26ef9..11f8581be 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -219,7 +219,7 @@ pub struct Stater { } #[allow(clippy::cognitive_complexity)] -fn print_it(arg: &str, output_type: OutputType, flag: u8, width: usize, precision: i32) { +fn print_it(arg: &str, output_type: &OutputType, flag: u8, width: usize, precision: i32) { // If the precision is given as just '.', the precision is taken to be zero. // A negative precision is taken as if the precision were omitted. // This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, @@ -250,7 +250,7 @@ fn print_it(arg: &str, output_type: OutputType, flag: u8, width: usize, precisio // By default, a sign is used only for negative numbers. // A + overrides a space if both are used. - if output_type == OutputType::Unknown { + if output_type == &OutputType::Unknown { return print!("?"); } @@ -461,7 +461,7 @@ impl Stater { Ok(tokens) } - fn new(matches: ArgMatches) -> UResult { + fn new(matches: &ArgMatches) -> UResult { let files: Vec = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) @@ -743,7 +743,7 @@ impl Stater { output_type = OutputType::Unknown; } } - print_it(&arg, output_type, flag, width, precision); + print_it(&arg, &output_type, flag, width, precision); } } } @@ -836,7 +836,7 @@ impl Stater { } } - print_it(&arg, output_type, flag, width, precision); + print_it(&arg, &output_type, flag, width, precision); } } } @@ -957,7 +957,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .after_help(&long_usage[..]) .get_matches_from(args); - let stater = Stater::new(matches)?; + let stater = Stater::new(&matches)?; let exit_status = stater.exec(); if exit_status == 0 { Ok(()) diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index cc5da742e..b0581b3f6 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -127,7 +127,7 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result { command.env(buffer_name, m.to_string()); @@ -167,9 +167,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let mut tmp_dir = tempdir().unwrap(); let (preload_env, libstdbuf) = get_preload_env(&mut tmp_dir).map_err_context(String::new)?; command.env(preload_env, libstdbuf); - set_command_env(&mut command, "_STDBUF_I", options.stdin); - set_command_env(&mut command, "_STDBUF_O", options.stdout); - set_command_env(&mut command, "_STDBUF_E", options.stderr); + set_command_env(&mut command, "_STDBUF_I", &options.stdin); + set_command_env(&mut command, "_STDBUF_O", &options.stdout); + set_command_env(&mut command, "_STDBUF_E", &options.stderr); command.args(command_params); let mut process = command diff --git a/src/uu/tac/src/tac.rs b/src/uu/tac/src/tac.rs index c729f1581..5b48c9702 100644 --- a/src/uu/tac/src/tac.rs +++ b/src/uu/tac/src/tac.rs @@ -57,7 +57,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { None => vec!["-"], }; - tac(files, before, regex, separator) + tac(&files, before, regex, separator) } pub fn uu_app<'a>() -> App<'a> { @@ -223,7 +223,7 @@ fn buffer_tac(data: &[u8], before: bool, separator: &str) -> std::io::Result<()> Ok(()) } -fn tac(filenames: Vec<&str>, before: bool, regex: bool, separator: &str) -> UResult<()> { +fn tac(filenames: &[&str], before: bool, regex: bool, separator: &str) -> UResult<()> { // Compile the regular expression pattern if it is provided. let maybe_pattern = if regex { match regex::bytes::Regex::new(separator) { @@ -234,7 +234,7 @@ fn tac(filenames: Vec<&str>, before: bool, regex: bool, separator: &str) -> URes None }; - for &filename in &filenames { + for &filename in filenames { let mmap; let buf; diff --git a/src/uu/tee/src/tee.rs b/src/uu/tee/src/tee.rs index fb102ab2a..937f06769 100644 --- a/src/uu/tee/src/tee.rs +++ b/src/uu/tee/src/tee.rs @@ -53,7 +53,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .unwrap_or_default(), }; - match tee(options) { + match tee(&options) { Ok(_) => Ok(()), Err(_) => Err(1.into()), } @@ -95,7 +95,7 @@ fn ignore_interrupts() -> Result<()> { Ok(()) } -fn tee(options: Options) -> Result<()> { +fn tee(options: &Options) -> Result<()> { if options.ignore_interrupts { ignore_interrupts()? } diff --git a/src/uu/test/src/test.rs b/src/uu/test/src/test.rs index 566deb732..e5f8a93d6 100644 --- a/src/uu/test/src/test.rs +++ b/src/uu/test/src/test.rs @@ -188,25 +188,25 @@ fn eval(stack: &mut Vec) -> Result { let f = pop_literal!(); Ok(match op { - "-b" => path(&f, PathCondition::BlockSpecial), - "-c" => path(&f, PathCondition::CharacterSpecial), - "-d" => path(&f, PathCondition::Directory), - "-e" => path(&f, PathCondition::Exists), - "-f" => path(&f, PathCondition::Regular), - "-g" => path(&f, PathCondition::GroupIdFlag), - "-G" => path(&f, PathCondition::GroupOwns), - "-h" => path(&f, PathCondition::SymLink), - "-k" => path(&f, PathCondition::Sticky), - "-L" => path(&f, PathCondition::SymLink), - "-O" => path(&f, PathCondition::UserOwns), - "-p" => path(&f, PathCondition::Fifo), - "-r" => path(&f, PathCondition::Readable), - "-S" => path(&f, PathCondition::Socket), - "-s" => path(&f, PathCondition::NonEmpty), + "-b" => path(&f, &PathCondition::BlockSpecial), + "-c" => path(&f, &PathCondition::CharacterSpecial), + "-d" => path(&f, &PathCondition::Directory), + "-e" => path(&f, &PathCondition::Exists), + "-f" => path(&f, &PathCondition::Regular), + "-g" => path(&f, &PathCondition::GroupIdFlag), + "-G" => path(&f, &PathCondition::GroupOwns), + "-h" => path(&f, &PathCondition::SymLink), + "-k" => path(&f, &PathCondition::Sticky), + "-L" => path(&f, &PathCondition::SymLink), + "-O" => path(&f, &PathCondition::UserOwns), + "-p" => path(&f, &PathCondition::Fifo), + "-r" => path(&f, &PathCondition::Readable), + "-S" => path(&f, &PathCondition::Socket), + "-s" => path(&f, &PathCondition::NonEmpty), "-t" => isatty(&f)?, - "-u" => path(&f, PathCondition::UserIdFlag), - "-w" => path(&f, PathCondition::Writable), - "-x" => path(&f, PathCondition::Executable), + "-u" => path(&f, &PathCondition::UserIdFlag), + "-w" => path(&f, &PathCondition::Writable), + "-x" => path(&f, &PathCondition::Executable), _ => panic!(), }) } @@ -283,7 +283,7 @@ enum PathCondition { } #[cfg(not(windows))] -fn path(path: &OsStr, condition: PathCondition) -> bool { +fn path(path: &OsStr, condition: &PathCondition) -> bool { use std::fs::{self, Metadata}; use std::os::unix::fs::{FileTypeExt, MetadataExt}; @@ -325,7 +325,7 @@ fn path(path: &OsStr, condition: PathCondition) -> bool { } }; - let metadata = if condition == PathCondition::SymLink { + let metadata = if condition == &PathCondition::SymLink { fs::symlink_metadata(path) } else { fs::metadata(path) @@ -362,7 +362,7 @@ fn path(path: &OsStr, condition: PathCondition) -> bool { } #[cfg(windows)] -fn path(path: &OsStr, condition: PathCondition) -> bool { +fn path(path: &OsStr, condition: &PathCondition) -> bool { use std::fs::metadata; let stat = match metadata(path) { diff --git a/src/uu/timeout/src/timeout.rs b/src/uu/timeout/src/timeout.rs index 2542bd6e6..9a8222dee 100644 --- a/src/uu/timeout/src/timeout.rs +++ b/src/uu/timeout/src/timeout.rs @@ -57,7 +57,7 @@ struct Config { } impl Config { - fn from(options: clap::ArgMatches) -> Config { + fn from(options: &clap::ArgMatches) -> Config { let signal = match options.value_of(options::SIGNAL) { Some(signal_) => { let signal_result = signal_by_name_or_value(signal_); @@ -112,7 +112,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = app.get_matches_from(args); - let config = Config::from(matches); + let config = Config::from(&matches); timeout( &config.command, config.duration, diff --git a/src/uu/tr/src/convert.rs b/src/uu/tr/src/convert.rs index 4a7b97250..b3d986f1e 100644 --- a/src/uu/tr/src/convert.rs +++ b/src/uu/tr/src/convert.rs @@ -27,8 +27,8 @@ fn parse_octal(input: &str) -> IResult<&str, char> { )(input) } -pub fn reduce_octal_to_char(input: String) -> String { - let result = many0(alt((parse_octal, anychar)))(input.as_str()) +pub fn reduce_octal_to_char(input: &str) -> String { + let result = many0(alt((parse_octal, anychar)))(input) .map(|(_, r)| r) .unwrap() .into_iter() diff --git a/src/uu/tr/src/tr.rs b/src/uu/tr/src/tr.rs index 26c8d6d82..f2efbb176 100644 --- a/src/uu/tr/src/tr.rs +++ b/src/uu/tr/src/tr.rs @@ -64,7 +64,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .values_of(options::SETS) .map(|v| { v.map(ToString::to_string) - .map(convert::reduce_octal_to_char) + .map(|input| convert::reduce_octal_to_char(&input)) .collect::>() }) .unwrap_or_default(); diff --git a/src/uu/truncate/src/truncate.rs b/src/uu/truncate/src/truncate.rs index fb945a00c..685363f8f 100644 --- a/src/uu/truncate/src/truncate.rs +++ b/src/uu/truncate/src/truncate.rs @@ -129,7 +129,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let no_create = matches.is_present(options::NO_CREATE); let reference = matches.value_of(options::REFERENCE).map(String::from); let size = matches.value_of(options::SIZE).map(String::from); - truncate(no_create, io_blocks, reference, size, files) + truncate(no_create, io_blocks, reference, size, &files) } } @@ -210,7 +210,7 @@ fn file_truncate(filename: &str, create: bool, size: usize) -> std::io::Result<( fn truncate_reference_and_size( rfilename: &str, size_string: &str, - filenames: Vec, + filenames: &[String], create: bool, ) -> UResult<()> { let mode = match parse_mode_and_size(size_string) { @@ -238,7 +238,7 @@ fn truncate_reference_and_size( })?; let fsize = metadata.len() as usize; let tsize = mode.to_size(fsize); - for filename in &filenames { + for filename in filenames { file_truncate(filename, create, tsize) .map_err_context(|| format!("cannot open {} for writing", filename.quote()))?; } @@ -258,7 +258,7 @@ fn truncate_reference_and_size( /// the size of at least one file. fn truncate_reference_file_only( rfilename: &str, - filenames: Vec, + filenames: &[String], create: bool, ) -> UResult<()> { let metadata = metadata(rfilename).map_err(|e| match e.kind() { @@ -272,7 +272,7 @@ fn truncate_reference_file_only( _ => e.map_err_context(String::new), })?; let tsize = metadata.len() as usize; - for filename in &filenames { + for filename in filenames { file_truncate(filename, create, tsize) .map_err_context(|| format!("cannot open {} for writing", filename.quote()))?; } @@ -294,13 +294,13 @@ fn truncate_reference_file_only( /// /// If the any file could not be opened, or there was a problem setting /// the size of at least one file. -fn truncate_size_only(size_string: &str, filenames: Vec, create: bool) -> UResult<()> { +fn truncate_size_only(size_string: &str, filenames: &[String], create: bool) -> UResult<()> { let mode = parse_mode_and_size(size_string) .map_err(|e| USimpleError::new(1, format!("Invalid number: {}", e)))?; if let TruncateMode::RoundDown(0) | TruncateMode::RoundUp(0) = mode { return Err(USimpleError::new(1, "division by zero")); } - for filename in &filenames { + for filename in filenames { let fsize = match metadata(filename) { Ok(m) => m.len(), Err(_) => 0, @@ -324,7 +324,7 @@ fn truncate( _: bool, reference: Option, size: Option, - filenames: Vec, + filenames: &[String], ) -> UResult<()> { let create = !no_create; // There are four possibilities diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index aeac7cfe1..a1c5a91ef 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -27,7 +27,7 @@ static SUMMARY: &str = "Convert blanks in each FILE to tabs, writing to standard const DEFAULT_TABSTOP: usize = 8; -fn tabstops_parse(s: String) -> Vec { +fn tabstops_parse(s: &str) -> Vec { let words = s.split(','); let nums = words @@ -67,10 +67,10 @@ struct Options { } impl Options { - fn new(matches: clap::ArgMatches) -> Options { + fn new(matches: &clap::ArgMatches) -> Options { let tabstops = match matches.value_of(options::TABS) { None => vec![DEFAULT_TABSTOP], - Some(s) => tabstops_parse(s.to_string()), + Some(s) => tabstops_parse(s), }; let aflag = (matches.is_present(options::ALL) || matches.is_present(options::TABS)) @@ -99,7 +99,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let matches = uu_app().get_matches_from(args); - unexpand(Options::new(matches)).map_err_context(String::new) + unexpand(&Options::new(&matches)).map_err_context(String::new) } pub fn uu_app<'a>() -> App<'a> { @@ -138,7 +138,7 @@ pub fn uu_app<'a>() -> App<'a> { .help("interpret input file as 8-bit ASCII rather than UTF-8")) } -fn open(path: String) -> BufReader> { +fn open(path: &str) -> BufReader> { let file_buf; if path == "-" { BufReader::new(Box::new(stdin()) as Box) @@ -243,13 +243,13 @@ fn next_char_info(uflag: bool, buf: &[u8], byte: usize) -> (CharType, usize, usi (ctype, cwidth, nbytes) } -fn unexpand(options: Options) -> std::io::Result<()> { +fn unexpand(options: &Options) -> std::io::Result<()> { let mut output = BufWriter::new(stdout()); let ts = &options.tabstops[..]; let mut buf = Vec::new(); let lastcol = if ts.len() > 1 { *ts.last().unwrap() } else { 0 }; - for file in options.files.into_iter() { + for file in options.files.iter() { let mut fh = open(file); while match fh.read_until(b'\n', &mut buf) { diff --git a/src/uu/uniq/src/uniq.rs b/src/uu/uniq/src/uniq.rs index c5192d98a..111124c05 100644 --- a/src/uu/uniq/src/uniq.rs +++ b/src/uu/uniq/src/uniq.rs @@ -294,8 +294,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { zero_terminated: matches.is_present(options::ZERO_TERMINATED), }; uniq.print_uniq( - &mut open_input_file(in_file_name)?, - &mut open_output_file(out_file_name)?, + &mut open_input_file(&in_file_name)?, + &mut open_output_file(&out_file_name)?, ) } @@ -409,11 +409,11 @@ fn get_delimiter(matches: &ArgMatches) -> Delimiters { } } -fn open_input_file(in_file_name: String) -> UResult>> { +fn open_input_file(in_file_name: &str) -> UResult>> { let in_file = if in_file_name == "-" { Box::new(stdin()) as Box } else { - let path = Path::new(&in_file_name[..]); + let path = Path::new(in_file_name); let in_file = File::open(&path) .map_err_context(|| format!("Could not open {}", in_file_name.maybe_quote()))?; Box::new(in_file) as Box @@ -421,11 +421,11 @@ fn open_input_file(in_file_name: String) -> UResult UResult>> { +fn open_output_file(out_file_name: &str) -> UResult>> { let out_file = if out_file_name == "-" { Box::new(stdout()) as Box } else { - let path = Path::new(&out_file_name[..]); + let path = Path::new(out_file_name); let out_file = File::create(&path) .map_err_context(|| format!("Could not create {}", out_file_name.maybe_quote()))?; Box::new(out_file) as Box diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index c7e53d0de..d8782e62d 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -159,7 +159,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let settings = Settings::new(&matches); - wc(inputs, &settings) + wc(&inputs, &settings) } pub fn uu_app<'a>() -> App<'a> { @@ -409,7 +409,7 @@ fn max_width(inputs: &[Input]) -> usize { result } -fn wc(inputs: Vec, settings: &Settings) -> UResult<()> { +fn wc(inputs: &[Input], settings: &Settings) -> UResult<()> { // Compute the width, in digits, to use when formatting counts. // // The width is the number of digits needed to print the number of @@ -421,14 +421,14 @@ fn wc(inputs: Vec, settings: &Settings) -> UResult<()> { let max_width = if settings.number_enabled() <= 1 { 0 } else { - max_width(&inputs) + max_width(inputs) }; let mut total_word_count = WordCount::default(); let num_inputs = inputs.len(); - for input in &inputs { + for input in inputs { let word_count = match word_count_from_input(input, settings) { CountResult::Success(word_count) => word_count, CountResult::Interrupted(word_count, error) => { diff --git a/src/uucore/src/lib/features/encoding.rs b/src/uucore/src/lib/features/encoding.rs index 8eee74c55..b36e6a6a0 100644 --- a/src/uucore/src/lib/features/encoding.rs +++ b/src/uucore/src/lib/features/encoding.rs @@ -156,12 +156,12 @@ impl Data { } // NOTE: this will likely be phased out at some point -pub fn wrap_print(data: &Data, res: String) { +pub fn wrap_print(data: &Data, res: &str) { let stdout = io::stdout(); wrap_write(stdout.lock(), data.line_wrap, res).unwrap(); } -pub fn wrap_write(mut writer: W, line_wrap: usize, res: String) -> io::Result<()> { +pub fn wrap_write(mut writer: W, line_wrap: usize, res: &str) -> io::Result<()> { use std::cmp::min; if line_wrap == 0 { diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index 0461555e7..b3ea7e780 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -197,7 +197,7 @@ impl MountInfo { } #[cfg(target_os = "linux")] - fn new(file_name: &str, raw: Vec<&str>) -> Option { + fn new(file_name: &str, raw: &[&str]) -> Option { match file_name { // spell-checker:ignore (word) noatime // Format: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue @@ -410,7 +410,7 @@ pub fn read_fs_list() -> Vec { .filter_map(|line| line.ok()) .filter_map(|line| { let raw_data = line.split_whitespace().collect::>(); - MountInfo::new(file_name, raw_data) + MountInfo::new(file_name, &raw_data) }) .collect::>() } @@ -902,9 +902,9 @@ mod tests { // spell-checker:ignore (word) relatime let info = MountInfo::new( LINUX_MOUNTINFO, - "106 109 253:6 / /mnt rw,relatime - xfs /dev/fs0 rw" + &"106 109 253:6 / /mnt rw,relatime - xfs /dev/fs0 rw" .split_ascii_whitespace() - .collect(), + .collect::>(), ) .unwrap(); @@ -917,9 +917,9 @@ mod tests { // Test parsing with different amounts of optional fields. let info = MountInfo::new( LINUX_MOUNTINFO, - "106 109 253:6 / /mnt rw,relatime master:1 - xfs /dev/fs0 rw" + &"106 109 253:6 / /mnt rw,relatime master:1 - xfs /dev/fs0 rw" .split_ascii_whitespace() - .collect(), + .collect::>(), ) .unwrap(); @@ -928,9 +928,9 @@ mod tests { let info = MountInfo::new( LINUX_MOUNTINFO, - "106 109 253:6 / /mnt rw,relatime master:1 shared:2 - xfs /dev/fs0 rw" + &"106 109 253:6 / /mnt rw,relatime master:1 shared:2 - xfs /dev/fs0 rw" .split_ascii_whitespace() - .collect(), + .collect::>(), ) .unwrap(); diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs index 076731f3f..d92caff75 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs @@ -46,12 +46,12 @@ pub struct DivOut<'a> { } #[allow(dead_code)] -pub fn arrnum_int_div_step( - rem_in: Remainder, +pub fn arrnum_int_div_step<'a>( + rem_in: &'a Remainder, radix_in: u8, base_ten_int_divisor: u8, after_decimal: bool, -) -> DivOut { +) -> DivOut<'a> { let mut rem_out = Remainder { position: rem_in.position, replace: Vec::new(), diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/tests.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/tests.rs index 7945d41ac..903a3faf1 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/tests.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/tests.rs @@ -49,7 +49,7 @@ fn test_arrnum_int_div_short_circuit() { let remainder_position_should_be: usize = 3; let remainder_replace_should_be = vec![1, 2]; - let result = arrnum_int_div_step(remainder_passed_in, base_num, base_ten_int_divisor, false); + let result = arrnum_int_div_step(&remainder_passed_in, base_num, base_ten_int_divisor, false); assert!(quotient_should_be == result.quotient); assert!(remainder_position_should_be == result.remainder.position); assert!(remainder_replace_should_be == result.remainder.replace); diff --git a/src/uucore/src/lib/features/tokenize/num_format/num_format.rs b/src/uucore/src/lib/features/tokenize/num_format/num_format.rs index 0e184fb6f..89d0fe89b 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/num_format.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/num_format.rs @@ -25,7 +25,7 @@ pub fn warn_expected_numeric(pf_arg: &str) { // when character constant arguments have excess characters // issue a warning when POSIXLY_CORRECT is not set -fn warn_char_constant_ign(remaining_bytes: Vec) { +fn warn_char_constant_ign(remaining_bytes: &[u8]) { match env::var("POSIXLY_CORRECT") { Ok(_) => {} Err(e) => { @@ -59,7 +59,7 @@ fn get_provided(str_in_opt: Option<&String>) -> Option { ignored.push(cont); } if !ignored.is_empty() { - warn_char_constant_ign(ignored); + warn_char_constant_ign(&ignored); } second_byte as u8 } diff --git a/tests/by-util/test_basename.rs b/tests/by-util/test_basename.rs index 9a9e7983d..1250ba76f 100644 --- a/tests/by-util/test_basename.rs +++ b/tests/by-util/test_basename.rs @@ -92,9 +92,9 @@ fn test_zero_param() { } } -fn expect_error(input: Vec<&str>) { +fn expect_error(input: &[&str]) { assert!(!new_ucmd!() - .args(&input) + .args(input) .fails() .no_stdout() .stderr_str() @@ -104,12 +104,12 @@ fn expect_error(input: Vec<&str>) { #[test] fn test_invalid_option() { let path = "/foo/bar/baz"; - expect_error(vec!["-q", path]); + expect_error(&["-q", path]); } #[test] fn test_no_args() { - expect_error(vec![]); + expect_error(&[]); } #[test] @@ -119,7 +119,7 @@ fn test_no_args_output() { #[test] fn test_too_many_args() { - expect_error(vec!["a", "b", "c"]); + expect_error(&["a", "b", "c"]); } #[test] diff --git a/tests/by-util/test_chmod.rs b/tests/by-util/test_chmod.rs index 1b0b7131b..f3c01722e 100644 --- a/tests/by-util/test_chmod.rs +++ b/tests/by-util/test_chmod.rs @@ -33,7 +33,7 @@ fn make_file(file: &str, mode: u32) { set_permissions(file, perms).unwrap(); } -fn run_single_test(test: &TestCase, at: AtPath, mut ucmd: UCommand) { +fn run_single_test(test: &TestCase, at: &AtPath, mut ucmd: UCommand) { make_file(&at.plus_as_string(TEST_FILE), test.before); let perms = at.metadata(TEST_FILE).permissions().mode(); if perms != test.before { @@ -64,7 +64,7 @@ fn run_single_test(test: &TestCase, at: AtPath, mut ucmd: UCommand) { fn run_tests(tests: Vec) { for test in tests { let (at, ucmd) = at_and_ucmd!(); - run_single_test(&test, at, ucmd); + run_single_test(&test, &at, ucmd); } } @@ -295,7 +295,7 @@ fn test_chmod_reference_file() { ]; let (at, ucmd) = at_and_ucmd!(); make_file(&at.plus_as_string(REFERENCE_FILE), REFERENCE_PERMS); - run_single_test(&tests[0], at, ucmd); + run_single_test(&tests[0], &at, ucmd); } #[test] @@ -553,7 +553,7 @@ fn test_mode_after_dash_dash() { before: 0o100777, after: 0o100333, }, - at, + &at, ucmd, ); } diff --git a/tests/common/util.rs b/tests/common/util.rs index 0b44851db..f86cf2d26 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -235,7 +235,7 @@ impl CmdResult { } /// like `stdout_is`, but succeeds if any elements of `expected` matches stdout. - pub fn stdout_is_any + std::fmt::Debug>(&self, expected: Vec) -> &CmdResult { + pub fn stdout_is_any + std::fmt::Debug>(&self, expected: &[T]) -> &CmdResult { if !expected.iter().any(|msg| self.stdout_str() == msg.as_ref()) { panic!( "stdout was {}\nExpected any of {:#?}", @@ -294,7 +294,7 @@ impl CmdResult { } contents }); - self.stdout_is_any(possible_values.collect()); + self.stdout_is_any(&possible_values.collect::>()); } /// asserts that the command resulted in stderr stream output that equals the @@ -816,13 +816,13 @@ impl TestScenario { util_name: T, env_clear: bool, ) -> UCommand { - UCommand::new_from_tmp(bin, Some(util_name), self.tmpd.clone(), env_clear) + UCommand::new_from_tmp(bin, &Some(util_name), self.tmpd.clone(), env_clear) } /// Returns builder for invoking any system command. Paths given are treated /// relative to the environment's unique temporary test directory. pub fn cmd>(&self, bin: S) -> UCommand { - UCommand::new_from_tmp::(bin, None, self.tmpd.clone(), true) + UCommand::new_from_tmp::(bin, &None, self.tmpd.clone(), true) } /// Returns builder for invoking any uutils command. Paths given are treated @@ -842,7 +842,7 @@ impl TestScenario { /// Differs from the builder returned by `cmd` in that `cmd_keepenv` does not call /// `Command::env_clear` (Clears the entire environment map for the child process.) pub fn cmd_keepenv>(&self, bin: S) -> UCommand { - UCommand::new_from_tmp::(bin, None, self.tmpd.clone(), false) + UCommand::new_from_tmp::(bin, &None, self.tmpd.clone(), false) } } @@ -872,7 +872,7 @@ pub struct UCommand { impl UCommand { pub fn new, S: AsRef, U: AsRef>( bin_path: T, - util_name: Option, + util_name: &Option, curdir: U, env_clear: bool, ) -> UCommand { @@ -924,7 +924,7 @@ impl UCommand { pub fn new_from_tmp, S: AsRef>( bin_path: T, - util_name: Option, + util_name: &Option, tmpd: Rc, env_clear: bool, ) -> UCommand { From 784f2e2ea1f7e8adde2796ce214a1927e609308d Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 13:55:03 +0100 Subject: [PATCH 07/10] use semicolons if nothing returned --- build.rs | 10 ++++---- src/bin/uudoc.rs | 2 +- src/uu/chcon/src/chcon.rs | 2 +- src/uu/cp/src/cp.rs | 6 ++--- src/uu/dd/src/parseargs.rs | 4 ++-- src/uu/dd/src/parseargs/unit_tests.rs | 4 ++-- src/uu/dircolors/src/dircolors.rs | 4 ++-- src/uu/dirname/src/dirname.rs | 2 +- src/uu/du/src/du.rs | 4 ++-- src/uu/expand/src/expand.rs | 2 +- src/uu/expr/src/syntax_tree.rs | 2 +- src/uu/expr/src/tokens.rs | 4 ++-- src/uu/factor/src/factor.rs | 8 +++---- src/uu/fmt/src/linebreak.rs | 2 +- src/uu/hashsum/src/digest.rs | 2 +- src/uu/hashsum/src/hashsum.rs | 24 +++++++++---------- src/uu/head/src/head.rs | 4 ++-- src/uu/head/src/parse.rs | 12 +++++----- src/uu/ln/src/ln.rs | 6 ++--- src/uu/mktemp/src/mktemp.rs | 2 +- src/uu/mv/src/mv.rs | 4 ++-- src/uu/od/src/multifilereader.rs | 2 +- src/uu/od/src/parse_formats.rs | 2 +- src/uu/pinky/src/pinky.rs | 14 +++++------ src/uu/ptx/src/ptx.rs | 2 +- src/uu/shred/src/shred.rs | 4 ++-- src/uu/shuf/src/rand_read_adapter.rs | 2 +- src/uu/sort/src/ext_sort.rs | 2 +- src/uu/sort/src/merge.rs | 4 ++-- src/uu/sort/src/sort.rs | 12 +++++----- src/uu/split/src/platform/unix.rs | 2 +- src/uu/stat/src/stat.rs | 2 +- src/uu/tail/src/parse.rs | 12 +++++----- src/uu/tail/src/tail.rs | 2 +- src/uu/tee/src/tee.rs | 2 +- src/uu/uptime/src/uptime.rs | 2 +- src/uu/wc/src/word_count.rs | 2 +- src/uu/who/src/who.rs | 2 +- src/uucore/src/lib/features/fs.rs | 2 +- src/uucore/src/lib/features/fsext.rs | 2 +- src/uucore/src/lib/features/mode.rs | 4 ++-- src/uucore/src/lib/features/perms.rs | 6 ++--- .../num_format/formatters/base_conv/mod.rs | 6 ++--- src/uucore/src/lib/features/tokenize/sub.rs | 4 ++-- .../lib/features/tokenize/unescaped_text.rs | 2 +- src/uucore/src/lib/lib.rs | 2 +- src/uucore/src/lib/mods/panic.rs | 2 +- tests/by-util/test_chcon.rs | 4 ++-- tests/by-util/test_chown.rs | 2 +- tests/by-util/test_env.rs | 2 +- tests/by-util/test_ls.rs | 4 ++-- tests/by-util/test_mkdir.rs | 6 ++--- tests/by-util/test_shuf.rs | 4 ++-- tests/by-util/test_sort.rs | 10 ++++---- tests/by-util/test_touch.rs | 2 +- tests/common/util.rs | 8 +++---- 56 files changed, 125 insertions(+), 127 deletions(-) diff --git a/build.rs b/build.rs index ecff0f707..a5dfb3646 100644 --- a/build.rs +++ b/build.rs @@ -77,7 +77,7 @@ pub fn main() { ) .as_bytes(), ) - .unwrap() + .unwrap(); } k if k.starts_with(override_prefix) => { mf.write_all( @@ -97,7 +97,7 @@ pub fn main() { ) .as_bytes(), ) - .unwrap() + .unwrap(); } "false" | "true" => { mf.write_all( @@ -116,7 +116,7 @@ pub fn main() { ) .as_bytes(), ) - .unwrap() + .unwrap(); } "hashsum" => { mf.write_all( @@ -150,7 +150,7 @@ pub fn main() { ) .as_bytes(), ) - .unwrap() + .unwrap(); } _ => { mf.write_all( @@ -169,7 +169,7 @@ pub fn main() { ) .as_bytes(), ) - .unwrap() + .unwrap(); } } } diff --git a/src/bin/uudoc.rs b/src/bin/uudoc.rs index 38e8a0323..bbb20eb1d 100644 --- a/src/bin/uudoc.rs +++ b/src/bin/uudoc.rs @@ -45,7 +45,7 @@ fn main() -> io::Result<()> { } else { println!("Error writing to {}", p); } - writeln!(summary, "* [{0}](utils/{0}.md)", name)? + writeln!(summary, "* [{0}](utils/{0}.md)", name)?; } Ok(()) } diff --git a/src/uu/chcon/src/chcon.rs b/src/uu/chcon/src/chcon.rs index 0b373c5e0..84de681cd 100644 --- a/src/uu/chcon/src/chcon.rs +++ b/src/uu/chcon/src/chcon.rs @@ -743,7 +743,7 @@ This almost certainly means that you have a corrupted file system.\n\ NOTIFY YOUR SYSTEM MANAGER.\n\ The following directory is part of the cycle {}.", file_name.quote() - ) + ); } #[derive(Debug)] diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index a0d62295e..49cecfc00 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -742,7 +742,7 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec CopyResu } _ => { show_error!("{}", error); - non_fatal_errors = true + non_fatal_errors = true; } } } @@ -1580,5 +1580,5 @@ fn test_cp_localize_to_target() { ) .unwrap() == Path::new("target/c.txt") - ) + ); } diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index 57d93f966..c790de41f 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -491,14 +491,14 @@ pub fn parse_conv_flag_input(matches: &Matches) -> Result { if case.is_some() { return Err(ParseError::MultipleUCaseLCase); } else { - case = Some(flag) + case = Some(flag); } } ConvFlag::Block => match (cbs, iconvflags.unblock) { diff --git a/src/uu/dd/src/parseargs/unit_tests.rs b/src/uu/dd/src/parseargs/unit_tests.rs index c74439159..a72944309 100644 --- a/src/uu/dd/src/parseargs/unit_tests.rs +++ b/src/uu/dd/src/parseargs/unit_tests.rs @@ -56,10 +56,10 @@ fn unimplemented_flags_should_error() { let matches = uu_app().try_get_matches_from(args).unwrap(); if parse_iflags(&matches).is_ok() { - succeeded.push(format!("iflag={}", flag)) + succeeded.push(format!("iflag={}", flag)); } if parse_oflags(&matches).is_ok() { - succeeded.push(format!("oflag={}", flag)) + succeeded.push(format!("oflag={}", flag)); } } diff --git a/src/uu/dircolors/src/dircolors.rs b/src/uu/dircolors/src/dircolors.rs index 2fee24e5b..56f7e62de 100644 --- a/src/uu/dircolors/src/dircolors.rs +++ b/src/uu/dircolors/src/dircolors.rs @@ -127,7 +127,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let result; if files.is_empty() { - result = parse(INTERNAL_DB.lines(), &out_format, "") + result = parse(INTERNAL_DB.lines(), &out_format, ""); } else { if files.len() > 1 { return Err(UUsageError::new( @@ -138,7 +138,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match File::open(files[0]) { Ok(f) => { let fin = BufReader::new(f); - result = parse(fin.lines().filter_map(Result::ok), &out_format, files[0]) + result = parse(fin.lines().filter_map(Result::ok), &out_format, files[0]); } Err(e) => { return Err(USimpleError::new( diff --git a/src/uu/dirname/src/dirname.rs b/src/uu/dirname/src/dirname.rs index 4a6a5ad9b..343007d29 100644 --- a/src/uu/dirname/src/dirname.rs +++ b/src/uu/dirname/src/dirname.rs @@ -61,7 +61,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { match p.parent() { Some(d) => { if d.components().next() == None { - print!(".") + print!("."); } else { print_verbatim(d).unwrap(); } diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index 71d335b1e..e95541cac 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -335,7 +335,7 @@ fn du( ErrorKind::PermissionDenied => { let description = format!("cannot access {}", entry.path().quote()); let error_message = "Permission denied"; - show_error_custom_description!(description, "{}", error_message) + show_error_custom_description!(description, "{}", error_message); } _ => show_error!("cannot access {}: {}", entry.path().quote(), error), }, @@ -486,7 +486,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { if options.inodes && (matches.is_present(options::APPARENT_SIZE) || matches.is_present(options::BYTES)) { - show_warning!("options --apparent-size and -b are ineffective with --inodes") + show_warning!("options --apparent-size and -b are ineffective with --inodes"); } let block_size = u64::try_from(read_block_size(matches.value_of(options::BLOCK_SIZE))).unwrap(); diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 429bc1cc7..ebddaa690 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -332,7 +332,7 @@ fn expand(options: &Options) -> std::io::Result<()> { // now dump out either spaces if we're expanding, or a literal tab if we're not if init || !options.iflag { if nts <= options.tspaces.len() { - output.write_all(options.tspaces[..nts].as_bytes())? + output.write_all(options.tspaces[..nts].as_bytes())?; } else { output.write_all(" ".repeat(nts).as_bytes())?; }; diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index dd90fd0aa..3c78358dc 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -370,7 +370,7 @@ fn push_op_to_stack( }, )) => { if la && prev_prec >= prec || !la && prev_prec > prec { - out_stack.push(op_stack.pop().unwrap()) + out_stack.push(op_stack.pop().unwrap()); } else { op_stack.push((token_idx, token.clone())); return Ok(()); diff --git a/src/uu/expr/src/tokens.rs b/src/uu/expr/src/tokens.rs index 748960bc3..a80ad4a60 100644 --- a/src/uu/expr/src/tokens.rs +++ b/src/uu/expr/src/tokens.rs @@ -155,8 +155,8 @@ fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, toke if should_use_as_escaped { acc.pop(); - acc.push((tok_idx, Token::new_value(s))) + acc.push((tok_idx, Token::new_value(s))); } else { - acc.push((tok_idx, token)) + acc.push((tok_idx, token)); } } diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index d5dbf2491..151aa74a9 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -34,7 +34,7 @@ impl Decomposition { if let Some((_, e)) = self.0.iter_mut().find(|(f, _)| *f == factor) { *e += exp; } else { - self.0.push((factor, exp)) + self.0.push((factor, exp)); } } @@ -79,11 +79,11 @@ impl Factors { pub fn add(&mut self, prime: u64, exp: Exponent) { debug_assert!(miller_rabin::is_prime(prime)); - self.0.borrow_mut().add(prime, exp) + self.0.borrow_mut().add(prime, exp); } pub fn push(&mut self, prime: u64) { - self.add(prime, 1) + self.add(prime, 1); } #[cfg(test)] @@ -99,7 +99,7 @@ impl fmt::Display for Factors { for (p, exp) in v.iter() { for _ in 0..*exp { - write!(f, " {}", p)? + write!(f, " {}", p)?; } } diff --git a/src/uu/fmt/src/linebreak.rs b/src/uu/fmt/src/linebreak.rs index d24d92798..f3096d279 100644 --- a/src/uu/fmt/src/linebreak.rs +++ b/src/uu/fmt/src/linebreak.rs @@ -384,7 +384,7 @@ fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a Wo None => return breakwords, Some(prev) => { breakwords.push((prev, next_best.break_before)); - best_idx = next_best.prev + best_idx = next_best.prev; } } } diff --git a/src/uu/hashsum/src/digest.rs b/src/uu/hashsum/src/digest.rs index 61f425662..4b6b5f6d2 100644 --- a/src/uu/hashsum/src/digest.rs +++ b/src/uu/hashsum/src/digest.rs @@ -44,7 +44,7 @@ impl Digest for md5::Context { } fn input(&mut self, input: &[u8]) { - self.consume(input) + self.consume(input); } fn result(&mut self, out: &mut [u8]) { diff --git a/src/uu/hashsum/src/hashsum.rs b/src/uu/hashsum/src/hashsum.rs index 82f485875..30c9d5b92 100644 --- a/src/uu/hashsum/src/hashsum.rs +++ b/src/uu/hashsum/src/hashsum.rs @@ -173,28 +173,28 @@ fn detect_algo( }; name = n; alg = Some(val); - output_bits = bits + output_bits = bits; }; if matches.is_present("md5") { - set_or_crash("MD5", Box::new(Md5::new()), 128) + set_or_crash("MD5", Box::new(Md5::new()), 128); } if matches.is_present("sha1") { - set_or_crash("SHA1", Box::new(Sha1::new()), 160) + set_or_crash("SHA1", Box::new(Sha1::new()), 160); } if matches.is_present("sha224") { - set_or_crash("SHA224", Box::new(Sha224::new()), 224) + set_or_crash("SHA224", Box::new(Sha224::new()), 224); } if matches.is_present("sha256") { - set_or_crash("SHA256", Box::new(Sha256::new()), 256) + set_or_crash("SHA256", Box::new(Sha256::new()), 256); } if matches.is_present("sha384") { - set_or_crash("SHA384", Box::new(Sha384::new()), 384) + set_or_crash("SHA384", Box::new(Sha384::new()), 384); } if matches.is_present("sha512") { - set_or_crash("SHA512", Box::new(Sha512::new()), 512) + set_or_crash("SHA512", Box::new(Sha512::new()), 512); } if matches.is_present("b2sum") { - set_or_crash("BLAKE2", Box::new(blake2b_simd::State::new()), 512) + set_or_crash("BLAKE2", Box::new(blake2b_simd::State::new()), 512); } if matches.is_present("sha3") { match matches.value_of("bits") { @@ -229,16 +229,16 @@ fn detect_algo( } } if matches.is_present("sha3-224") { - set_or_crash("SHA3-224", Box::new(Sha3_224::new()), 224) + set_or_crash("SHA3-224", Box::new(Sha3_224::new()), 224); } if matches.is_present("sha3-256") { - set_or_crash("SHA3-256", Box::new(Sha3_256::new()), 256) + set_or_crash("SHA3-256", Box::new(Sha3_256::new()), 256); } if matches.is_present("sha3-384") { - set_or_crash("SHA3-384", Box::new(Sha3_384::new()), 384) + set_or_crash("SHA3-384", Box::new(Sha3_384::new()), 384); } if matches.is_present("sha3-512") { - set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512) + set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512); } if matches.is_present("shake128") { match matches.value_of("bits") { diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 5c222657b..69c1ed100 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -424,7 +424,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { if !first { println!(); } - println!("==> standard input <==") + println!("==> standard input <=="); } let stdin = std::io::stdin(); let mut stdin = stdin.lock(); @@ -460,7 +460,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> { if !first { println!(); } - println!("==> {} <==", name) + println!("==> {} <==", name); } head_file(&mut file, options) } diff --git a/src/uu/head/src/parse.rs b/src/uu/head/src/parse.rs index 8bcfea3da..3f1d8ef42 100644 --- a/src/uu/head/src/parse.rs +++ b/src/uu/head/src/parse.rs @@ -43,11 +43,11 @@ pub fn parse_obsolete(src: &str) -> Option // this also saves us 1 heap allocation 'q' => { quiet = true; - verbose = false + verbose = false; } 'v' => { verbose = true; - quiet = false + quiet = false; } 'z' => zero_terminated = true, 'c' => multiplier = Some(1), @@ -58,20 +58,20 @@ pub fn parse_obsolete(src: &str) -> Option _ => return Some(Err(ParseError::Syntax)), } if let Some((_, next)) = chars.next() { - c = next + c = next; } else { break; } } let mut options = Vec::new(); if quiet { - options.push(OsString::from("-q")) + options.push(OsString::from("-q")); } if verbose { - options.push(OsString::from("-v")) + options.push(OsString::from("-v")); } if zero_terminated { - options.push(OsString::from("-z")) + options.push(OsString::from("-z")); } if let Some(n) = multiplier { options.push(OsString::from("-c")); diff --git a/src/uu/ln/src/ln.rs b/src/uu/ln/src/ln.rs index cd2dde5fd..ff9a34d43 100644 --- a/src/uu/ln/src/ln.rs +++ b/src/uu/ln/src/ln.rs @@ -308,7 +308,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings) if is_symlink(target_dir) { if target_dir.is_file() { if let Err(e) = fs::remove_file(target_dir) { - show_error!("Could not update {}: {}", target_dir.quote(), e) + show_error!("Could not update {}: {}", target_dir.quote(), e); }; } if target_dir.is_dir() { @@ -316,7 +316,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings) // considered as a dir // See test_ln::test_symlink_no_deref_dir if let Err(e) = fs::remove_dir(target_dir) { - show_error!("Could not update {}: {}", target_dir.quote(), e) + show_error!("Could not update {}: {}", target_dir.quote(), e); }; } } @@ -402,7 +402,7 @@ fn link(src: &Path, dst: &Path, settings: &Settings) -> Result<()> { if !read_yes() { return Ok(()); } - fs::remove_file(dst)? + fs::remove_file(dst)?; } OverwriteMode::Force => fs::remove_file(dst)?, }; diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index 83a567c4b..687915640 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -118,7 +118,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } if matches.is_present(OPT_T) { - tmpdir = env::temp_dir() + tmpdir = env::temp_dir(); } let res = if dry_run { diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index 9c672782b..ee77b63f4 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -305,7 +305,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UR sourcepath.quote(), targetpath.quote() )) - ) + ); } Ok(()) } @@ -340,7 +340,7 @@ fn rename(from: &Path, to: &Path, b: &Behavior) -> io::Result<()> { // normalize behavior between *nix and windows if from.is_dir() { if is_empty_dir(to) { - fs::remove_dir(to)? + fs::remove_dir(to)?; } else { return Err(io::Error::new(io::ErrorKind::Other, "Directory not empty")); } diff --git a/src/uu/od/src/multifilereader.rs b/src/uu/od/src/multifilereader.rs index 1b3aba03d..7fbd75358 100644 --- a/src/uu/od/src/multifilereader.rs +++ b/src/uu/od/src/multifilereader.rs @@ -60,7 +60,7 @@ impl<'b> MultifileReader<'b> { // then move on the the next file. // This matches the behavior of the original `od` show_error!("{}: {}", fname.maybe_quote(), e); - self.any_err = true + self.any_err = true; } } } diff --git a/src/uu/od/src/parse_formats.rs b/src/uu/od/src/parse_formats.rs index 301bb5154..01dd65e1c 100644 --- a/src/uu/od/src/parse_formats.rs +++ b/src/uu/od/src/parse_formats.rs @@ -138,7 +138,7 @@ pub fn parse_format_flags(args: &[String]) -> Result std::io::Result RngCore for ReadRng { panic!( "reading random bytes from Read implementation failed; error: {}", err - ) + ); }); } diff --git a/src/uu/sort/src/ext_sort.rs b/src/uu/sort/src/ext_sort.rs index 4bef20625..fbb9c16d7 100644 --- a/src/uu/sort/src/ext_sort.rs +++ b/src/uu/sort/src/ext_sort.rs @@ -159,7 +159,7 @@ fn reader_writer< fn sorter(receiver: &Receiver, sender: &SyncSender, settings: &GlobalSettings) { while let Ok(mut payload) = receiver.recv() { payload.with_contents_mut(|contents| { - sort_by(&mut contents.lines, settings, &contents.line_data) + sort_by(&mut contents.lines, settings, &contents.line_data); }); if sender.send(payload).is_err() { // The receiver has gone away, likely because the other thread hit an error. diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 8350cdf30..96d5128f6 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -50,7 +50,7 @@ fn replace_output_file_in_input_files( std::fs::copy(file_path, ©_path) .map_err(|error| SortError::OpenTmpFileFailed { error })?; *file = copy_path.clone().into_os_string(); - copy = Some(copy_path) + copy = Some(copy_path); } } } @@ -187,7 +187,7 @@ fn merge_without_limit>>( file_number, line_idx: 0, receiver, - }) + }); } } diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index e7d7bb03f..239256aae 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -535,7 +535,7 @@ impl<'a> Line<'a> { } Selection::Str(str) => { if selector.needs_selection { - line_data.selections.push(str) + line_data.selections.push(str); } } } @@ -701,9 +701,9 @@ impl<'a> Line<'a> { fn tokenize(line: &str, separator: Option, token_buffer: &mut Vec) { assert!(token_buffer.is_empty()); if let Some(separator) = separator { - tokenize_with_separator(line, separator, token_buffer) + tokenize_with_separator(line, separator, token_buffer); } else { - tokenize_default(line, token_buffer) + tokenize_default(line, token_buffer); } } @@ -1232,7 +1232,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { ), )); } - settings.separator = Some(separator.chars().next().unwrap()) + settings.separator = Some(separator.chars().next().unwrap()); } if let Some(values) = matches.values_of(options::KEY) { @@ -1524,9 +1524,9 @@ fn exec( fn sort_by<'a>(unsorted: &mut Vec>, settings: &GlobalSettings, line_data: &LineData<'a>) { if settings.stable || settings.unique { - unsorted.par_sort_by(|a, b| compare_by(a, b, settings, line_data, line_data)) + unsorted.par_sort_by(|a, b| compare_by(a, b, settings, line_data, line_data)); } else { - unsorted.par_sort_unstable_by(|a, b| compare_by(a, b, settings, line_data, line_data)) + unsorted.par_sort_unstable_by(|a, b| compare_by(a, b, settings, line_data, line_data)); } } diff --git a/src/uu/split/src/platform/unix.rs b/src/uu/split/src/platform/unix.rs index 448b8b782..c05593861 100644 --- a/src/uu/split/src/platform/unix.rs +++ b/src/uu/split/src/platform/unix.rs @@ -55,7 +55,7 @@ impl Drop for WithEnvVarSet { if let Ok(ref prev_value) = self._previous_var_value { env::set_var(&self._previous_var_key, &prev_value); } else { - env::remove_var(&self._previous_var_key) + env::remove_var(&self._previous_var_key); } } } diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index 11f8581be..fd8578faa 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -406,7 +406,7 @@ impl Stater { flag, precision, format: chars[i], - }) + }); } '\\' => { if !use_printf { diff --git a/src/uu/tail/src/parse.rs b/src/uu/tail/src/parse.rs index a788b2c48..1c4f36bbd 100644 --- a/src/uu/tail/src/parse.rs +++ b/src/uu/tail/src/parse.rs @@ -42,11 +42,11 @@ pub fn parse_obsolete(src: &str) -> Option // this also saves us 1 heap allocation 'q' => { quiet = true; - verbose = false + verbose = false; } 'v' => { verbose = true; - quiet = false + quiet = false; } 'z' => zero_terminated = true, 'c' => multiplier = Some(1), @@ -57,20 +57,20 @@ pub fn parse_obsolete(src: &str) -> Option _ => return Some(Err(ParseError::Syntax)), } if let Some((_, next)) = chars.next() { - c = next + c = next; } else { break; } } let mut options = Vec::new(); if quiet { - options.push(OsString::from("-q")) + options.push(OsString::from("-q")); } if verbose { - options.push(OsString::from("-v")) + options.push(OsString::from("-v")); } if zero_terminated { - options.push(OsString::from("-z")) + options.push(OsString::from("-z")); } if let Some(n) = multiplier { options.push(OsString::from("-c")); diff --git a/src/uu/tail/src/tail.rs b/src/uu/tail/src/tail.rs index 7c2652a7b..54808ed34 100644 --- a/src/uu/tail/src/tail.rs +++ b/src/uu/tail/src/tail.rs @@ -102,7 +102,7 @@ impl Settings { if let Some(n) = matches.value_of(options::SLEEP_INT) { let parsed: Option = n.parse().ok(); if let Some(m) = parsed { - settings.sleep_msec = m * 1000 + settings.sleep_msec = m * 1000; } } } diff --git a/src/uu/tee/src/tee.rs b/src/uu/tee/src/tee.rs index 937f06769..8285ac60b 100644 --- a/src/uu/tee/src/tee.rs +++ b/src/uu/tee/src/tee.rs @@ -97,7 +97,7 @@ fn ignore_interrupts() -> Result<()> { fn tee(options: &Options) -> Result<()> { if options.ignore_interrupts { - ignore_interrupts()? + ignore_interrupts()?; } let mut writers: Vec = options .files diff --git a/src/uu/uptime/src/uptime.rs b/src/uu/uptime/src/uptime.rs index a9d971e5b..13ec7fd23 100644 --- a/src/uu/uptime/src/uptime.rs +++ b/src/uu/uptime/src/uptime.rs @@ -178,7 +178,7 @@ fn print_uptime(upsecs: i64) { match updays.cmp(&1) { std::cmp::Ordering::Equal => print!("up {:1} day, {:2}:{:02}, ", updays, uphours, upmins), std::cmp::Ordering::Greater => { - print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins) + print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins); } _ => print!("up {:2}:{:02}, ", uphours, upmins), }; diff --git a/src/uu/wc/src/word_count.rs b/src/uu/wc/src/word_count.rs index 617b811fc..c1dd0c3d3 100644 --- a/src/uu/wc/src/word_count.rs +++ b/src/uu/wc/src/word_count.rs @@ -27,7 +27,7 @@ impl Add for WordCount { impl AddAssign for WordCount { fn add_assign(&mut self, other: Self) { - *self = *self + other + *self = *self + other; } } diff --git a/src/uu/who/src/who.rs b/src/uu/who/src/who.rs index 8df10b745..50dde9de0 100644 --- a/src/uu/who/src/who.rs +++ b/src/uu/who/src/who.rs @@ -351,7 +351,7 @@ impl Who { let records = Utmpx::iter_all_records_from(f).peekable(); if self.include_heading { - self.print_heading() + self.print_heading(); } let cur_tty = if self.my_line_only { current_tty() diff --git a/src/uucore/src/lib/features/fs.rs b/src/uucore/src/lib/features/fs.rs index 680f0f72b..b1b86e73a 100644 --- a/src/uucore/src/lib/features/fs.rs +++ b/src/uucore/src/lib/features/fs.rs @@ -159,7 +159,7 @@ pub fn resolve_relative_path(path: &Path) -> Cow { } Component::CurDir => (), Component::RootDir | Component::Normal(_) | Component::Prefix(_) => { - result.push(comp.as_os_str()) + result.push(comp.as_os_str()); } } } diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index b3ea7e780..8ba7f8fc0 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -156,7 +156,7 @@ impl MountInfo { // but set dev_id if let Ok(stat) = std::fs::metadata(&self.mount_dir) { // Why do we cast this to i32? - self.dev_id = (stat.dev() as i32).to_string() + self.dev_id = (stat.dev() as i32).to_string(); } else { self.dev_id = "".to_string(); } diff --git a/src/uucore/src/lib/features/mode.rs b/src/uucore/src/lib/features/mode.rs index 2206177a3..bf11e481a 100644 --- a/src/uucore/src/lib/features/mode.rs +++ b/src/uucore/src/lib/features/mode.rs @@ -62,7 +62,7 @@ pub fn parse_symbolic( // keep the setgid and setuid bits for directories srwx |= fperm & (0o4000 | 0o2000); } - fperm = (fperm & !mask) | (srwx & mask) + fperm = (fperm & !mask) | (srwx & mask); } _ => unreachable!(), } @@ -113,7 +113,7 @@ fn parse_change(mode: &str, fperm: u32, considering_dir: bool) -> (u32, usize) { 'x' => srwx |= 0o111, 'X' => { if considering_dir || (fperm & 0o0111) != 0 { - srwx |= 0o111 + srwx |= 0o111; } } 's' => srwx |= 0o4000 | 0o2000, diff --git a/src/uucore/src/lib/features/perms.rs b/src/uucore/src/lib/features/perms.rs index 128334f1c..942c67e29 100644 --- a/src/uucore/src/lib/features/perms.rs +++ b/src/uucore/src/lib/features/perms.rs @@ -296,9 +296,9 @@ impl ChownExecutor { } else { "Too many levels of symbolic links".into() } - ) + ); } else { - show_error!("{}", e) + show_error!("{}", e); } continue; } @@ -450,7 +450,7 @@ pub fn chown_base<'a>( .required(true) .takes_value(true) .multiple_occurrences(false), - ) + ); } app = app.arg( Arg::new(options::ARG_FILES) diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs index d92caff75..e6b1ea770 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/base_conv/mod.rs @@ -16,7 +16,7 @@ pub fn arrnum_int_mult(arr_num: &[u8], basenum: u8, base_ten_int_fact: u8) -> Ve new_amount = (u16::from(*u) * fact) + carry; rem = new_amount % base; carry = (new_amount - rem) / base; - ret_rev.push(rem as u8) + ret_rev.push(rem as u8); } None => { while carry != 0 { @@ -119,7 +119,7 @@ pub fn arrnum_int_add(arrnum: &[u8], basenum: u8, base_ten_int_term: u8) -> Vec< new_amount = u16::from(*u) + carry; rem = new_amount % base; carry = (new_amount - rem) / base; - ret_rev.push(rem as u8) + ret_rev.push(rem as u8); } None => { while carry != 0 { @@ -170,7 +170,7 @@ pub fn base_conv_float(src: &[u8], radix_src: u8, _radix_dest: u8) -> f64 { break; } factor /= radix_src_float; - r += factor * f64::from(*u) + r += factor * f64::from(*u); } r } diff --git a/src/uucore/src/lib/features/tokenize/sub.rs b/src/uucore/src/lib/features/tokenize/sub.rs index c869a3564..0c3a68c3c 100644 --- a/src/uucore/src/lib/features/tokenize/sub.rs +++ b/src/uucore/src/lib/features/tokenize/sub.rs @@ -283,10 +283,10 @@ impl SubParser { } } else { if let Some(x) = n_ch { - it.put_back(x) + it.put_back(x); }; if let Some(x) = preface { - it.put_back(x) + it.put_back(x); }; false } diff --git a/src/uucore/src/lib/features/tokenize/unescaped_text.rs b/src/uucore/src/lib/features/tokenize/unescaped_text.rs index ffbcd4afe..a192c757b 100644 --- a/src/uucore/src/lib/features/tokenize/unescaped_text.rs +++ b/src/uucore/src/lib/features/tokenize/unescaped_text.rs @@ -227,7 +227,7 @@ impl UnescapedText { new_vec.extend(tmp_str.bytes()); tmp_str = String::new(); } - UnescapedText::handle_escaped(new_vec, it, subs_mode) + UnescapedText::handle_escaped(new_vec, it, subs_mode); } x if x == '%' && !subs_mode => { if let Some(follow) = it.next() { diff --git a/src/uucore/src/lib/lib.rs b/src/uucore/src/lib/lib.rs index 2bbf85dc1..4c9d6c21d 100644 --- a/src/uucore/src/lib/lib.rs +++ b/src/uucore/src/lib/lib.rs @@ -97,7 +97,7 @@ pub fn get_utility_is_second_arg() -> bool { } pub fn set_utility_is_second_arg() { - crate::macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst) + crate::macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst); } // args_os() can be expensive to call, it copies all of argv before iterating. diff --git a/src/uucore/src/lib/mods/panic.rs b/src/uucore/src/lib/mods/panic.rs index dd0eff6a8..5a1e20d80 100644 --- a/src/uucore/src/lib/mods/panic.rs +++ b/src/uucore/src/lib/mods/panic.rs @@ -36,7 +36,7 @@ pub fn mute_sigpipe_panic() { let hook = panic::take_hook(); panic::set_hook(Box::new(move |info| { if !is_broken_pipe(info) { - hook(info) + hook(info); } })); } diff --git a/tests/by-util/test_chcon.rs b/tests/by-util/test_chcon.rs index 2bdc512d5..82dab9ae3 100644 --- a/tests/by-util/test_chcon.rs +++ b/tests/by-util/test_chcon.rs @@ -461,9 +461,9 @@ fn set_file_context(path: impl AsRef, context: &str) -> Result<(), selinux context, path.display(), r - ) + ); } else { - println!("set_file_context: '{}' => '{}'.", context, path.display()) + println!("set_file_context: '{}' => '{}'.", context, path.display()); } r } diff --git a/tests/by-util/test_chown.rs b/tests/by-util/test_chown.rs index d5ebb4600..0857e5659 100644 --- a/tests/by-util/test_chown.rs +++ b/tests/by-util/test_chown.rs @@ -48,7 +48,7 @@ mod test_passgrp { #[test] fn test_grp2gid() { if cfg!(target_os = "linux") || cfg!(target_os = "android") || cfg!(target_os = "windows") { - assert_eq!(0, grp2gid("root").unwrap()) + assert_eq!(0, grp2gid("root").unwrap()); } else { assert_eq!(0, grp2gid("wheel").unwrap()); } diff --git a/tests/by-util/test_env.rs b/tests/by-util/test_env.rs index 135ee72ef..e1950f0df 100644 --- a/tests/by-util/test_env.rs +++ b/tests/by-util/test_env.rs @@ -187,7 +187,7 @@ fn test_change_directory() { .arg(pwd) .succeeds() .stdout_move_str(); - assert_eq!(out.trim(), temporary_path.as_os_str()) + assert_eq!(out.trim(), temporary_path.as_os_str()); } #[cfg(windows)] diff --git a/tests/by-util/test_ls.rs b/tests/by-util/test_ls.rs index 559fe3f47..5a74ee755 100644 --- a/tests/by-util/test_ls.rs +++ b/tests/by-util/test_ls.rs @@ -1551,7 +1551,7 @@ fn test_ls_inode() { assert!(!re_long.is_match(result.stdout_str())); assert!(!result.stdout_str().contains(inode_long)); - assert_eq!(inode_short, inode_long) + assert_eq!(inode_short, inode_long); } #[test] @@ -1901,7 +1901,7 @@ fn test_ls_version_sort() { assert_eq!( result.stdout_str().split('\n').collect::>(), expected, - ) + ); } #[test] diff --git a/tests/by-util/test_mkdir.rs b/tests/by-util/test_mkdir.rs index f3451fb5e..e1038003b 100644 --- a/tests/by-util/test_mkdir.rs +++ b/tests/by-util/test_mkdir.rs @@ -75,7 +75,7 @@ fn test_symbolic_mode() { ucmd.arg("-m").arg("a=rwx").arg(TEST_DIR1).succeeds(); let perms = at.metadata(TEST_DIR1).permissions().mode(); - assert_eq!(perms, 0o40777) + assert_eq!(perms, 0o40777); } #[test] @@ -85,7 +85,7 @@ fn test_symbolic_alteration() { ucmd.arg("-m").arg("-w").arg(TEST_DIR1).succeeds(); let perms = at.metadata(TEST_DIR1).permissions().mode(); - assert_eq!(perms, 0o40555) + assert_eq!(perms, 0o40555); } #[test] @@ -98,5 +98,5 @@ fn test_multi_symbolic() { .arg(TEST_DIR1) .succeeds(); let perms = at.metadata(TEST_DIR1).permissions().mode(); - assert_eq!(perms, 0o40750) + assert_eq!(perms, 0o40750); } diff --git a/tests/by-util/test_shuf.rs b/tests/by-util/test_shuf.rs index 901b6f8be..86828dc45 100644 --- a/tests/by-util/test_shuf.rs +++ b/tests/by-util/test_shuf.rs @@ -91,7 +91,7 @@ fn test_head_count() { result_seq.iter().all(|x| input_seq.contains(x)), "Output includes element not from input: {}", result.stdout_str() - ) + ); } #[test] @@ -129,7 +129,7 @@ fn test_repeat() { .iter() .filter(|x| !input_seq.contains(x)) .collect::>() - ) + ); } #[test] diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index d472d4b5e..5cf622fb8 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -155,7 +155,7 @@ fn test_multiple_decimals_general() { test_helper( "multiple_decimals_general", &["-g", "--general-numeric-sort", "--sort=general-numeric"], - ) + ); } #[test] @@ -163,7 +163,7 @@ fn test_multiple_decimals_numeric() { test_helper( "multiple_decimals_numeric", &["-n", "--numeric-sort", "--sort=numeric"], - ) + ); } #[test] @@ -171,7 +171,7 @@ fn test_numeric_with_trailing_invalid_chars() { test_helper( "numeric_trailing_chars", &["-n", "--numeric-sort", "--sort=numeric"], - ) + ); } #[test] @@ -588,7 +588,7 @@ fn test_keys_with_options_blanks_start() { #[test] fn test_keys_blanks_with_char_idx() { - test_helper("keys_blanks", &["-k 1.2b"]) + test_helper("keys_blanks", &["-k 1.2b"]); } #[test] @@ -648,7 +648,7 @@ fn test_keys_negative_size_match() { #[test] fn test_keys_ignore_flag() { - test_helper("keys_ignore_flag", &["-k 1n -b"]) + test_helper("keys_ignore_flag", &["-k 1n -b"]); } #[test] diff --git a/tests/by-util/test_touch.rs b/tests/by-util/test_touch.rs index 983d14fe2..e661907cc 100644 --- a/tests/by-util/test_touch.rs +++ b/tests/by-util/test_touch.rs @@ -27,7 +27,7 @@ fn get_symlink_times(at: &AtPath, path: &str) -> (FileTime, FileTime) { } fn set_file_times(at: &AtPath, path: &str, atime: FileTime, mtime: FileTime) { - filetime::set_file_times(&at.plus_as_string(path), atime, mtime).unwrap() + filetime::set_file_times(&at.plus_as_string(path), atime, mtime).unwrap(); } // Adjusts for local timezone diff --git a/tests/common/util.rs b/tests/common/util.rs index f86cf2d26..5b293c216 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -241,7 +241,7 @@ impl CmdResult { "stdout was {}\nExpected any of {:#?}", self.stdout_str(), expected - ) + ); } self } @@ -419,14 +419,14 @@ impl CmdResult { pub fn stdout_matches(&self, regex: ®ex::Regex) -> &CmdResult { if !regex.is_match(self.stdout_str().trim()) { - panic!("Stdout does not match regex:\n{}", self.stdout_str()) + panic!("Stdout does not match regex:\n{}", self.stdout_str()); } self } pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &CmdResult { if regex.is_match(self.stdout_str().trim()) { - panic!("Stdout matches regex:\n{}", self.stdout_str()) + panic!("Stdout matches regex:\n{}", self.stdout_str()); } self } @@ -1059,7 +1059,7 @@ impl UCommand { .write_all(input); if !self.ignore_stdin_write_error { if let Err(e) = write_result { - panic!("failed to write to stdin of child: {}", e) + panic!("failed to write to stdin of child: {}", e); } } } From cf24620d3d1785299cbc84e066ceb5882862c6e7 Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 14:04:13 +0100 Subject: [PATCH 08/10] remove 'let and return' --- src/uu/tr/src/convert.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/uu/tr/src/convert.rs b/src/uu/tr/src/convert.rs index b3d986f1e..00656ca49 100644 --- a/src/uu/tr/src/convert.rs +++ b/src/uu/tr/src/convert.rs @@ -28,10 +28,9 @@ fn parse_octal(input: &str) -> IResult<&str, char> { } pub fn reduce_octal_to_char(input: &str) -> String { - let result = many0(alt((parse_octal, anychar)))(input) + many0(alt((parse_octal, anychar)))(input) .map(|(_, r)| r) .unwrap() .into_iter() - .collect(); - result + .collect() } From 2f85610cc34bc68fe883eee975996868cf02487d Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 14:07:07 +0100 Subject: [PATCH 09/10] remove explicit iter loops --- src/uu/cp/src/cp.rs | 2 +- src/uu/dd/src/dd.rs | 2 +- src/uu/df/src/df.rs | 2 +- src/uu/dirname/src/dirname.rs | 2 +- src/uu/du/src/du.rs | 2 +- src/uu/expand/src/expand.rs | 2 +- src/uu/pr/src/pr.rs | 2 +- src/uu/sort/src/sort.rs | 2 +- src/uu/unexpand/src/unexpand.rs | 2 +- src/uucore/src/lib/features/fs.rs | 2 +- src/uucore/src/lib/features/memo.rs | 2 +- tests/by-util/test_relpath.rs | 8 ++++---- tests/by-util/test_tee.rs | 4 ++-- 13 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 49cecfc00..871017f26 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -741,7 +741,7 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec( let mut blocks = block(&buf, cbs, rstat); if let Some(ct) = i.cflags.ctable { - for buf in blocks.iter_mut() { + for buf in &mut blocks { apply_conversion(buf, ct); } } diff --git a/src/uu/df/src/df.rs b/src/uu/df/src/df.rs index 54b39cb15..b9512f6d8 100644 --- a/src/uu/df/src/df.rs +++ b/src/uu/df/src/df.rs @@ -367,7 +367,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } } println!(); - for fs in fs_list.iter() { + for fs in &fs_list { print!("{0: <16} ", fs.mount_info.dev_name); if opt.show_fs_type { print!("{0: <5} ", fs.mount_info.fs_type); diff --git a/src/uu/dirname/src/dirname.rs b/src/uu/dirname/src/dirname.rs index 343007d29..e47177ea2 100644 --- a/src/uu/dirname/src/dirname.rs +++ b/src/uu/dirname/src/dirname.rs @@ -56,7 +56,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .collect(); if !dirnames.is_empty() { - for path in dirnames.iter() { + for path in &dirnames { let p = Path::new(path); match p.parent() { Some(d) => { diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index e95541cac..72a5f771f 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -853,7 +853,7 @@ mod test_du { (Some("K".to_string()), 1024), (None, 1024), ]; - for it in test_data.iter() { + for it in &test_data { assert_eq!(read_block_size(it.0.as_deref()), it.1); } } diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index ebddaa690..8e4bf43b8 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -278,7 +278,7 @@ fn expand(options: &Options) -> std::io::Result<()> { let ts = options.tabstops.as_ref(); let mut buf = Vec::new(); - for file in options.files.iter() { + for file in &options.files { let mut fh = open(file); while match fh.read_until(b'\n', &mut buf) { diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 561998b36..6e0cc76e0 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -1007,7 +1007,7 @@ fn mpr(paths: &[String], options: &OutputOptions) -> Result { let mut lines = Vec::new(); let mut page_counter = start_page; - for (_key, file_line_group) in file_line_groups.into_iter() { + for (_key, file_line_group) in &file_line_groups { for file_line in file_line_group { if let Err(e) = file_line.line_content { return Err(e.into()); diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 239256aae..e9177654e 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -571,7 +571,7 @@ impl<'a> Line<'a> { let mut fields = vec![]; tokenize(self.line, settings.separator, &mut fields); - for selector in settings.selectors.iter() { + for selector in &settings.selectors { let mut selection = selector.get_range(self.line, Some(&fields)); match selector.settings.mode { SortMode::Numeric | SortMode::HumanNumeric => { diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index a1c5a91ef..3b419d854 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -249,7 +249,7 @@ fn unexpand(options: &Options) -> std::io::Result<()> { let mut buf = Vec::new(); let lastcol = if ts.len() > 1 { *ts.last().unwrap() } else { 0 }; - for file in options.files.iter() { + for file in &options.files { let mut fh = open(file); while match fh.read_until(b'\n', &mut buf) { diff --git a/src/uucore/src/lib/features/fs.rs b/src/uucore/src/lib/features/fs.rs index b1b86e73a..ccfd8318c 100644 --- a/src/uucore/src/lib/features/fs.rs +++ b/src/uucore/src/lib/features/fs.rs @@ -500,7 +500,7 @@ mod tests { #[test] fn test_normalize_path() { - for test in NORMALIZE_PATH_TESTS.iter() { + for test in &NORMALIZE_PATH_TESTS { let path = Path::new(test.path); let normalized = normalize_path(path); assert_eq!( diff --git a/src/uucore/src/lib/features/memo.rs b/src/uucore/src/lib/features/memo.rs index 232ead2ae..f2d1a33d9 100644 --- a/src/uucore/src/lib/features/memo.rs +++ b/src/uucore/src/lib/features/memo.rs @@ -67,7 +67,7 @@ impl Memo { pm } pub fn apply(&self, pf_args_it: &mut Peekable>) { - for tkn in self.tokens.iter() { + for tkn in &self.tokens { tkn.print(pf_args_it); } } diff --git a/tests/by-util/test_relpath.rs b/tests/by-util/test_relpath.rs index 44a685c90..5f7d4fccf 100644 --- a/tests/by-util/test_relpath.rs +++ b/tests/by-util/test_relpath.rs @@ -74,7 +74,7 @@ fn test_relpath_with_from_no_d() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; - for test in TESTS.iter() { + for test in &TESTS { let from: &str = &convert_path(test.from); let to: &str = &convert_path(test.to); let expected: &str = &convert_path(test.expected); @@ -96,7 +96,7 @@ fn test_relpath_with_from_with_d() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; - for test in TESTS.iter() { + for test in &TESTS { let from: &str = &convert_path(test.from); let to: &str = &convert_path(test.to); let pwd = at.as_string(); @@ -132,7 +132,7 @@ fn test_relpath_no_from_no_d() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; - for test in TESTS.iter() { + for test in &TESTS { let to: &str = &convert_path(test.to); at.mkdir_all(to); @@ -150,7 +150,7 @@ fn test_relpath_no_from_with_d() { let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; - for test in TESTS.iter() { + for test in &TESTS { let to: &str = &convert_path(test.to); let pwd = at.as_string(); at.mkdir_all(to); diff --git a/tests/by-util/test_tee.rs b/tests/by-util/test_tee.rs index 0f41d7db7..17e3c05cf 100644 --- a/tests/by-util/test_tee.rs +++ b/tests/by-util/test_tee.rs @@ -9,7 +9,7 @@ fn test_tee_processing_multiple_operands() { // POSIX says: "Processing of at least 13 file operands shall be supported." let content = "tee_sample_content"; - for &n in [1, 2, 12, 13].iter() { + for &n in &[1, 2, 12, 13] { let files = (1..=n).map(|x| x.to_string()).collect::>(); let (at, mut ucmd) = at_and_ucmd!(); @@ -18,7 +18,7 @@ fn test_tee_processing_multiple_operands() { .succeeds() .stdout_is(content); - for file in files.iter() { + for file in &files { assert!(at.file_exists(file)); assert_eq!(at.read(file), content); } From ba45fe312abffe58241d1bb031e024c602a1dd6e Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 14:59:31 +0100 Subject: [PATCH 10/10] use 'Self' and derive 'Default' where possible --- src/uu/base32/src/base_common.rs | 4 +- src/uu/cp/src/cp.rs | 54 +++---- src/uu/csplit/src/csplit.rs | 8 +- src/uu/csplit/src/csplit_error.rs | 2 +- src/uu/csplit/src/patterns.rs | 8 +- src/uu/csplit/src/split_name.rs | 4 +- src/uu/date/src/date.rs | 16 +- src/uu/dd/src/dd.rs | 8 +- src/uu/dd/src/parseargs.rs | 6 +- src/uu/df/src/df.rs | 18 +-- src/uu/du/src/du.rs | 12 +- src/uu/expand/src/expand.rs | 4 +- src/uu/expr/src/syntax_tree.rs | 12 +- src/uu/expr/src/tokens.rs | 8 +- src/uu/factor/sieve.rs | 28 ++-- src/uu/factor/src/factor.rs | 16 +- src/uu/factor/src/miller_rabin.rs | 2 +- src/uu/factor/src/numeric/montgomery.rs | 2 +- src/uu/factor/src/numeric/traits.rs | 2 +- src/uu/hashsum/src/digest.rs | 6 +- src/uu/head/src/head.rs | 4 +- src/uu/head/src/take.rs | 4 +- src/uu/join/src/join.rs | 18 +-- src/uu/ls/src/ls.rs | 4 +- src/uu/ls/src/quoting_style.rs | 4 +- src/uu/od/src/formatteriteminfo.rs | 2 +- src/uu/od/src/inputoffset.rs | 4 +- src/uu/od/src/mockstream.rs | 4 +- src/uu/od/src/od.rs | 4 +- src/uu/od/src/output_info.rs | 8 +- src/uu/od/src/parse_formats.rs | 7 +- src/uu/od/src/partialreader.rs | 2 +- src/uu/od/src/peekreader.rs | 2 +- src/uu/pr/src/pr.rs | 10 +- src/uu/ptx/src/ptx.rs | 8 +- src/uu/runcon/src/errors.rs | 8 +- src/uu/seq/src/extendedbigdecimal.rs | 12 +- src/uu/seq/src/extendedbigint.rs | 22 +-- src/uu/seq/src/number.rs | 12 +- src/uu/shred/src/shred.rs | 4 +- src/uu/shuf/src/rand_read_adapter.rs | 4 +- src/uu/sort/src/chunks.rs | 2 +- src/uu/sort/src/merge.rs | 4 +- src/uu/sort/src/numeric_str_cmp.rs | 8 +- src/uu/sort/src/sort.rs | 15 +- src/uu/split/src/platform/unix.rs | 8 +- src/uu/split/src/split.rs | 20 +-- src/uu/stat/src/stat.rs | 10 +- src/uu/stdbuf/src/stdbuf.rs | 2 +- src/uu/tail/src/platform/unix.rs | 4 +- src/uu/tail/src/tail.rs | 4 +- src/uu/test/src/parser.rs | 52 +++---- src/uu/timeout/src/timeout.rs | 4 +- src/uu/tr/src/operation.rs | 139 ++++++++---------- src/uu/tsort/src/tsort.rs | 9 +- src/uu/unexpand/src/unexpand.rs | 4 +- src/uu/wc/src/wc.rs | 6 +- src/uu/yes/src/splice.rs | 2 +- src/uucore/src/lib/features/encoding.rs | 2 +- src/uucore/src/lib/features/entries.rs | 4 +- src/uucore/src/lib/features/fsext.rs | 12 +- src/uucore/src/lib/features/memo.rs | 6 +- src/uucore/src/lib/features/process.rs | 4 +- src/uucore/src/lib/features/ringbuffer.rs | 8 +- .../formatters/cninetyninehexfloatf.rs | 5 +- .../tokenize/num_format/formatters/decf.rs | 4 +- .../num_format/formatters/float_common.rs | 4 +- .../tokenize/num_format/formatters/floatf.rs | 5 +- .../tokenize/num_format/formatters/intf.rs | 15 +- .../tokenize/num_format/formatters/scif.rs | 5 +- src/uucore/src/lib/features/tokenize/sub.rs | 26 ++-- .../lib/features/tokenize/unescaped_text.rs | 17 ++- src/uucore/src/lib/features/utmpx.rs | 2 +- src/uucore/src/lib/mods/error.rs | 10 +- src/uucore/src/lib/mods/ranges.rs | 14 +- src/uucore/src/lib/parser/parse_size.rs | 8 +- tests/by-util/test_kill.rs | 4 +- tests/by-util/test_split.rs | 10 +- tests/common/util.rs | 94 ++++++------ 79 files changed, 445 insertions(+), 474 deletions(-) diff --git a/src/uu/base32/src/base_common.rs b/src/uu/base32/src/base_common.rs index 35295a295..39a46e315 100644 --- a/src/uu/base32/src/base_common.rs +++ b/src/uu/base32/src/base_common.rs @@ -38,7 +38,7 @@ pub mod options { } impl Config { - pub fn from(options: &clap::ArgMatches) -> UResult { + pub fn from(options: &clap::ArgMatches) -> UResult { let file: Option = match options.values_of(options::FILE) { Some(mut values) => { let name = values.next().unwrap(); @@ -76,7 +76,7 @@ impl Config { }) .transpose()?; - Ok(Config { + Ok(Self { decode: options.is_present(options::DECODE), ignore_garbage: options.is_present(options::IGNORE_GARBAGE), wrap_cols: cols, diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 871017f26..374ab2f81 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -495,43 +495,43 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } impl ClobberMode { - fn from_matches(matches: &ArgMatches) -> ClobberMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::FORCE) { - ClobberMode::Force + Self::Force } else if matches.is_present(options::REMOVE_DESTINATION) { - ClobberMode::RemoveDestination + Self::RemoveDestination } else { - ClobberMode::Standard + Self::Standard } } } impl OverwriteMode { - fn from_matches(matches: &ArgMatches) -> OverwriteMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::INTERACTIVE) { - OverwriteMode::Interactive(ClobberMode::from_matches(matches)) + Self::Interactive(ClobberMode::from_matches(matches)) } else if matches.is_present(options::NO_CLOBBER) { - OverwriteMode::NoClobber + Self::NoClobber } else { - OverwriteMode::Clobber(ClobberMode::from_matches(matches)) + Self::Clobber(ClobberMode::from_matches(matches)) } } } impl CopyMode { - fn from_matches(matches: &ArgMatches) -> CopyMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::LINK) { - CopyMode::Link + Self::Link } else if matches.is_present(options::SYMBOLIC_LINK) { - CopyMode::SymLink + Self::SymLink } else if matches.is_present(options::SPARSE) { - CopyMode::Sparse + Self::Sparse } else if matches.is_present(options::UPDATE) { - CopyMode::Update + Self::Update } else if matches.is_present(options::ATTRIBUTES_ONLY) { - CopyMode::AttrOnly + Self::AttrOnly } else { - CopyMode::Copy + Self::Copy } } } @@ -539,16 +539,16 @@ impl CopyMode { impl FromStr for Attribute { type Err = Error; - fn from_str(value: &str) -> CopyResult { + fn from_str(value: &str) -> CopyResult { Ok(match &*value.to_lowercase() { - "mode" => Attribute::Mode, + "mode" => Self::Mode, #[cfg(unix)] - "ownership" => Attribute::Ownership, - "timestamps" => Attribute::Timestamps, + "ownership" => Self::Ownership, + "timestamps" => Self::Timestamps, #[cfg(feature = "feat_selinux")] - "context" => Attribute::Context, - "links" => Attribute::Links, - "xattr" => Attribute::Xattr, + "context" => Self::Context, + "links" => Self::Links, + "xattr" => Self::Xattr, _ => { return Err(Error::InvalidArgument(format!( "invalid attribute {}", @@ -577,7 +577,7 @@ fn add_all_attributes() -> Vec { } impl Options { - fn from_matches(matches: &ArgMatches) -> CopyResult { + fn from_matches(matches: &ArgMatches) -> CopyResult { let not_implemented_opts = vec![ options::COPY_CONTENTS, options::SPARSE, @@ -646,7 +646,7 @@ impl Options { // if not executed first. preserve_attributes.sort_unstable(); - let options = Options { + let options = Self { attributes_only: matches.is_present(options::ATTRIBUTES_ONLY), copy_contents: matches.is_present(options::COPY_CONTENTS), copy_mode: CopyMode::from_matches(matches), @@ -703,11 +703,11 @@ impl TargetType { /// /// Treat target as a dir if we have multiple sources or the target /// exists and already is a directory - fn determine(sources: &[Source], target: &TargetSlice) -> TargetType { + fn determine(sources: &[Source], target: &TargetSlice) -> Self { if sources.len() > 1 || target.is_dir() { - TargetType::Directory + Self::Directory } else { - TargetType::File + Self::File } } } diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index 6f79b69f2..da0d24727 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -57,13 +57,13 @@ pub struct CsplitOptions { } impl CsplitOptions { - fn new(matches: &ArgMatches) -> CsplitOptions { + fn new(matches: &ArgMatches) -> Self { let keep_files = matches.is_present(options::KEEP_FILES); let quiet = matches.is_present(options::QUIET); let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES); let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED); - CsplitOptions { + Self { split_name: crash_if_err!( 1, SplitName::new( @@ -477,8 +477,8 @@ impl InputSplitter where I: Iterator)>, { - fn new(iter: I) -> InputSplitter { - InputSplitter { + fn new(iter: I) -> Self { + Self { iter, buffer: Vec::new(), rewind: false, diff --git a/src/uu/csplit/src/csplit_error.rs b/src/uu/csplit/src/csplit_error.rs index 53d48a026..b81a331a2 100644 --- a/src/uu/csplit/src/csplit_error.rs +++ b/src/uu/csplit/src/csplit_error.rs @@ -35,7 +35,7 @@ pub enum CsplitError { impl From for CsplitError { fn from(error: io::Error) -> Self { - CsplitError::IoError(error) + Self::IoError(error) } } diff --git a/src/uu/csplit/src/patterns.rs b/src/uu/csplit/src/patterns.rs index 6689b79de..0346ed381 100644 --- a/src/uu/csplit/src/patterns.rs +++ b/src/uu/csplit/src/patterns.rs @@ -44,8 +44,8 @@ pub enum ExecutePattern { impl ExecutePattern { pub fn iter(&self) -> ExecutePatternIter { match self { - ExecutePattern::Times(n) => ExecutePatternIter::new(Some(*n)), - ExecutePattern::Always => ExecutePatternIter::new(None), + Self::Times(n) => ExecutePatternIter::new(Some(*n)), + Self::Always => ExecutePatternIter::new(None), } } } @@ -56,8 +56,8 @@ pub struct ExecutePatternIter { } impl ExecutePatternIter { - fn new(max: Option) -> ExecutePatternIter { - ExecutePatternIter { max, cur: 0 } + fn new(max: Option) -> Self { + Self { max, cur: 0 } } } diff --git a/src/uu/csplit/src/split_name.rs b/src/uu/csplit/src/split_name.rs index 44ea2a5af..b1f4f1505 100644 --- a/src/uu/csplit/src/split_name.rs +++ b/src/uu/csplit/src/split_name.rs @@ -29,7 +29,7 @@ impl SplitName { prefix_opt: Option, format_opt: Option, n_digits_opt: Option, - ) -> Result { + ) -> Result { // get the prefix let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); // the width for the split offset @@ -231,7 +231,7 @@ impl SplitName { } }; - Ok(SplitName { fn_split_name }) + Ok(Self { fn_split_name }) } /// Returns the filename of the i-th split. diff --git a/src/uu/date/src/date.rs b/src/uu/date/src/date.rs index 49090f0ff..5a88225bb 100644 --- a/src/uu/date/src/date.rs +++ b/src/uu/date/src/date.rs @@ -111,11 +111,11 @@ enum Iso8601Format { impl<'a> From<&'a str> for Iso8601Format { fn from(s: &str) -> Self { match s { - HOURS | HOUR => Iso8601Format::Hours, - MINUTES | MINUTE => Iso8601Format::Minutes, - SECONDS | SECOND => Iso8601Format::Seconds, - NS => Iso8601Format::Ns, - DATE => Iso8601Format::Date, + HOURS | HOUR => Self::Hours, + MINUTES | MINUTE => Self::Minutes, + SECONDS | SECOND => Self::Seconds, + NS => Self::Ns, + DATE => Self::Date, // Should be caught by clap _ => panic!("Invalid format: {}", s), } @@ -131,9 +131,9 @@ enum Rfc3339Format { impl<'a> From<&'a str> for Rfc3339Format { fn from(s: &str) -> Self { match s { - DATE => Rfc3339Format::Date, - SECONDS | SECOND => Rfc3339Format::Seconds, - NS => Rfc3339Format::Ns, + DATE => Self::Date, + SECONDS | SECOND => Self::Seconds, + NS => Self::Ns, // Should be caught by clap _ => panic!("Invalid format: {}", s), } diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 7640cadaf..54e3190ce 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -69,7 +69,7 @@ impl Input { let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?; let count = parseargs::parse_count(&iflags, matches)?; - let mut i = Input { + let mut i = Self { src: io::stdin(), non_ascii, ibs, @@ -157,7 +157,7 @@ impl Input { .map_err_context(|| "failed to seek in input file".to_string())?; } - let i = Input { + let i = Self { src, non_ascii, ibs, @@ -306,7 +306,7 @@ impl OutputTrait for Output { .map_err_context(|| String::from("write error"))?; } - Ok(Output { dst, obs, cflags }) + Ok(Self { dst, obs, cflags }) } fn fsync(&mut self) -> io::Result<()> { @@ -497,7 +497,7 @@ impl OutputTrait for Output { .map_err_context(|| "failed to seek in output file".to_string())?; } - Ok(Output { dst, obs, cflags }) + Ok(Self { dst, obs, cflags }) } else { // The following error should only occur if someone // mistakenly calls Output::::new() without checking diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index c790de41f..d85a7fcc7 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -296,9 +296,9 @@ impl std::str::FromStr for StatusLevel { fn from_str(s: &str) -> Result { match s { - "none" => Ok(StatusLevel::None), - "noxfer" => Ok(StatusLevel::Noxfer), - "progress" => Ok(StatusLevel::Progress), + "none" => Ok(Self::None), + "noxfer" => Ok(Self::Noxfer), + "progress" => Ok(Self::Progress), _ => Err(ParseError::StatusLevelNotRecognized(s.to_string())), } } diff --git a/src/uu/df/src/df.rs b/src/uu/df/src/df.rs index b9512f6d8..77deeb6df 100644 --- a/src/uu/df/src/df.rs +++ b/src/uu/df/src/df.rs @@ -52,6 +52,7 @@ static OPT_EXCLUDE_TYPE: &str = "exclude-type"; /// Store names of file systems as a selector. /// Note: `exclude` takes priority over `include`. +#[derive(Default)] struct FsSelector { include: HashSet, exclude: HashSet, @@ -79,11 +80,8 @@ fn usage() -> String { } impl FsSelector { - fn new() -> FsSelector { - FsSelector { - include: HashSet::new(), - exclude: HashSet::new(), - } + fn new() -> Self { + Self::default() } #[inline(always)] @@ -105,8 +103,8 @@ impl FsSelector { } impl Options { - fn new() -> Options { - Options { + fn new() -> Self { + Self { show_local_fs: false, show_all_fs: false, show_listed_fs: false, @@ -124,7 +122,7 @@ impl Options { impl Filesystem { // TODO: resolve uuid in `mount_info.dev_name` if exists - fn new(mount_info: MountInfo) -> Option { + fn new(mount_info: MountInfo) -> Option { let _stat_path = if !mount_info.mount_dir.is_empty() { mount_info.mount_dir.clone() } else { @@ -145,14 +143,14 @@ impl Filesystem { if statfs_fn(path.as_ptr(), &mut statvfs) < 0 { None } else { - Some(Filesystem { + Some(Self { mount_info, usage: FsUsage::new(statvfs), }) } } #[cfg(windows)] - Some(Filesystem { + Some(Self { mount_info, usage: FsUsage::new(Path::new(&_stat_path)), }) diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index 72a5f771f..16e1d166f 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -114,7 +114,7 @@ struct Stat { } impl Stat { - fn new(path: PathBuf, options: &Options) -> Result { + fn new(path: PathBuf, options: &Options) -> Result { let metadata = if options.dereference { fs::metadata(&path)? } else { @@ -127,7 +127,7 @@ impl Stat { dev_id: metadata.dev(), }; #[cfg(not(windows))] - return Ok(Stat { + return Ok(Self { path, is_dir: metadata.is_dir(), size: metadata.len(), @@ -815,9 +815,9 @@ impl FromStr for Threshold { let size = u64::try_from(parse_size(&s[offset..])?).unwrap(); if s.starts_with('-') { - Ok(Threshold::Upper(size)) + Ok(Self::Upper(size)) } else { - Ok(Threshold::Lower(size)) + Ok(Self::Lower(size)) } } } @@ -825,8 +825,8 @@ impl FromStr for Threshold { impl Threshold { fn should_exclude(&self, size: u64) -> bool { match *self { - Threshold::Upper(threshold) => size > threshold, - Threshold::Lower(threshold) => size < threshold, + Self::Upper(threshold) => size > threshold, + Self::Lower(threshold) => size < threshold, } } } diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 8e4bf43b8..fd7876ad1 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -133,7 +133,7 @@ struct Options { } impl Options { - fn new(matches: &ArgMatches) -> Options { + fn new(matches: &ArgMatches) -> Self { let (remaining_mode, tabstops) = match matches.value_of(options::TABS) { Some(s) => tabstops_parse(s), None => (RemainingMode::None, vec![DEFAULT_TABSTOP]), @@ -160,7 +160,7 @@ impl Options { None => vec!["-".to_owned()], }; - Options { + Self { files, tabstops, tspaces, diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index 3c78358dc..8894f87fb 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -66,23 +66,23 @@ impl AstNode { } } - fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { - Box::new(AstNode::Node { + fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { + Box::new(Self::Node { token_idx, op_type: op_type.into(), operands, }) } - fn new_leaf(token_idx: usize, value: &str) -> Box { - Box::new(AstNode::Leaf { + fn new_leaf(token_idx: usize, value: &str) -> Box { + Box::new(Self::Leaf { token_idx, value: value.into(), }) } pub fn evaluate(&self) -> Result { match self { - AstNode::Leaf { value, .. } => Ok(value.clone()), - AstNode::Node { op_type, .. } => match self.operand_values() { + Self::Leaf { value, .. } => Ok(value.clone()), + Self::Node { op_type, .. } => match self.operand_values() { Err(reason) => Err(reason), Ok(operand_values) => match op_type.as_ref() { "+" => { diff --git a/src/uu/expr/src/tokens.rs b/src/uu/expr/src/tokens.rs index a80ad4a60..27912d006 100644 --- a/src/uu/expr/src/tokens.rs +++ b/src/uu/expr/src/tokens.rs @@ -42,25 +42,25 @@ pub enum Token { } impl Token { fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self { - Token::InfixOp { + Self::InfixOp { left_assoc, precedence, value: v.into(), } } fn new_value(v: &str) -> Self { - Token::Value { value: v.into() } + Self::Value { value: v.into() } } fn is_infix_plus(&self) -> bool { match self { - Token::InfixOp { value, .. } => value == "+", + Self::InfixOp { value, .. } => value == "+", _ => false, } } fn is_a_number(&self) -> bool { match self { - Token::Value { value, .. } => value.parse::().is_ok(), + Self::Value { value, .. } => value.parse::().is_ok(), _ => false, } } diff --git a/src/uu/factor/sieve.rs b/src/uu/factor/sieve.rs index f783c2d98..e7d499151 100644 --- a/src/uu/factor/sieve.rs +++ b/src/uu/factor/sieve.rs @@ -15,6 +15,7 @@ use std::slice::Iter; /// This is a reasonably efficient implementation based on /// O'Neill, M. E. "[The Genuine Sieve of Eratosthenes.](http://dx.doi.org/10.1017%2FS0956796808007004)" /// Journal of Functional Programming, Volume 19, Issue 1, 2009, pp. 95--106. +#[derive(Default)] pub struct Sieve { inner: Wheel, filts: PrimeHeap, @@ -58,23 +59,20 @@ impl Iterator for Sieve { } impl Sieve { - fn new() -> Sieve { - Sieve { - inner: Wheel::new(), - filts: PrimeHeap::new(), - } + fn new() -> Self { + Self::default() } #[allow(dead_code)] #[inline] pub fn primes() -> PrimeSieve { - INIT_PRIMES.iter().copied().chain(Sieve::new()) + INIT_PRIMES.iter().copied().chain(Self::new()) } #[allow(dead_code)] #[inline] pub fn odd_primes() -> PrimeSieve { - INIT_PRIMES[1..].iter().copied().chain(Sieve::new()) + INIT_PRIMES[1..].iter().copied().chain(Self::new()) } } @@ -106,14 +104,20 @@ impl Iterator for Wheel { impl Wheel { #[inline] - fn new() -> Wheel { - Wheel { + fn new() -> Self { + Self { next: 11u64, increment: WHEEL_INCS.iter().cycle(), } } } +impl Default for Wheel { + fn default() -> Self { + Self::new() + } +} + /// The increments of a wheel of circumference 210 /// (i.e., a wheel that skips all multiples of 2, 3, 5, 7) const WHEEL_INCS: &[u64] = &[ @@ -124,16 +128,12 @@ const INIT_PRIMES: &[u64] = &[2, 3, 5, 7]; /// A min-heap of "infinite lists" of prime multiples, where a list is /// represented as (head, increment). -#[derive(Debug)] +#[derive(Debug, Default)] struct PrimeHeap { data: Vec<(u64, u64)>, } impl PrimeHeap { - fn new() -> PrimeHeap { - PrimeHeap { data: Vec::new() } - } - fn peek(&self) -> Option<(u64, u64)> { if let Some(&(x, y)) = self.data.get(0) { Some((x, y)) diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index 151aa74a9..c776f95ea 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table}; type Exponent = u8; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); // spell-checker:ignore (names) ErdÅ‘s–Kac * ErdÅ‘s Kac @@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); const NUM_FACTORS_INLINE: usize = 5; impl Decomposition { - fn one() -> Decomposition { - Decomposition(SmallVec::new()) + fn one() -> Self { + Self::default() } fn add(&mut self, factor: u64, exp: Exponent) { @@ -51,7 +51,7 @@ impl Decomposition { } impl PartialEq for Decomposition { - fn eq(&self, other: &Decomposition) -> bool { + fn eq(&self, other: &Self) -> bool { for p in &self.0 { if other.get(p.0) != Some(p) { return false; @@ -73,8 +73,8 @@ impl Eq for Decomposition {} pub struct Factors(RefCell); impl Factors { - pub fn one() -> Factors { - Factors(RefCell::new(Decomposition::one())) + pub fn one() -> Self { + Self(RefCell::new(Decomposition::one())) } pub fn add(&mut self, prime: u64, exp: Exponent) { @@ -286,9 +286,9 @@ impl quickcheck::Arbitrary for Factors { impl std::ops::BitXor for Factors { type Output = Self; - fn bitxor(self, rhs: Exponent) -> Factors { + fn bitxor(self, rhs: Exponent) -> Self { debug_assert_ne!(rhs, 0); - let mut r = Factors::one(); + let mut r = Self::one(); for (p, e) in self.0.borrow().0.iter() { r.add(*p, rhs * e); } diff --git a/src/uu/factor/src/miller_rabin.rs b/src/uu/factor/src/miller_rabin.rs index d336188a5..b5a01735a 100644 --- a/src/uu/factor/src/miller_rabin.rs +++ b/src/uu/factor/src/miller_rabin.rs @@ -42,7 +42,7 @@ pub(crate) enum Result { impl Result { pub(crate) fn is_prime(&self) -> bool { - *self == Result::Prime + *self == Self::Prime } } diff --git a/src/uu/factor/src/numeric/montgomery.rs b/src/uu/factor/src/numeric/montgomery.rs index 485025d87..504e6a09b 100644 --- a/src/uu/factor/src/numeric/montgomery.rs +++ b/src/uu/factor/src/numeric/montgomery.rs @@ -106,7 +106,7 @@ impl Arithmetic for Montgomery { let n = T::from_u64(n); let a = modular_inverse(n).wrapping_neg(); debug_assert_eq!(n.wrapping_mul(&a), T::one().wrapping_neg()); - Montgomery { a, n } + Self { a, n } } fn modulus(&self) -> u64 { diff --git a/src/uu/factor/src/numeric/traits.rs b/src/uu/factor/src/numeric/traits.rs index 2e9167e0b..1dc681976 100644 --- a/src/uu/factor/src/numeric/traits.rs +++ b/src/uu/factor/src/numeric/traits.rs @@ -61,7 +61,7 @@ macro_rules! double_int { fn as_double_width(self) -> $y { self as _ } - fn from_double_width(n: $y) -> $x { + fn from_double_width(n: $y) -> Self { n as _ } } diff --git a/src/uu/hashsum/src/digest.rs b/src/uu/hashsum/src/digest.rs index 4b6b5f6d2..3176f34b5 100644 --- a/src/uu/hashsum/src/digest.rs +++ b/src/uu/hashsum/src/digest.rs @@ -40,7 +40,7 @@ pub trait Digest { impl Digest for md5::Context { fn new() -> Self { - md5::Context::new() + Self::new() } fn input(&mut self, input: &[u8]) { @@ -52,7 +52,7 @@ impl Digest for md5::Context { } fn reset(&mut self) { - *self = md5::Context::new(); + *self = Self::new(); } fn output_bits(&self) -> usize { @@ -85,7 +85,7 @@ impl Digest for blake2b_simd::State { impl Digest for sha1::Sha1 { fn new() -> Self { - sha1::Sha1::new() + Self::new() } fn input(&mut self, input: &[u8]) { diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 69c1ed100..eded419df 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -112,7 +112,7 @@ enum Modes { impl Default for Modes { fn default() -> Self { - Modes::Lines(10) + Self::Lines(10) } } @@ -167,7 +167,7 @@ impl HeadOptions { pub fn get_from(args: impl uucore::Args) -> Result { let matches = uu_app().get_matches_from(arg_iterate(args)?); - let mut options: HeadOptions = Default::default(); + let mut options = Self::default(); options.quiet = matches.is_present(options::QUIET_NAME); options.verbose = matches.is_present(options::VERBOSE_NAME); diff --git a/src/uu/head/src/take.rs b/src/uu/head/src/take.rs index fded202a5..a003f9328 100644 --- a/src/uu/head/src/take.rs +++ b/src/uu/head/src/take.rs @@ -28,7 +28,7 @@ pub struct TakeAllBut { } impl TakeAllBut { - pub fn new(mut iter: I, n: usize) -> TakeAllBut { + pub fn new(mut iter: I, n: usize) -> Self { // Create a new ring buffer and fill it up. // // If there are fewer than `n` elements in `iter`, then we @@ -44,7 +44,7 @@ impl TakeAllBut { }; buf.push_back(value); } - TakeAllBut { iter, buf } + Self { iter, buf } } } diff --git a/src/uu/join/src/join.rs b/src/uu/join/src/join.rs index be664be82..559d957d1 100644 --- a/src/uu/join/src/join.rs +++ b/src/uu/join/src/join.rs @@ -63,8 +63,8 @@ struct Settings { } impl Default for Settings { - fn default() -> Settings { - Settings { + fn default() -> Self { + Self { key1: 0, key2: 0, print_unpaired1: false, @@ -163,8 +163,8 @@ struct Input { } impl Input { - fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Input { - Input { + fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Self { + Self { separator, ignore_case, check_order, @@ -198,14 +198,14 @@ enum Spec { } impl Spec { - fn parse(format: &str) -> UResult { + fn parse(format: &str) -> UResult { let mut chars = format.chars(); let file_num = match chars.next() { Some('0') => { // Must be all alone without a field specifier. if chars.next().is_none() { - return Ok(Spec::Key); + return Ok(Self::Key); } return Err(USimpleError::new( 1, @@ -223,7 +223,7 @@ impl Spec { }; if let Some('.') = chars.next() { - return Ok(Spec::Field(file_num, parse_field_number(chars.as_str())?)); + return Ok(Self::Field(file_num, parse_field_number(chars.as_str())?)); } Err(USimpleError::new( @@ -239,7 +239,7 @@ struct Line { } impl Line { - fn new(string: Vec, separator: Sep) -> Line { + fn new(string: Vec, separator: Sep) -> Self { let fields = match separator { Sep::Whitespaces => string // GNU join uses Bourne shell field splitters by default @@ -251,7 +251,7 @@ impl Line { Sep::Line => vec![string.clone()], }; - Line { fields, string } + Self { fields, string } } /// Get field at index. diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index 0b5bcbb23..ed858e62a 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -339,7 +339,7 @@ struct PaddingCollection { impl Config { #[allow(clippy::cognitive_complexity)] - fn from(options: &clap::ArgMatches) -> UResult { + fn from(options: &clap::ArgMatches) -> UResult { let context = options.is_present(options::CONTEXT); let (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) { ( @@ -661,7 +661,7 @@ impl Config { Dereference::DirArgs }; - Ok(Config { + Ok(Self { format, files, sort, diff --git a/src/uu/ls/src/quoting_style.rs b/src/uu/ls/src/quoting_style.rs index c7c64cc6c..4900dc566 100644 --- a/src/uu/ls/src/quoting_style.rs +++ b/src/uu/ls/src/quoting_style.rs @@ -79,8 +79,8 @@ impl Iterator for EscapeOctal { } impl EscapeOctal { - fn from(c: char) -> EscapeOctal { - EscapeOctal { + fn from(c: char) -> Self { + Self { c, idx: 2, state: EscapeOctalState::Backslash, diff --git a/src/uu/od/src/formatteriteminfo.rs b/src/uu/od/src/formatteriteminfo.rs index 13cf62246..9778b68f4 100644 --- a/src/uu/od/src/formatteriteminfo.rs +++ b/src/uu/od/src/formatteriteminfo.rs @@ -18,7 +18,7 @@ impl Clone for FormatWriter { } impl PartialEq for FormatWriter { - fn eq(&self, other: &FormatWriter) -> bool { + fn eq(&self, other: &Self) -> bool { use crate::formatteriteminfo::FormatWriter::*; match (self, other) { diff --git a/src/uu/od/src/inputoffset.rs b/src/uu/od/src/inputoffset.rs index 2bdf03ca4..bc12098f8 100644 --- a/src/uu/od/src/inputoffset.rs +++ b/src/uu/od/src/inputoffset.rs @@ -19,8 +19,8 @@ pub struct InputOffset { impl InputOffset { /// creates a new `InputOffset` using the provided values. - pub fn new(radix: Radix, byte_pos: usize, label: Option) -> InputOffset { - InputOffset { + pub fn new(radix: Radix, byte_pos: usize, label: Option) -> Self { + Self { radix, byte_pos, label, diff --git a/src/uu/od/src/mockstream.rs b/src/uu/od/src/mockstream.rs index 5beecbf9c..a1ce0dd68 100644 --- a/src/uu/od/src/mockstream.rs +++ b/src/uu/od/src/mockstream.rs @@ -54,8 +54,8 @@ impl FailingMockStream { /// /// When `read` or `write` is called, it will return an error `repeat_count` times. /// `kind` and `message` can be specified to define the exact error. - pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream { - FailingMockStream { + pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> Self { + Self { kind, message, repeat_count, diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index d1be3dfc7..16abb20fc 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -121,7 +121,7 @@ struct OdOptions { } impl OdOptions { - fn new(matches: &ArgMatches, args: &[String]) -> UResult { + fn new(matches: &ArgMatches, args: &[String]) -> UResult { let byte_order = match matches.value_of(options::ENDIAN) { None => ByteOrder::Native, Some("little") => ByteOrder::Little, @@ -232,7 +232,7 @@ impl OdOptions { } }; - Ok(OdOptions { + Ok(Self { byte_order, skip_bytes, read_bytes, diff --git a/src/uu/od/src/output_info.rs b/src/uu/od/src/output_info.rs index cf050475a..60cbaf5ab 100644 --- a/src/uu/od/src/output_info.rs +++ b/src/uu/od/src/output_info.rs @@ -54,7 +54,7 @@ impl OutputInfo { line_bytes: usize, formats: &[ParsedFormatterItemInfo], output_duplicates: bool, - ) -> OutputInfo { + ) -> Self { let byte_size_block = formats.iter().fold(1, |max, next| { cmp::max(max, next.formatter_item_info.byte_size) }); @@ -68,9 +68,9 @@ impl OutputInfo { let print_width_line = print_width_block * (line_bytes / byte_size_block); let spaced_formatters = - OutputInfo::create_spaced_formatter_info(formats, byte_size_block, print_width_block); + Self::create_spaced_formatter_info(formats, byte_size_block, print_width_block); - OutputInfo { + Self { byte_size_line: line_bytes, print_width_line, byte_size_block, @@ -90,7 +90,7 @@ impl OutputInfo { .map(|f| SpacedFormatterItemInfo { formatter_item_info: f.formatter_item_info, add_ascii_dump: f.add_ascii_dump, - spacing: OutputInfo::calculate_alignment(f, byte_size_block, print_width_block), + spacing: Self::calculate_alignment(f, byte_size_block, print_width_block), }) .collect() } diff --git a/src/uu/od/src/parse_formats.rs b/src/uu/od/src/parse_formats.rs index 01dd65e1c..21971445d 100644 --- a/src/uu/od/src/parse_formats.rs +++ b/src/uu/od/src/parse_formats.rs @@ -14,11 +14,8 @@ pub struct ParsedFormatterItemInfo { } impl ParsedFormatterItemInfo { - pub fn new( - formatter_item_info: FormatterItemInfo, - add_ascii_dump: bool, - ) -> ParsedFormatterItemInfo { - ParsedFormatterItemInfo { + pub fn new(formatter_item_info: FormatterItemInfo, add_ascii_dump: bool) -> Self { + Self { formatter_item_info, add_ascii_dump, } diff --git a/src/uu/od/src/partialreader.rs b/src/uu/od/src/partialreader.rs index f155a7bd2..68e3f30a1 100644 --- a/src/uu/od/src/partialreader.rs +++ b/src/uu/od/src/partialreader.rs @@ -24,7 +24,7 @@ impl PartialReader { /// `skip` bytes, and limits the output to `limit` bytes. Set `limit` /// to `None` if there should be no limit. pub fn new(inner: R, skip: usize, limit: Option) -> Self { - PartialReader { inner, skip, limit } + Self { inner, skip, limit } } } diff --git a/src/uu/od/src/peekreader.rs b/src/uu/od/src/peekreader.rs index 73a94d2e2..45cd554d0 100644 --- a/src/uu/od/src/peekreader.rs +++ b/src/uu/od/src/peekreader.rs @@ -43,7 +43,7 @@ pub struct PeekReader { impl PeekReader { /// Create a new `PeekReader` wrapping `inner` pub fn new(inner: R) -> Self { - PeekReader { + Self { inner, temp_buffer: Vec::new(), } diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 6e0cc76e0..6282be454 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -112,8 +112,8 @@ struct NumberingMode { } impl Default for NumberingMode { - fn default() -> NumberingMode { - NumberingMode { + fn default() -> Self { + Self { width: 5, separator: TAB.to_string(), first_number: 1, @@ -122,8 +122,8 @@ impl Default for NumberingMode { } impl Default for FileLine { - fn default() -> FileLine { - FileLine { + fn default() -> Self { + Self { file_id: 0, line_number: 0, page_number: 0, @@ -136,7 +136,7 @@ impl Default for FileLine { impl From for PrError { fn from(err: IOError) -> Self { - PrError::EncounteredErrors(err.to_string()) + Self::EncounteredErrors(err.to_string()) } } diff --git a/src/uu/ptx/src/ptx.rs b/src/uu/ptx/src/ptx.rs index e389b89ac..fff70373f 100644 --- a/src/uu/ptx/src/ptx.rs +++ b/src/uu/ptx/src/ptx.rs @@ -52,8 +52,8 @@ struct Config { } impl Default for Config { - fn default() -> Config { - Config { + fn default() -> Self { + Self { format: OutFormat::Dumb, gnu_ext: true, auto_ref: false, @@ -96,7 +96,7 @@ struct WordFilter { } impl WordFilter { - fn new(matches: &clap::ArgMatches, config: &Config) -> UResult { + fn new(matches: &clap::ArgMatches, config: &Config) -> UResult { let (o, oset): (bool, HashSet) = if matches.is_present(options::ONLY_FILE) { let words = read_word_filter_file(matches, options::ONLY_FILE).map_err_context(String::new)?; @@ -139,7 +139,7 @@ impl WordFilter { } } }; - Ok(WordFilter { + Ok(Self { only_specified: o, ignore_specified: i, only_set: oset, diff --git a/src/uu/runcon/src/errors.rs b/src/uu/runcon/src/errors.rs index 082b55055..18f06deb9 100644 --- a/src/uu/runcon/src/errors.rs +++ b/src/uu/runcon/src/errors.rs @@ -94,12 +94,12 @@ pub(crate) struct RunconError { } impl RunconError { - pub(crate) fn new(e: Error) -> RunconError { - RunconError::with_code(error_exit_status::ANOTHER_ERROR, e) + pub(crate) fn new(e: Error) -> Self { + Self::with_code(error_exit_status::ANOTHER_ERROR, e) } - pub(crate) fn with_code(code: i32, e: Error) -> RunconError { - RunconError { inner: e, code } + pub(crate) fn with_code(code: i32, e: Error) -> Self { + Self { inner: e, code } } } diff --git a/src/uu/seq/src/extendedbigdecimal.rs b/src/uu/seq/src/extendedbigdecimal.rs index 6cad83dad..3c7e3df53 100644 --- a/src/uu/seq/src/extendedbigdecimal.rs +++ b/src/uu/seq/src/extendedbigdecimal.rs @@ -110,10 +110,10 @@ impl From for ExtendedBigDecimal { fn from(big_int: ExtendedBigInt) -> Self { match big_int { ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)), - ExtendedBigInt::Infinity => ExtendedBigDecimal::Infinity, - ExtendedBigInt::MinusInfinity => ExtendedBigDecimal::MinusInfinity, - ExtendedBigInt::MinusZero => ExtendedBigDecimal::MinusZero, - ExtendedBigInt::Nan => ExtendedBigDecimal::Nan, + ExtendedBigInt::Infinity => Self::Infinity, + ExtendedBigInt::MinusInfinity => Self::MinusInfinity, + ExtendedBigInt::MinusZero => Self::MinusZero, + ExtendedBigInt::Nan => Self::Nan, } } } @@ -124,7 +124,7 @@ impl Display for ExtendedBigDecimal { ExtendedBigDecimal::BigDecimal(x) => { let (n, p) = x.as_bigint_and_exponent(); match p { - 0 => ExtendedBigDecimal::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f), + 0 => Self::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f), _ => x.fmt(f), } } @@ -145,7 +145,7 @@ impl Display for ExtendedBigDecimal { impl Zero for ExtendedBigDecimal { fn zero() -> Self { - ExtendedBigDecimal::BigDecimal(BigDecimal::zero()) + Self::BigDecimal(BigDecimal::zero()) } fn is_zero(&self) -> bool { match self { diff --git a/src/uu/seq/src/extendedbigint.rs b/src/uu/seq/src/extendedbigint.rs index 4a33fa617..bbe64300a 100644 --- a/src/uu/seq/src/extendedbigint.rs +++ b/src/uu/seq/src/extendedbigint.rs @@ -42,7 +42,7 @@ impl ExtendedBigInt { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - ExtendedBigInt::BigInt(BigInt::one()) + Self::BigInt(BigInt::one()) } } @@ -51,10 +51,10 @@ impl From for ExtendedBigInt { match big_decimal { // TODO When can this fail? ExtendedBigDecimal::BigDecimal(x) => Self::BigInt(x.to_bigint().unwrap()), - ExtendedBigDecimal::Infinity => ExtendedBigInt::Infinity, - ExtendedBigDecimal::MinusInfinity => ExtendedBigInt::MinusInfinity, - ExtendedBigDecimal::MinusZero => ExtendedBigInt::MinusZero, - ExtendedBigDecimal::Nan => ExtendedBigInt::Nan, + ExtendedBigDecimal::Infinity => Self::Infinity, + ExtendedBigDecimal::MinusInfinity => Self::MinusInfinity, + ExtendedBigDecimal::MinusZero => Self::MinusZero, + ExtendedBigDecimal::Nan => Self::Nan, } } } @@ -62,22 +62,22 @@ impl From for ExtendedBigInt { impl Display for ExtendedBigInt { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ExtendedBigInt::BigInt(n) => n.fmt(f), - ExtendedBigInt::Infinity => f32::INFINITY.fmt(f), - ExtendedBigInt::MinusInfinity => f32::NEG_INFINITY.fmt(f), - ExtendedBigInt::MinusZero => { + Self::BigInt(n) => n.fmt(f), + Self::Infinity => f32::INFINITY.fmt(f), + Self::MinusInfinity => f32::NEG_INFINITY.fmt(f), + Self::MinusZero => { // FIXME Come up with a way of formatting this with a // "-" prefix. 0.fmt(f) } - ExtendedBigInt::Nan => "nan".fmt(f), + Self::Nan => "nan".fmt(f), } } } impl Zero for ExtendedBigInt { fn zero() -> Self { - ExtendedBigInt::BigInt(BigInt::zero()) + Self::BigInt(BigInt::zero()) } fn is_zero(&self) -> bool { match self { diff --git a/src/uu/seq/src/number.rs b/src/uu/seq/src/number.rs index cec96c0ba..1b46f8f55 100644 --- a/src/uu/seq/src/number.rs +++ b/src/uu/seq/src/number.rs @@ -42,7 +42,7 @@ impl Number { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - Number::Int(ExtendedBigInt::one()) + Self::Int(ExtendedBigInt::one()) } /// Round this number towards the given other number. @@ -89,12 +89,8 @@ pub struct PreciseNumber { } impl PreciseNumber { - pub fn new( - number: Number, - num_integral_digits: usize, - num_fractional_digits: usize, - ) -> PreciseNumber { - PreciseNumber { + pub fn new(number: Number, num_integral_digits: usize, num_fractional_digits: usize) -> Self { + Self { number, num_integral_digits, num_fractional_digits, @@ -106,7 +102,7 @@ impl PreciseNumber { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - PreciseNumber::new(Number::one(), 1, 0) + Self::new(Number::one(), 1, 0) } /// Decide whether this number is zero (either positive or negative). diff --git a/src/uu/shred/src/shred.rs b/src/uu/shred/src/shred.rs index cb3cee2da..2ad91afd1 100644 --- a/src/uu/shred/src/shred.rs +++ b/src/uu/shred/src/shred.rs @@ -68,9 +68,9 @@ struct FilenameGenerator { } impl FilenameGenerator { - fn new(name_len: usize) -> FilenameGenerator { + fn new(name_len: usize) -> Self { let indices: Vec = vec![0; name_len]; - FilenameGenerator { + Self { name_len, name_charset_indices: RefCell::new(indices), exhausted: Cell::new(false), diff --git a/src/uu/shuf/src/rand_read_adapter.rs b/src/uu/shuf/src/rand_read_adapter.rs index ebe9bd01c..fd8998c10 100644 --- a/src/uu/shuf/src/rand_read_adapter.rs +++ b/src/uu/shuf/src/rand_read_adapter.rs @@ -38,8 +38,8 @@ pub struct ReadRng { impl ReadRng { /// Create a new `ReadRng` from a `Read`. - pub fn new(r: R) -> ReadRng { - ReadRng { reader: r } + pub fn new(r: R) -> Self { + Self { reader: r } } } diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index bfe6aa73b..d7e795efa 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -100,7 +100,7 @@ pub struct RecycledChunk { impl RecycledChunk { pub fn new(capacity: usize) -> Self { - RecycledChunk { + Self { lines: Vec::new(), selections: Vec::new(), num_infos: Vec::new(), diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 96d5128f6..a7b4417e3 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -415,7 +415,7 @@ impl WriteableTmpFile for WriteablePlainTmpFile { type InnerWrite = BufWriter; fn create((file, path): (File, PathBuf), _: Option<&str>) -> UResult { - Ok(WriteablePlainTmpFile { + Ok(Self { file: BufWriter::new(file), path, }) @@ -484,7 +484,7 @@ impl WriteableTmpFile for WriteableCompressedTmpFile { code: err.raw_os_error().unwrap(), })?; let child_stdin = child.stdin.take().unwrap(); - Ok(WriteableCompressedTmpFile { + Ok(Self { path, compress_prog: compress_prog.to_owned(), child, diff --git a/src/uu/sort/src/numeric_str_cmp.rs b/src/uu/sort/src/numeric_str_cmp.rs index d60159775..d6855b267 100644 --- a/src/uu/sort/src/numeric_str_cmp.rs +++ b/src/uu/sort/src/numeric_str_cmp.rs @@ -85,12 +85,12 @@ impl NumInfo { let has_si_unit = parse_settings.accept_si_units && matches!(char, 'K' | 'k' | 'M' | 'G' | 'T' | 'P' | 'E' | 'Z' | 'Y'); ( - NumInfo { exponent, sign }, + Self { exponent, sign }, start..if has_si_unit { idx + 1 } else { idx }, ) } else { ( - NumInfo { + Self { sign: Sign::Positive, exponent: 0, }, @@ -127,10 +127,10 @@ impl NumInfo { } } if let Some(start) = start { - (NumInfo { exponent, sign }, start..num.len()) + (Self { exponent, sign }, start..num.len()) } else { ( - NumInfo { + Self { sign: Sign::Positive, exponent: 0, }, diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index e9177654e..31aa2b0a2 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -323,7 +323,7 @@ pub struct GlobalSettings { /// Data needed for sorting. Should be computed once before starting to sort /// by calling `GlobalSettings::init_precomputed`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Precomputed { needs_tokens: bool, num_infos_per_line: usize, @@ -378,8 +378,8 @@ impl GlobalSettings { } impl Default for GlobalSettings { - fn default() -> GlobalSettings { - GlobalSettings { + fn default() -> Self { + Self { mode: SortMode::Default, debug: false, ignore_leading_blanks: false, @@ -400,12 +400,7 @@ impl Default for GlobalSettings { buffer_size: DEFAULT_BUF_SIZE, compress_prog: None, merge_batch_size: 32, - precomputed: Precomputed { - num_infos_per_line: 0, - floats_per_line: 0, - selections_per_line: 0, - needs_tokens: false, - }, + precomputed: Precomputed::default(), } } } @@ -784,7 +779,7 @@ impl KeyPosition { impl Default for KeyPosition { fn default() -> Self { - KeyPosition { + Self { field: 1, char: 1, ignore_blanks: false, diff --git a/src/uu/split/src/platform/unix.rs b/src/uu/split/src/platform/unix.rs index c05593861..f6bac702b 100644 --- a/src/uu/split/src/platform/unix.rs +++ b/src/uu/split/src/platform/unix.rs @@ -39,10 +39,10 @@ struct WithEnvVarSet { } impl WithEnvVarSet { /// Save previous value assigned to key, set key=value - fn new(key: &str, value: &str) -> WithEnvVarSet { + fn new(key: &str, value: &str) -> Self { let previous_env_value = env::var(key); env::set_var(key, value); - WithEnvVarSet { + Self { _previous_var_key: String::from(key), _previous_var_value: previous_env_value, } @@ -66,7 +66,7 @@ impl FilterWriter { /// /// * `command` - The shell command to execute /// * `filepath` - Path of the output file (forwarded to command as $FILE) - fn new(command: &str, filepath: &str) -> FilterWriter { + fn new(command: &str, filepath: &str) -> Self { // set $FILE, save previous value (if there was one) let _with_env_var_set = WithEnvVarSet::new("FILE", filepath); @@ -78,7 +78,7 @@ impl FilterWriter { .spawn() .expect("Couldn't spawn filter command"); - FilterWriter { shell_process } + Self { shell_process } } } diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index d83408ce6..239df62fb 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -182,31 +182,31 @@ impl Strategy { matches.occurrences_of(OPT_LINE_BYTES), matches.occurrences_of(OPT_NUMBER), ) { - (0, 0, 0, 0) => Ok(Strategy::Lines(1000)), + (0, 0, 0, 0) => Ok(Self::Lines(1000)), (1, 0, 0, 0) => { let s = matches.value_of(OPT_LINES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of lines: {}", e)))?; - Ok(Strategy::Lines(n)) + Ok(Self::Lines(n)) } (0, 1, 0, 0) => { let s = matches.value_of(OPT_BYTES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; - Ok(Strategy::Bytes(n)) + Ok(Self::Bytes(n)) } (0, 0, 1, 0) => { let s = matches.value_of(OPT_LINE_BYTES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; - Ok(Strategy::LineBytes(n)) + Ok(Self::LineBytes(n)) } (0, 0, 0, 1) => { let s = matches.value_of(OPT_NUMBER).unwrap(); let n = s.parse::().map_err(|e| { USimpleError::new(1, format!("invalid number of chunks: {}", e)) })?; - Ok(Strategy::Number(n)) + Ok(Self::Number(n)) } _ => Err(UUsageError::new(1, "cannot split in more than one way")), } @@ -232,7 +232,7 @@ struct Settings { impl Settings { /// Parse a strategy from the command-line arguments. fn from(matches: ArgMatches) -> UResult { - let result = Settings { + let result = Self { suffix_length: matches .value_of(OPT_SUFFIX_LENGTH) .unwrap() @@ -275,8 +275,8 @@ struct LineSplitter { } impl LineSplitter { - fn new(chunk_size: usize) -> LineSplitter { - LineSplitter { + fn new(chunk_size: usize) -> Self { + Self { lines_per_split: chunk_size, } } @@ -314,8 +314,8 @@ struct ByteSplitter { } impl ByteSplitter { - fn new(chunk_size: usize) -> ByteSplitter { - ByteSplitter { + fn new(chunk_size: usize) -> Self { + Self { bytes_per_split: u128::try_from(chunk_size).unwrap(), } } diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index fd8578faa..e2a0f57ef 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -461,7 +461,7 @@ impl Stater { Ok(tokens) } - fn new(matches: &ArgMatches) -> UResult { + fn new(matches: &ArgMatches) -> UResult { let files: Vec = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) @@ -480,12 +480,12 @@ impl Stater { let show_fs = matches.is_present(options::FILE_SYSTEM); let default_tokens = if format_str.is_empty() { - Stater::generate_tokens(&Stater::default_format(show_fs, terse, false), use_printf)? + Self::generate_tokens(&Self::default_format(show_fs, terse, false), use_printf)? } else { - Stater::generate_tokens(format_str, use_printf)? + Self::generate_tokens(format_str, use_printf)? }; let default_dev_tokens = - Stater::generate_tokens(&Stater::default_format(show_fs, terse, true), use_printf)?; + Self::generate_tokens(&Self::default_format(show_fs, terse, true), use_printf)?; let mount_list = if show_fs { // mount points aren't displayed when showing filesystem information @@ -501,7 +501,7 @@ impl Stater { Some(mount_list) }; - Ok(Stater { + Ok(Self { follow: matches.is_present(options::DEREFERENCE), show_fs, from_user: !format_str.is_empty(), diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index b0581b3f6..c62873fb3 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -70,7 +70,7 @@ impl<'a> TryFrom<&ArgMatches> for ProgramOptions { type Error = ProgramOptionsError; fn try_from(matches: &ArgMatches) -> Result { - Ok(ProgramOptions { + Ok(Self { stdin: check_option(matches, options::INPUT)?, stdout: check_option(matches, options::OUTPUT)?, stderr: check_option(matches, options::ERROR)?, diff --git a/src/uu/tail/src/platform/unix.rs b/src/uu/tail/src/platform/unix.rs index 580a40135..e7f75c31e 100644 --- a/src/uu/tail/src/platform/unix.rs +++ b/src/uu/tail/src/platform/unix.rs @@ -25,8 +25,8 @@ pub struct ProcessChecker { } impl ProcessChecker { - pub fn new(process_id: self::Pid) -> ProcessChecker { - ProcessChecker { pid: process_id } + pub fn new(process_id: self::Pid) -> Self { + Self { pid: process_id } } // Borrowing mutably to be aligned with Windows implementation diff --git a/src/uu/tail/src/tail.rs b/src/uu/tail/src/tail.rs index 54808ed34..951399866 100644 --- a/src/uu/tail/src/tail.rs +++ b/src/uu/tail/src/tail.rs @@ -72,7 +72,7 @@ enum FilterMode { impl Default for FilterMode { fn default() -> Self { - FilterMode::Lines(10, b'\n') + Self::Lines(10, b'\n') } } @@ -92,7 +92,7 @@ impl Settings { pub fn get_from(args: impl uucore::Args) -> Result { let matches = uu_app().get_matches_from(arg_iterate(args)?); - let mut settings: Settings = Settings { + let mut settings: Self = Self { sleep_msec: 1000, follow: matches.is_present(options::FOLLOW), ..Default::default() diff --git a/src/uu/test/src/parser.rs b/src/uu/test/src/parser.rs index ce4c0dec0..d8d7ce802 100644 --- a/src/uu/test/src/parser.rs +++ b/src/uu/test/src/parser.rs @@ -44,26 +44,26 @@ impl Symbol { /// Create a new Symbol from an OsString. /// /// Returns Symbol::None in place of None - fn new(token: Option) -> Symbol { + fn new(token: Option) -> Self { match token { Some(s) => match s.to_str() { Some(t) => match t { - "(" => Symbol::LParen, - "!" => Symbol::Bang, - "-a" | "-o" => Symbol::BoolOp(s), - "=" | "==" | "!=" => Symbol::Op(Operator::String(s)), - "-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Symbol::Op(Operator::Int(s)), - "-ef" | "-nt" | "-ot" => Symbol::Op(Operator::File(s)), - "-n" | "-z" => Symbol::UnaryOp(UnaryOperator::StrlenOp(s)), + "(" => Self::LParen, + "!" => Self::Bang, + "-a" | "-o" => Self::BoolOp(s), + "=" | "==" | "!=" => Self::Op(Operator::String(s)), + "-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Self::Op(Operator::Int(s)), + "-ef" | "-nt" | "-ot" => Self::Op(Operator::File(s)), + "-n" | "-z" => Self::UnaryOp(UnaryOperator::StrlenOp(s)), "-b" | "-c" | "-d" | "-e" | "-f" | "-g" | "-G" | "-h" | "-k" | "-L" | "-O" | "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => { - Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) + Self::UnaryOp(UnaryOperator::FiletestOp(s)) } - _ => Symbol::Literal(s), + _ => Self::Literal(s), }, - None => Symbol::Literal(s), + None => Self::Literal(s), }, - None => Symbol::None, + None => Self::None, } } @@ -74,18 +74,18 @@ impl Symbol { /// # Panics /// /// Panics if `self` is Symbol::None - fn into_literal(self) -> Symbol { - Symbol::Literal(match self { - Symbol::LParen => OsString::from("("), - Symbol::Bang => OsString::from("!"), - Symbol::BoolOp(s) - | Symbol::Literal(s) - | Symbol::Op(Operator::String(s)) - | Symbol::Op(Operator::Int(s)) - | Symbol::Op(Operator::File(s)) - | Symbol::UnaryOp(UnaryOperator::StrlenOp(s)) - | Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) => s, - Symbol::None => panic!(), + fn into_literal(self) -> Self { + Self::Literal(match self { + Self::LParen => OsString::from("("), + Self::Bang => OsString::from("!"), + Self::BoolOp(s) + | Self::Literal(s) + | Self::Op(Operator::String(s)) + | Self::Op(Operator::Int(s)) + | Self::Op(Operator::File(s)) + | Self::UnaryOp(UnaryOperator::StrlenOp(s)) + | Self::UnaryOp(UnaryOperator::FiletestOp(s)) => s, + Self::None => panic!(), }) } } @@ -120,8 +120,8 @@ struct Parser { impl Parser { /// Construct a new Parser from a `Vec` of tokens. - fn new(tokens: Vec) -> Parser { - Parser { + fn new(tokens: Vec) -> Self { + Self { tokens: tokens.into_iter().peekable(), stack: vec![], } diff --git a/src/uu/timeout/src/timeout.rs b/src/uu/timeout/src/timeout.rs index 9a8222dee..2e686f811 100644 --- a/src/uu/timeout/src/timeout.rs +++ b/src/uu/timeout/src/timeout.rs @@ -57,7 +57,7 @@ struct Config { } impl Config { - fn from(options: &clap::ArgMatches) -> Config { + fn from(options: &clap::ArgMatches) -> Self { let signal = match options.value_of(options::SIGNAL) { Some(signal_) => { let signal_result = signal_by_name_or_value(signal_); @@ -88,7 +88,7 @@ impl Config { .map(String::from) .collect::>(); - Config { + Self { foreground, kill_after, signal, diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 373dec0c2..4d00a0af1 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -140,10 +140,10 @@ impl Sequence { set2_str: &str, truncate_set1_flag: bool, ) -> Result<(Vec, Vec), BadSequence> { - let set1 = Sequence::from_str(set1_str)?; - let set2 = Sequence::from_str(set2_str)?; + let set1 = Self::from_str(set1_str)?; + let set2 = Self::from_str(set2_str)?; - let is_char_star = |s: &&Sequence| -> bool { matches!(s, Sequence::CharStar(_)) }; + let is_char_star = |s: &&Self| -> bool { matches!(s, Sequence::CharStar(_)) }; let set1_star_count = set1.iter().filter(is_char_star).count(); if set1_star_count == 0 { let set2_star_count = set2.iter().filter(is_char_star).count(); @@ -152,17 +152,15 @@ impl Sequence { Sequence::CharStar(c) => Some(c), _ => None, }); - let mut partition = set2 - .as_slice() - .split(|s| matches!(s, Sequence::CharStar(_))); - let set1_len = set1.iter().flat_map(Sequence::flatten).count(); + let mut partition = set2.as_slice().split(|s| matches!(s, Self::CharStar(_))); + let set1_len = set1.iter().flat_map(Self::flatten).count(); let set2_len = set2 .iter() .filter_map(|s| match s { Sequence::CharStar(_) => None, r => Some(r), }) - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .count(); let star_compensate_len = set1_len.saturating_sub(set2_len); let (left, right) = (partition.next(), partition.next()); @@ -175,35 +173,35 @@ impl Sequence { if let Some(c) = char_star { std::iter::repeat(*c) .take(star_compensate_len) - .chain(set2_b.iter().flat_map(Sequence::flatten)) + .chain(set2_b.iter().flat_map(Self::flatten)) .collect() } else { - set2_b.iter().flat_map(Sequence::flatten).collect() + set2_b.iter().flat_map(Self::flatten).collect() } } (Some(set2_a), None) => match char_star { Some(c) => set2_a .iter() - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .chain(std::iter::repeat(*c).take(star_compensate_len)) .collect(), - None => set2_a.iter().flat_map(Sequence::flatten).collect(), + None => set2_a.iter().flat_map(Self::flatten).collect(), }, (Some(set2_a), Some(set2_b)) => match char_star { Some(c) => set2_a .iter() - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .chain(std::iter::repeat(*c).take(star_compensate_len)) - .chain(set2_b.iter().flat_map(Sequence::flatten)) + .chain(set2_b.iter().flat_map(Self::flatten)) .collect(), None => set2_a .iter() .chain(set2_b.iter()) - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .collect(), }, }; - let mut set1_solved: Vec = set1.iter().flat_map(Sequence::flatten).collect(); + let mut set1_solved: Vec = set1.iter().flat_map(Self::flatten).collect(); if truncate_set1_flag { set1_solved.truncate(set2_solved.len()); } @@ -218,15 +216,15 @@ impl Sequence { } impl Sequence { - pub fn from_str(input: &str) -> Result, BadSequence> { + pub fn from_str(input: &str) -> Result, BadSequence> { many0(alt(( - Sequence::parse_char_range, - Sequence::parse_char_star, - Sequence::parse_char_repeat, - Sequence::parse_class, - Sequence::parse_char_equal, + Self::parse_char_range, + Self::parse_char_star, + Self::parse_char_repeat, + Self::parse_class, + Self::parse_char_equal, // NOTE: This must be the last one - map(Sequence::parse_backslash_or_char, |s| Ok(Sequence::Char(s))), + map(Self::parse_backslash_or_char, |s| Ok(Self::Char(s))), )))(input) .map(|(_, r)| r) .unwrap() @@ -251,64 +249,64 @@ impl Sequence { } fn parse_backslash_or_char(input: &str) -> IResult<&str, char> { - alt((Sequence::parse_backslash, anychar))(input) + alt((Self::parse_backslash, anychar))(input) } - fn parse_char_range(input: &str) -> IResult<&str, Result> { + fn parse_char_range(input: &str) -> IResult<&str, Result> { separated_pair( - Sequence::parse_backslash_or_char, + Self::parse_backslash_or_char, tag("-"), - Sequence::parse_backslash_or_char, + Self::parse_backslash_or_char, )(input) .map(|(l, (a, b))| { (l, { let (start, end) = (u32::from(a), u32::from(b)); - Ok(Sequence::CharRange(start, end)) + Ok(Self::CharRange(start, end)) }) }) } - fn parse_char_star(input: &str) -> IResult<&str, Result> { - delimited(tag("["), Sequence::parse_backslash_or_char, tag("*]"))(input) - .map(|(l, a)| (l, Ok(Sequence::CharStar(a)))) + fn parse_char_star(input: &str) -> IResult<&str, Result> { + delimited(tag("["), Self::parse_backslash_or_char, tag("*]"))(input) + .map(|(l, a)| (l, Ok(Self::CharStar(a)))) } - fn parse_char_repeat(input: &str) -> IResult<&str, Result> { + fn parse_char_repeat(input: &str) -> IResult<&str, Result> { delimited( tag("["), - separated_pair(Sequence::parse_backslash_or_char, tag("*"), digit1), + separated_pair(Self::parse_backslash_or_char, tag("*"), digit1), tag("]"), )(input) .map(|(l, (c, str))| { ( l, match usize::from_str_radix(str, 8) { - Ok(0) => Ok(Sequence::CharStar(c)), - Ok(count) => Ok(Sequence::CharRepeat(c, count)), + Ok(0) => Ok(Self::CharStar(c)), + Ok(count) => Ok(Self::CharRepeat(c, count)), Err(_) => Err(BadSequence::InvalidRepeatCount(str.to_string())), }, ) }) } - fn parse_class(input: &str) -> IResult<&str, Result> { + fn parse_class(input: &str) -> IResult<&str, Result> { delimited( tag("[:"), alt(( map( alt(( - value(Sequence::Alnum, tag("alnum")), - value(Sequence::Alpha, tag("alpha")), - value(Sequence::Blank, tag("blank")), - value(Sequence::Control, tag("cntrl")), - value(Sequence::Digit, tag("digit")), - value(Sequence::Graph, tag("graph")), - value(Sequence::Lower, tag("lower")), - value(Sequence::Print, tag("print")), - value(Sequence::Punct, tag("punct")), - value(Sequence::Space, tag("space")), - value(Sequence::Upper, tag("upper")), - value(Sequence::Xdigit, tag("xdigit")), + value(Self::Alnum, tag("alnum")), + value(Self::Alpha, tag("alpha")), + value(Self::Blank, tag("blank")), + value(Self::Control, tag("cntrl")), + value(Self::Digit, tag("digit")), + value(Self::Graph, tag("graph")), + value(Self::Lower, tag("lower")), + value(Self::Print, tag("print")), + value(Self::Punct, tag("punct")), + value(Self::Space, tag("space")), + value(Self::Upper, tag("upper")), + value(Self::Xdigit, tag("xdigit")), )), Ok, ), @@ -318,7 +316,7 @@ impl Sequence { )(input) } - fn parse_char_equal(input: &str) -> IResult<&str, Result> { + fn parse_char_equal(input: &str) -> IResult<&str, Result> { delimited( tag("[="), alt(( @@ -326,7 +324,7 @@ impl Sequence { Err(BadSequence::MissingEquivalentClassChar), peek(tag("=]")), ), - map(Sequence::parse_backslash_or_char, |c| Ok(Sequence::Char(c))), + map(Self::parse_backslash_or_char, |c| Ok(Self::Char(c))), )), tag("=]"), )(input) @@ -344,8 +342,8 @@ pub struct DeleteOperation { } impl DeleteOperation { - pub fn new(set: Vec, complement_flag: bool) -> DeleteOperation { - DeleteOperation { + pub fn new(set: Vec, complement_flag: bool) -> Self { + Self { set, complement_flag, } @@ -372,8 +370,8 @@ pub struct TranslateOperationComplement { } impl TranslateOperationComplement { - fn new(set1: Vec, set2: Vec) -> TranslateOperationComplement { - TranslateOperationComplement { + fn new(set1: Vec, set2: Vec) -> Self { + Self { iter: 0, set2_iter: 0, set1, @@ -389,16 +387,16 @@ pub struct TranslateOperationStandard { } impl TranslateOperationStandard { - fn new(set1: Vec, set2: Vec) -> Result { + fn new(set1: Vec, set2: Vec) -> Result { if let Some(fallback) = set2.last().copied() { - Ok(TranslateOperationStandard { + Ok(Self { translation_map: set1 .into_iter() .zip(set2.into_iter().chain(std::iter::repeat(fallback))) .collect::>(), }) } else if set1.is_empty() && set2.is_empty() { - Ok(TranslateOperationStandard { + Ok(Self { translation_map: HashMap::new(), }) } else { @@ -424,19 +422,13 @@ impl TranslateOperation { } impl TranslateOperation { - pub fn new( - set1: Vec, - set2: Vec, - complement: bool, - ) -> Result { + pub fn new(set1: Vec, set2: Vec, complement: bool) -> Result { if complement { - Ok(TranslateOperation::Complement( - TranslateOperationComplement::new(set1, set2), - )) + Ok(Self::Complement(TranslateOperationComplement::new( + set1, set2, + ))) } else { - Ok(TranslateOperation::Standard( - TranslateOperationStandard::new(set1, set2)?, - )) + Ok(Self::Standard(TranslateOperationStandard::new(set1, set2)?)) } } } @@ -444,13 +436,13 @@ impl TranslateOperation { impl SymbolTranslator for TranslateOperation { fn translate(&mut self, current: char) -> Option { match self { - TranslateOperation::Standard(TranslateOperationStandard { translation_map }) => Some( + Self::Standard(TranslateOperationStandard { translation_map }) => Some( translation_map .iter() .find_map(|(l, r)| if l.eq(¤t) { Some(*r) } else { None }) .unwrap_or(current), ), - TranslateOperation::Complement(TranslateOperationComplement { + Self::Complement(TranslateOperationComplement { iter, set2_iter, set1, @@ -467,8 +459,7 @@ impl SymbolTranslator for TranslateOperation { } else { while translation_map.get(¤t).is_none() { if let Some(value) = set2.get(*set2_iter) { - let (next_iter, next_key) = - TranslateOperation::next_complement_char(*iter, &*set1); + let (next_iter, next_key) = Self::next_complement_char(*iter, &*set1); *iter = next_iter; *set2_iter = set2_iter.saturating_add(1); translation_map.insert(next_key, *value); @@ -491,8 +482,8 @@ pub struct SqueezeOperation { } impl SqueezeOperation { - pub fn new(set1: Vec, complement: bool) -> SqueezeOperation { - SqueezeOperation { + pub fn new(set1: Vec, complement: bool) -> Self { + Self { set1: set1.into_iter().collect(), complement, previous: None, diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index c50b695ac..069d6dc4f 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -104,6 +104,7 @@ pub fn uu_app<'a>() -> App<'a> { // We use String as a representation of node here // but using integer may improve performance. +#[derive(Default)] struct Graph { in_edges: HashMap>, out_edges: HashMap>, @@ -111,12 +112,8 @@ struct Graph { } impl Graph { - fn new() -> Graph { - Graph { - in_edges: HashMap::new(), - out_edges: HashMap::new(), - result: vec![], - } + fn new() -> Self { + Self::default() } fn has_node(&self, n: &str) -> bool { diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 3b419d854..dc1d0c800 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -67,7 +67,7 @@ struct Options { } impl Options { - fn new(matches: &clap::ArgMatches) -> Options { + fn new(matches: &clap::ArgMatches) -> Self { let tabstops = match matches.value_of(options::TABS) { None => vec![DEFAULT_TABSTOP], Some(s) => tabstops_parse(s), @@ -82,7 +82,7 @@ impl Options { None => vec!["-".to_owned()], }; - Options { + Self { files, tabstops, aflag, diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index d8782e62d..6a96d425b 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -39,8 +39,8 @@ struct Settings { } impl Settings { - fn new(matches: &ArgMatches) -> Settings { - let settings = Settings { + fn new(matches: &ArgMatches) -> Self { + let settings = Self { show_bytes: matches.is_present(options::BYTES), show_chars: matches.is_present(options::CHAR), show_lines: matches.is_present(options::LINES), @@ -57,7 +57,7 @@ impl Settings { return settings; } - Settings { + Self { show_bytes: true, show_chars: false, show_lines: true, diff --git a/src/uu/yes/src/splice.rs b/src/uu/yes/src/splice.rs index 84bd1cc24..f77a09ed6 100644 --- a/src/uu/yes/src/splice.rs +++ b/src/uu/yes/src/splice.rs @@ -55,7 +55,7 @@ type Result = std::result::Result; impl From for Error { fn from(error: nix::Error) -> Self { - Error::Io(io::Error::from_raw_os_error(error as i32)) + Self::Io(io::Error::from_raw_os_error(error as i32)) } } diff --git a/src/uucore/src/lib/features/encoding.rs b/src/uucore/src/lib/features/encoding.rs index b36e6a6a0..e99017070 100644 --- a/src/uucore/src/lib/features/encoding.rs +++ b/src/uucore/src/lib/features/encoding.rs @@ -107,7 +107,7 @@ pub struct Data { impl Data { pub fn new(input: R, format: Format) -> Self { - Data { + Self { line_wrap: 76, ignore_garbage: false, input, diff --git a/src/uucore/src/lib/features/entries.rs b/src/uucore/src/lib/features/entries.rs index 60fa6a3da..90f3134ab 100644 --- a/src/uucore/src/lib/features/entries.rs +++ b/src/uucore/src/lib/features/entries.rs @@ -175,7 +175,7 @@ impl Passwd { /// SAFETY: All the pointed-to strings must be valid and not change while /// the function runs. That means PW_LOCK must be held. unsafe fn from_raw(raw: passwd) -> Self { - Passwd { + Self { name: cstr2string(raw.pw_name), uid: raw.pw_uid, gid: raw.pw_gid, @@ -243,7 +243,7 @@ impl Group { /// SAFETY: gr_name must be valid and not change while /// the function runs. That means PW_LOCK must be held. unsafe fn from_raw(raw: group) -> Self { - Group { + Self { name: cstr2string(raw.gr_name), gid: raw.gr_gid, } diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index 8ba7f8fc0..d1e623757 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -197,7 +197,7 @@ impl MountInfo { } #[cfg(target_os = "linux")] - fn new(file_name: &str, raw: &[&str]) -> Option { + fn new(file_name: &str, raw: &[&str]) -> Option { match file_name { // spell-checker:ignore (word) noatime // Format: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue @@ -207,7 +207,7 @@ impl MountInfo { let after_fields = raw[FIELDS_OFFSET..].iter().position(|c| *c == "-").unwrap() + FIELDS_OFFSET + 1; - let mut m = MountInfo { + let mut m = Self { dev_id: "".to_string(), dev_name: raw[after_fields + 1].to_string(), fs_type: raw[after_fields].to_string(), @@ -221,7 +221,7 @@ impl MountInfo { Some(m) } LINUX_MTAB => { - let mut m = MountInfo { + let mut m = Self { dev_id: "".to_string(), dev_name: raw[0].to_string(), fs_type: raw[2].to_string(), @@ -496,9 +496,9 @@ pub struct FsUsage { impl FsUsage { #[cfg(unix)] - pub fn new(statvfs: StatFs) -> FsUsage { + pub fn new(statvfs: StatFs) -> Self { { - FsUsage { + Self { blocksize: statvfs.f_bsize as u64, // or `statvfs.f_frsize` ? blocks: statvfs.f_blocks as u64, bfree: statvfs.f_bfree as u64, @@ -510,7 +510,7 @@ impl FsUsage { } } #[cfg(not(unix))] - pub fn new(path: &Path) -> FsUsage { + pub fn new(path: &Path) -> Self { let mut root_path = [0u16; MAX_PATH]; let success = unsafe { GetVolumePathNamesForVolumeNameW( diff --git a/src/uucore/src/lib/features/memo.rs b/src/uucore/src/lib/features/memo.rs index f2d1a33d9..fd57c33b5 100644 --- a/src/uucore/src/lib/features/memo.rs +++ b/src/uucore/src/lib/features/memo.rs @@ -26,8 +26,8 @@ fn warn_excess_args(first_arg: &str) { } impl Memo { - pub fn new(pf_string: &str, pf_args_it: &mut Peekable>) -> Memo { - let mut pm = Memo { tokens: Vec::new() }; + pub fn new(pf_string: &str, pf_args_it: &mut Peekable>) -> Self { + let mut pm = Self { tokens: Vec::new() }; let mut tmp_token: Option>; let mut it = put_back_n(pf_string.chars()); let mut has_sub = false; @@ -73,7 +73,7 @@ impl Memo { } pub fn run_all(pf_string: &str, pf_args: &[String]) { let mut arg_it = pf_args.iter().peekable(); - let pm = Memo::new(pf_string, &mut arg_it); + let pm = Self::new(pf_string, &mut arg_it); loop { if arg_it.peek().is_none() { break; diff --git a/src/uucore/src/lib/features/process.rs b/src/uucore/src/lib/features/process.rs index d0f530a5a..b573fdfcc 100644 --- a/src/uucore/src/lib/features/process.rs +++ b/src/uucore/src/lib/features/process.rs @@ -56,12 +56,12 @@ impl ExitStatus { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { - return ExitStatus::Signal(signal); + return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above - ExitStatus::Code(status.code().unwrap()) + Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { diff --git a/src/uucore/src/lib/features/ringbuffer.rs b/src/uucore/src/lib/features/ringbuffer.rs index 772336ef1..08073fae0 100644 --- a/src/uucore/src/lib/features/ringbuffer.rs +++ b/src/uucore/src/lib/features/ringbuffer.rs @@ -42,15 +42,15 @@ pub struct RingBuffer { } impl RingBuffer { - pub fn new(size: usize) -> RingBuffer { - RingBuffer { + pub fn new(size: usize) -> Self { + Self { data: VecDeque::new(), size, } } - pub fn from_iter(iter: impl Iterator, size: usize) -> RingBuffer { - let mut ring_buffer = RingBuffer::new(size); + pub fn from_iter(iter: impl Iterator, size: usize) -> Self { + let mut ring_buffer = Self::new(size); for value in iter { ring_buffer.push_back(value); } diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs index 68b35c3c1..85396a2aa 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs @@ -8,13 +8,14 @@ use super::base_conv; use super::base_conv::RadixDef; use super::float_common::{primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct CninetyNineHexFloatf { #[allow(dead_code)] as_num: f64, } impl CninetyNineHexFloatf { - pub fn new() -> CninetyNineHexFloatf { - CninetyNineHexFloatf { as_num: 0.0 } + pub fn new() -> Self { + Self::default() } } diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs index 3376345e0..52b8515c9 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs @@ -25,8 +25,8 @@ fn get_len_fmt_primitive(fmt: &FormatPrimitive) -> usize { pub struct Decf; impl Decf { - pub fn new() -> Decf { - Decf + pub fn new() -> Self { + Self } } impl Formatter for Decf { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs index 95b0e34e6..e62245534 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs @@ -46,12 +46,12 @@ impl FloatAnalysis { max_sd_opt: Option, max_after_dec_opt: Option, hex_output: bool, - ) -> FloatAnalysis { + ) -> Self { // this fn assumes // the input string // has no leading spaces or 0s let str_it = get_it_at(initial_prefix.offset, str_in); - let mut ret = FloatAnalysis { + let mut ret = Self { len_important: 0, decimal_pos: None, follow: None, diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs index afb2bcf08..e13629af5 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs @@ -6,10 +6,11 @@ use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct Floatf; impl Floatf { - pub fn new() -> Floatf { - Floatf + pub fn new() -> Self { + Self::default() } } impl Formatter for Floatf { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs index b6c18d436..0b93d134c 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs @@ -11,6 +11,7 @@ use super::super::formatter::{ use std::i64; use std::u64; +#[derive(Default)] pub struct Intf { _a: u32, } @@ -24,8 +25,8 @@ struct IntAnalysis { } impl Intf { - pub fn new() -> Intf { - Intf { _a: 0 } + pub fn new() -> Self { + Self::default() } // take a ref to argument string, and basic information // about prefix (offset, radix, sign), and analyze string @@ -166,7 +167,7 @@ impl Intf { fmt_prim.pre_decimal = Some(format!("{}", i)); fmt_prim } - Err(_) => Intf::get_max(field_char, sign), + Err(_) => Self::get_max(field_char, sign), }, _ => match u64::from_str_radix(segment, radix_in as u32) { Ok(u) => { @@ -180,7 +181,7 @@ impl Intf { }); fmt_prim } - Err(_) => Intf::get_max(field_char, sign), + Err(_) => Self::get_max(field_char, sign), }, } } @@ -196,7 +197,7 @@ impl Formatter for Intf { // get information about the string. see Intf::Analyze // def above. - let convert_hints = Intf::analyze( + let convert_hints = Self::analyze( str_in, *field.field_char == 'i' || *field.field_char == 'd', initial_prefix, @@ -226,7 +227,7 @@ impl Formatter for Intf { if convert_hints.check_past_max || decrease_from_max || radix_mismatch { // radix of in and out is the same. let segment = String::from(&str_in[begin..end]); - Intf::conv_from_segment( + Self::conv_from_segment( &segment, initial_prefix.radix_in.clone(), *field.field_char, @@ -246,7 +247,7 @@ impl Formatter for Intf { fmt_prim } } else { - Intf::get_max(*field.field_char, initial_prefix.sign) + Self::get_max(*field.field_char, initial_prefix.sign) }) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs index c46c7d423..c5b88b5a7 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs @@ -5,11 +5,12 @@ use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct Scif; impl Scif { - pub fn new() -> Scif { - Scif + pub fn new() -> Self { + Self::default() } } impl Formatter for Scif { diff --git a/src/uucore/src/lib/features/tokenize/sub.rs b/src/uucore/src/lib/features/tokenize/sub.rs index 0c3a68c3c..6f9196d93 100644 --- a/src/uucore/src/lib/features/tokenize/sub.rs +++ b/src/uucore/src/lib/features/tokenize/sub.rs @@ -67,7 +67,7 @@ impl Sub { second_field: CanAsterisk>, field_char: char, orig: String, - ) -> Sub { + ) -> Self { // for more dry printing, field characters are grouped // in initialization of token. let field_type = match field_char { @@ -84,7 +84,7 @@ impl Sub { exit(EXIT_ERR); } }; - Sub { + Self { min_width, second_field, field_char, @@ -94,6 +94,7 @@ impl Sub { } } +#[derive(Default)] struct SubParser { min_width_tmp: Option, min_width_is_asterisk: bool, @@ -106,32 +107,23 @@ struct SubParser { } impl SubParser { - fn new() -> SubParser { - SubParser { - min_width_tmp: None, - min_width_is_asterisk: false, - past_decimal: false, - second_field_tmp: None, - second_field_is_asterisk: false, - specifiers_found: false, - field_char: None, - text_so_far: String::new(), - } + fn new() -> Self { + Self::default() } fn from_it( it: &mut PutBackN, args: &mut Peekable>, ) -> Option> { - let mut parser = SubParser::new(); + let mut parser = Self::new(); if parser.sub_vals_retrieved(it) { - let t: Box = SubParser::build_token(parser); + let t: Box = Self::build_token(parser); t.print(args); Some(t) } else { None } } - fn build_token(parser: SubParser) -> Box { + fn build_token(parser: Self) -> Box { // not a self method so as to allow move of sub-parser vals. // return new Sub struct as token let t: Box = Box::new(Sub::new( @@ -151,7 +143,7 @@ impl SubParser { t } fn sub_vals_retrieved(&mut self, it: &mut PutBackN) -> bool { - if !SubParser::successfully_eat_prefix(it, &mut self.text_so_far) { + if !Self::successfully_eat_prefix(it, &mut self.text_so_far) { return false; } // this fn in particular is much longer than it needs to be diff --git a/src/uucore/src/lib/features/tokenize/unescaped_text.rs b/src/uucore/src/lib/features/tokenize/unescaped_text.rs index a192c757b..0ec721b48 100644 --- a/src/uucore/src/lib/features/tokenize/unescaped_text.rs +++ b/src/uucore/src/lib/features/tokenize/unescaped_text.rs @@ -35,10 +35,11 @@ fn flush_bytes(bslice: &[u8]) { let _ = stdout().flush(); } +#[derive(Default)] pub struct UnescapedText(Vec); impl UnescapedText { - fn new() -> UnescapedText { - UnescapedText(Vec::new()) + fn new() -> Self { + Self::default() } // take an iterator to the format string // consume between min and max chars @@ -133,7 +134,7 @@ impl UnescapedText { _ => {} } if !ignore { - let val = (UnescapedText::base_to_u32(min_len, max_len, base, it) % 256) as u8; + let val = (Self::base_to_u32(min_len, max_len, base, it) % 256) as u8; byte_vec.push(val); let bvec = [val]; flush_bytes(&bvec); @@ -170,8 +171,8 @@ impl UnescapedText { 'u' => 4, /* 'U' | */ _ => 8, }; - let val = UnescapedText::base_to_u32(len, len, 16, it); - UnescapedText::validate_iec(val, false); + let val = Self::base_to_u32(len, len, 16, it); + Self::validate_iec(val, false); if let Some(c) = from_u32(val) { c } else { @@ -199,7 +200,7 @@ impl UnescapedText { subs_mode: bool, ) -> Option> { let mut addchar = false; - let mut new_text = UnescapedText::new(); + let mut new_text = Self::new(); let mut tmp_str = String::new(); { let new_vec: &mut Vec = &mut (new_text.0); @@ -227,7 +228,7 @@ impl UnescapedText { new_vec.extend(tmp_str.bytes()); tmp_str = String::new(); } - UnescapedText::handle_escaped(new_vec, it, subs_mode); + Self::handle_escaped(new_vec, it, subs_mode); } x if x == '%' && !subs_mode => { if let Some(follow) = it.next() { @@ -266,7 +267,7 @@ impl token::Tokenizer for UnescapedText { it: &mut PutBackN, _: &mut Peekable>, ) -> Option> { - UnescapedText::from_it_core(it, false) + Self::from_it_core(it, false) } } impl token::Token for UnescapedText { diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index a3078b818..c82fd35ef 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -322,7 +322,7 @@ impl UtmpxIter { fn new() -> Self { // PoisonErrors can safely be ignored let guard = LOCK.lock().unwrap_or_else(|err| err.into_inner()); - UtmpxIter { + Self { guard, phantom: PhantomData, } diff --git a/src/uucore/src/lib/mods/error.rs b/src/uucore/src/lib/mods/error.rs index 24de6434b..ba7722f1c 100644 --- a/src/uucore/src/lib/mods/error.rs +++ b/src/uucore/src/lib/mods/error.rs @@ -265,7 +265,7 @@ impl From for Box where T: UError + 'static, { - fn from(t: T) -> Box { + fn from(t: T) -> Self { Box::new(t) } } @@ -490,8 +490,8 @@ impl FromIo> for std::io::ErrorKind { } impl From for UIoError { - fn from(f: std::io::Error) -> UIoError { - UIoError { + fn from(f: std::io::Error) -> Self { + Self { context: None, inner: f, } @@ -499,9 +499,9 @@ impl From for UIoError { } impl From for Box { - fn from(f: std::io::Error) -> Box { + fn from(f: std::io::Error) -> Self { let u_error: UIoError = f.into(); - Box::new(u_error) as Box + Box::new(u_error) as Self } } diff --git a/src/uucore/src/lib/mods/ranges.rs b/src/uucore/src/lib/mods/ranges.rs index f142e14fb..822c09e02 100644 --- a/src/uucore/src/lib/mods/ranges.rs +++ b/src/uucore/src/lib/mods/ranges.rs @@ -20,7 +20,7 @@ pub struct Range { impl FromStr for Range { type Err = &'static str; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { use std::usize::MAX; let mut parts = s.splitn(2, '-'); @@ -33,7 +33,7 @@ impl FromStr for Range { (Some(nm), None) => { if let Ok(nm) = nm.parse::() { if nm > 0 { - Ok(Range { low: nm, high: nm }) + Ok(Self { low: nm, high: nm }) } else { Err(field) } @@ -44,7 +44,7 @@ impl FromStr for Range { (Some(n), Some(m)) if m.is_empty() => { if let Ok(low) = n.parse::() { if low > 0 { - Ok(Range { low, high: MAX - 1 }) + Ok(Self { low, high: MAX - 1 }) } else { Err(field) } @@ -55,7 +55,7 @@ impl FromStr for Range { (Some(n), Some(m)) if n.is_empty() => { if let Ok(high) = m.parse::() { if high > 0 { - Ok(Range { low: 1, high }) + Ok(Self { low: 1, high }) } else { Err(field) } @@ -66,7 +66,7 @@ impl FromStr for Range { (Some(n), Some(m)) => match (n.parse::(), m.parse::()) { (Ok(low), Ok(high)) => { if low > 0 && low <= high { - Ok(Range { low, high }) + Ok(Self { low, high }) } else if low == 0 { Err(field) } else { @@ -81,10 +81,10 @@ impl FromStr for Range { } impl Range { - pub fn from_list(list: &str) -> Result, String> { + pub fn from_list(list: &str) -> Result, String> { use std::cmp::max; - let mut ranges: Vec = vec![]; + let mut ranges: Vec = vec![]; for item in list.split(',') { let range_item = FromStr::from_str(item) diff --git a/src/uucore/src/lib/parser/parse_size.rs b/src/uucore/src/lib/parser/parse_size.rs index c05c0d3f1..797daebbb 100644 --- a/src/uucore/src/lib/parser/parse_size.rs +++ b/src/uucore/src/lib/parser/parse_size.rs @@ -113,7 +113,7 @@ impl fmt::Display for ParseSizeError { // but there's a lot of downstream code that constructs these errors manually // that would be affected impl ParseSizeError { - fn parse_failure(s: &str) -> ParseSizeError { + fn parse_failure(s: &str) -> Self { // stderr on linux (GNU coreutils 8.32) (LC_ALL=C) // has to be handled in the respective uutils because strings differ, e.g.: // @@ -145,10 +145,10 @@ impl ParseSizeError { // --width // --strings // etc. - ParseSizeError::ParseFailure(format!("{}", s.quote())) + Self::ParseFailure(format!("{}", s.quote())) } - fn size_too_big(s: &str) -> ParseSizeError { + fn size_too_big(s: &str) -> Self { // stderr on linux (GNU coreutils 8.32) (LC_ALL=C) // has to be handled in the respective uutils because strings differ, e.g.: // @@ -165,7 +165,7 @@ impl ParseSizeError { // stderr on macos (brew - GNU coreutils 8.32) also differs for the same version, e.g.: // ghead: invalid number of bytes: '1Y': Value too large to be stored in data type // gtail: invalid number of bytes: '1Y': Value too large to be stored in data type - ParseSizeError::SizeTooBig(format!( + Self::SizeTooBig(format!( "{}: Value too large for defined data type", s.quote() )) diff --git a/tests/by-util/test_kill.rs b/tests/by-util/test_kill.rs index 40b9cec67..7581086a0 100644 --- a/tests/by-util/test_kill.rs +++ b/tests/by-util/test_kill.rs @@ -13,8 +13,8 @@ impl Target { // Creates a target that will naturally die after some time if not killed // fast enough. // This timeout avoids hanging failing tests. - fn new() -> Target { - Target { + fn new() -> Self { + Self { child: Command::new("sleep") .arg("30") .spawn() diff --git a/tests/by-util/test_split.rs b/tests/by-util/test_split.rs index 2005c0235..8e61c5153 100644 --- a/tests/by-util/test_split.rs +++ b/tests/by-util/test_split.rs @@ -32,8 +32,8 @@ struct Glob { } impl Glob { - fn new(at: &AtPath, directory: &str, regex: &str) -> Glob { - Glob { + fn new(at: &AtPath, directory: &str, regex: &str) -> Self { + Self { directory: AtPath::new(Path::new(&at.plus_as_string(directory))), regex: Regex::new(regex).unwrap(), } @@ -83,8 +83,8 @@ impl RandomFile { const LINESIZE: usize = 32; /// `create()` file handle located at `at` / `name` - fn new(at: &AtPath, name: &str) -> RandomFile { - RandomFile { + fn new(at: &AtPath, name: &str) -> Self { + Self { inner: File::create(&at.plus(name)).unwrap(), } } @@ -113,7 +113,7 @@ impl RandomFile { fn add_lines(&mut self, lines: usize) { let mut n = lines; while n > 0 { - writeln!(self.inner, "{}", random_chars(RandomFile::LINESIZE)).unwrap(); + writeln!(self.inner, "{}", random_chars(Self::LINESIZE)).unwrap(); n -= 1; } } diff --git a/tests/common/util.rs b/tests/common/util.rs index 5b293c216..d21aea968 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -88,8 +88,8 @@ impl CmdResult { success: bool, stdout: &[u8], stderr: &[u8], - ) -> CmdResult { - CmdResult { + ) -> Self { + Self { bin_path, util_name, tmpd, @@ -150,7 +150,7 @@ impl CmdResult { self.code.expect("Program must be run first") } - pub fn code_is(&self, expected_code: i32) -> &CmdResult { + pub fn code_is(&self, expected_code: i32) -> &Self { assert_eq!(self.code(), expected_code); self } @@ -170,7 +170,7 @@ impl CmdResult { } /// asserts that the command resulted in a success (zero) status code - pub fn success(&self) -> &CmdResult { + pub fn success(&self) -> &Self { assert!( self.success, "Command was expected to succeed.\nstdout = {}\n stderr = {}", @@ -181,7 +181,7 @@ impl CmdResult { } /// asserts that the command resulted in a failure (non-zero) status code - pub fn failure(&self) -> &CmdResult { + pub fn failure(&self) -> &Self { assert!( !self.success, "Command was expected to fail.\nstdout = {}\n stderr = {}", @@ -192,7 +192,7 @@ impl CmdResult { } /// asserts that the command's exit code is the same as the given one - pub fn status_code(&self, code: i32) -> &CmdResult { + pub fn status_code(&self, code: i32) -> &Self { assert_eq!(self.code, Some(code)); self } @@ -202,7 +202,7 @@ impl CmdResult { /// but you might find yourself using this function if /// 1. you can not know exactly what stdout will be or /// 2. you know that stdout will also be empty - pub fn no_stderr(&self) -> &CmdResult { + pub fn no_stderr(&self) -> &Self { assert!( self.stderr.is_empty(), "Expected stderr to be empty, but it's:\n{}", @@ -217,7 +217,7 @@ impl CmdResult { /// but you might find yourself using this function if /// 1. you can not know exactly what stderr will be or /// 2. you know that stderr will also be empty - pub fn no_stdout(&self) -> &CmdResult { + pub fn no_stdout(&self) -> &Self { assert!( self.stdout.is_empty(), "Expected stdout to be empty, but it's:\n{}", @@ -229,13 +229,13 @@ impl CmdResult { /// asserts that the command resulted in stdout stream output that equals the /// passed in value, trailing whitespace are kept to force strict comparison (#1235) /// stdout_only is a better choice unless stderr may or will be non-empty - pub fn stdout_is>(&self, msg: T) -> &CmdResult { + pub fn stdout_is>(&self, msg: T) -> &Self { assert_eq!(self.stdout_str(), String::from(msg.as_ref())); self } /// like `stdout_is`, but succeeds if any elements of `expected` matches stdout. - pub fn stdout_is_any + std::fmt::Debug>(&self, expected: &[T]) -> &CmdResult { + pub fn stdout_is_any + std::fmt::Debug>(&self, expected: &[T]) -> &Self { if !expected.iter().any(|msg| self.stdout_str() == msg.as_ref()) { panic!( "stdout was {}\nExpected any of {:#?}", @@ -247,7 +247,7 @@ impl CmdResult { } /// Like `stdout_is` but newlines are normalized to `\n`. - pub fn normalized_newlines_stdout_is>(&self, msg: T) -> &CmdResult { + pub fn normalized_newlines_stdout_is>(&self, msg: T) -> &Self { let msg = msg.as_ref().replace("\r\n", "\n"); assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg); self @@ -255,13 +255,13 @@ impl CmdResult { /// asserts that the command resulted in stdout stream output, /// whose bytes equal those of the passed in slice - pub fn stdout_is_bytes>(&self, msg: T) -> &CmdResult { + pub fn stdout_is_bytes>(&self, msg: T) -> &Self { assert_eq!(self.stdout, msg.as_ref()); self } /// like stdout_is(...), but expects the contents of the file at the provided relative path - pub fn stdout_is_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stdout_is_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_is(String::from_utf8(contents).unwrap()) } @@ -271,7 +271,7 @@ impl CmdResult { &self, file_rel_path: T, template_vars: &[(&str, &str)], - ) -> &CmdResult { + ) -> &Self { let mut contents = String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap(); for kv in template_vars { @@ -300,7 +300,7 @@ impl CmdResult { /// asserts that the command resulted in stderr stream output that equals the /// passed in value, when both are trimmed of trailing whitespace /// stderr_only is a better choice unless stdout may or will be non-empty - pub fn stderr_is>(&self, msg: T) -> &CmdResult { + pub fn stderr_is>(&self, msg: T) -> &Self { assert_eq!( self.stderr_str().trim_end(), String::from(msg.as_ref()).trim_end() @@ -310,13 +310,13 @@ impl CmdResult { /// asserts that the command resulted in stderr stream output, /// whose bytes equal those of the passed in slice - pub fn stderr_is_bytes>(&self, msg: T) -> &CmdResult { + pub fn stderr_is_bytes>(&self, msg: T) -> &Self { assert_eq!(self.stderr, msg.as_ref()); self } /// Like stdout_is_fixture, but for stderr - pub fn stderr_is_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stderr_is_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stderr_is(String::from_utf8(contents).unwrap()) } @@ -325,7 +325,7 @@ impl CmdResult { /// 1. the command resulted in stdout stream output that equals the /// passed in value /// 2. the command resulted in empty (zero-length) stderr stream output - pub fn stdout_only>(&self, msg: T) -> &CmdResult { + pub fn stdout_only>(&self, msg: T) -> &Self { self.no_stderr().stdout_is(msg) } @@ -333,12 +333,12 @@ impl CmdResult { /// 1. the command resulted in a stdout stream whose bytes /// equal those of the passed in value /// 2. the command resulted in an empty stderr stream - pub fn stdout_only_bytes>(&self, msg: T) -> &CmdResult { + pub fn stdout_only_bytes>(&self, msg: T) -> &Self { self.no_stderr().stdout_is_bytes(msg) } /// like stdout_only(...), but expects the contents of the file at the provided relative path - pub fn stdout_only_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stdout_only_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_only_bytes(contents) } @@ -347,7 +347,7 @@ impl CmdResult { /// 1. the command resulted in stderr stream output that equals the /// passed in value, when both are trimmed of trailing whitespace /// 2. the command resulted in empty (zero-length) stdout stream output - pub fn stderr_only>(&self, msg: T) -> &CmdResult { + pub fn stderr_only>(&self, msg: T) -> &Self { self.no_stdout().stderr_is(msg) } @@ -355,11 +355,11 @@ impl CmdResult { /// 1. the command resulted in a stderr stream whose bytes equal the ones /// of the passed value /// 2. the command resulted in an empty stdout stream - pub fn stderr_only_bytes>(&self, msg: T) -> &CmdResult { + pub fn stderr_only_bytes>(&self, msg: T) -> &Self { self.no_stderr().stderr_is_bytes(msg) } - pub fn fails_silently(&self) -> &CmdResult { + pub fn fails_silently(&self) -> &Self { assert!(!self.success); assert!(self.stderr.is_empty()); self @@ -373,7 +373,7 @@ impl CmdResult { /// `msg` should be the same as the one provided to UUsageError::new or show_error! /// /// 2. the command resulted in empty (zero-length) stdout stream output - pub fn usage_error>(&self, msg: T) -> &CmdResult { + pub fn usage_error>(&self, msg: T) -> &Self { self.stderr_only(format!( "{0}: {2}\nTry '{1} {0} --help' for more information.", self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command @@ -382,7 +382,7 @@ impl CmdResult { )) } - pub fn stdout_contains>(&self, cmp: T) -> &CmdResult { + pub fn stdout_contains>(&self, cmp: T) -> &Self { assert!( self.stdout_str().contains(cmp.as_ref()), "'{}' does not contain '{}'", @@ -392,7 +392,7 @@ impl CmdResult { self } - pub fn stderr_contains>(&self, cmp: T) -> &CmdResult { + pub fn stderr_contains>(&self, cmp: T) -> &Self { assert!( self.stderr_str().contains(cmp.as_ref()), "'{}' does not contain '{}'", @@ -402,7 +402,7 @@ impl CmdResult { self } - pub fn stdout_does_not_contain>(&self, cmp: T) -> &CmdResult { + pub fn stdout_does_not_contain>(&self, cmp: T) -> &Self { assert!( !self.stdout_str().contains(cmp.as_ref()), "'{}' contains '{}' but should not", @@ -412,19 +412,19 @@ impl CmdResult { self } - pub fn stderr_does_not_contain>(&self, cmp: T) -> &CmdResult { + pub fn stderr_does_not_contain>(&self, cmp: T) -> &Self { assert!(!self.stderr_str().contains(cmp.as_ref())); self } - pub fn stdout_matches(&self, regex: ®ex::Regex) -> &CmdResult { + pub fn stdout_matches(&self, regex: ®ex::Regex) -> &Self { if !regex.is_match(self.stdout_str().trim()) { panic!("Stdout does not match regex:\n{}", self.stdout_str()); } self } - pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &CmdResult { + pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &Self { if regex.is_match(self.stdout_str().trim()) { panic!("Stdout matches regex:\n{}", self.stdout_str()); } @@ -469,8 +469,8 @@ pub struct AtPath { } impl AtPath { - pub fn new(subdir: &Path) -> AtPath { - AtPath { + pub fn new(subdir: &Path) -> Self { + Self { subdir: PathBuf::from(subdir), } } @@ -776,9 +776,9 @@ pub struct TestScenario { } impl TestScenario { - pub fn new(util_name: &str) -> TestScenario { + pub fn new(util_name: &str) -> Self { let tmpd = Rc::new(TempDir::new().unwrap()); - let ts = TestScenario { + let ts = Self { bin_path: { // Instead of hard coding the path relative to the current // directory, use Cargo's OUT_DIR to find path to executable. @@ -875,11 +875,11 @@ impl UCommand { util_name: &Option, curdir: U, env_clear: bool, - ) -> UCommand { + ) -> Self { let bin_path = bin_path.as_ref(); let util_name = util_name.as_ref().map(|un| un.as_ref()); - let mut ucmd = UCommand { + let mut ucmd = Self { tmpd: None, has_run: false, raw: { @@ -927,31 +927,31 @@ impl UCommand { util_name: &Option, tmpd: Rc, env_clear: bool, - ) -> UCommand { + ) -> Self { let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap())); - let mut ucmd: UCommand = UCommand::new(bin_path, util_name, tmpd_path_buf, env_clear); + let mut ucmd: Self = Self::new(bin_path, util_name, tmpd_path_buf, env_clear); ucmd.tmpd = Some(tmpd); ucmd } - pub fn set_stdin>(&mut self, stdin: T) -> &mut UCommand { + pub fn set_stdin>(&mut self, stdin: T) -> &mut Self { self.stdin = Some(stdin.into()); self } - pub fn set_stdout>(&mut self, stdout: T) -> &mut UCommand { + pub fn set_stdout>(&mut self, stdout: T) -> &mut Self { self.stdout = Some(stdout.into()); self } - pub fn set_stderr>(&mut self, stderr: T) -> &mut UCommand { + pub fn set_stderr>(&mut self, stderr: T) -> &mut Self { self.stderr = Some(stderr.into()); self } /// Add a parameter to the invocation. Path arguments are treated relative /// to the test environment directory. - pub fn arg>(&mut self, arg: S) -> &mut UCommand { + pub fn arg>(&mut self, arg: S) -> &mut Self { assert!(!self.has_run, "{}", ALREADY_RUN); self.comm_string.push(' '); self.comm_string @@ -962,7 +962,7 @@ impl UCommand { /// Add multiple parameters to the invocation. Path arguments are treated relative /// to the test environment directory. - pub fn args>(&mut self, args: &[S]) -> &mut UCommand { + pub fn args>(&mut self, args: &[S]) -> &mut Self { assert!(!self.has_run, "{}", MULTIPLE_STDIN_MEANINGLESS); let strings = args .iter() @@ -980,7 +980,7 @@ impl UCommand { } /// provides standard input to feed in to the command when spawned - pub fn pipe_in>>(&mut self, input: T) -> &mut UCommand { + pub fn pipe_in>>(&mut self, input: T) -> &mut Self { assert!( self.bytes_into_stdin.is_none(), "{}", @@ -991,7 +991,7 @@ impl UCommand { } /// like pipe_in(...), but uses the contents of the file at the provided relative path as the piped in data - pub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> &mut UCommand { + pub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> &mut Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.pipe_in(contents) } @@ -999,13 +999,13 @@ impl UCommand { /// Ignores error caused by feeding stdin to the command. /// This is typically useful to test non-standard workflows /// like feeding something to a command that does not read it - pub fn ignore_stdin_write_error(&mut self) -> &mut UCommand { + pub fn ignore_stdin_write_error(&mut self) -> &mut Self { assert!(self.bytes_into_stdin.is_some(), "{}", NO_STDIN_MEANINGLESS); self.ignore_stdin_write_error = true; self } - pub fn env(&mut self, key: K, val: V) -> &mut UCommand + pub fn env(&mut self, key: K, val: V) -> &mut Self where K: AsRef, V: AsRef,