From 538b69d46059f6eba283e5e214f5dd59179c2dc7 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 5 Feb 2026 17:05:15 +0000 Subject: [PATCH 1/3] clippy: fix str_to_string lint https://rust-lang.github.io/rust-clippy/master/index.html#str_to_string --- Cargo.toml | 2 + fuzz/fuzz_targets/fuzz_cksum.rs | 16 ++-- fuzz/fuzz_targets/fuzz_dirname.rs | 12 +-- fuzz/fuzz_targets/fuzz_non_utf8_paths.rs | 16 ++-- fuzz/fuzz_targets/fuzz_test.rs | 34 +++---- fuzz/uufuzz/examples/simple_integration.rs | 2 +- fuzz/uufuzz/src/lib.rs | 40 ++++---- src/bin/uudoc.rs | 4 +- src/uu/chgrp/src/chgrp.rs | 2 +- src/uu/chmod/src/chmod.rs | 8 +- src/uu/chroot/src/chroot.rs | 20 ++-- src/uu/cp/src/cp.rs | 4 +- src/uu/csplit/src/csplit.rs | 8 +- src/uu/csplit/src/patterns.rs | 14 +-- src/uu/csplit/src/split_name.rs | 2 +- src/uu/date/src/date.rs | 6 +- src/uu/date/src/locale.rs | 8 +- src/uu/dd/src/parseargs.rs | 48 +++++----- src/uu/df/src/columns.rs | 2 +- src/uu/df/src/filesystem.rs | 2 +- src/uu/df/src/table.rs | 46 ++++----- src/uu/dircolors/src/dircolors.rs | 10 +- src/uu/du/src/du.rs | 16 ++-- src/uu/expand/src/expand.rs | 10 +- src/uu/expr/src/syntax_tree.rs | 14 +-- src/uu/fmt/src/fmt.rs | 2 +- src/uu/fold/src/fold.rs | 2 +- src/uu/head/src/parse.rs | 2 +- src/uu/install/src/install.rs | 6 +- src/uu/join/benches/join_bench.rs | 12 +-- src/uu/ln/src/ln.rs | 2 +- src/uu/ls/src/colors.rs | 2 +- src/uu/ls/src/dired.rs | 4 +- src/uu/ls/src/ls.rs | 10 +- src/uu/mktemp/src/mktemp.rs | 8 +- src/uu/more/src/more.rs | 8 +- src/uu/mv/benches/mv_bench.rs | 16 ++-- src/uu/nohup/src/nohup.rs | 2 +- src/uu/numfmt/benches/numfmt_bench.rs | 14 +-- src/uu/od/src/parse_formats.rs | 32 +++---- src/uu/od/src/parse_inputs.rs | 70 +++++++------- src/uu/od/src/parse_nrofbytes.rs | 4 +- src/uu/od/src/prn_float.rs | 2 +- src/uu/pathchk/src/pathchk.rs | 2 +- src/uu/pr/src/pr.rs | 20 ++-- src/uu/rm/benches/rm_bench.rs | 11 +-- src/uu/sort/benches/sort_locale_c_bench.rs | 6 +- src/uu/sort/benches/sort_locale_de_bench.rs | 2 +- src/uu/sort/benches/sort_locale_utf8_bench.rs | 10 +- src/uu/sort/src/sort.rs | 6 +- src/uu/split/benches/split_bench.rs | 8 +- src/uu/split/src/split.rs | 2 +- src/uu/split/src/strategy.rs | 54 +++++------ src/uu/stat/src/stat.rs | 10 +- src/uu/stdbuf/build.rs | 6 +- src/uu/stdbuf/src/libstdbuf/build.rs | 2 +- src/uu/stdbuf/src/stdbuf.rs | 6 +- src/uu/stty/src/stty.rs | 6 +- src/uu/sync/src/sync.rs | 2 +- src/uu/timeout/src/timeout.rs | 4 +- src/uu/touch/src/touch.rs | 6 +- src/uu/truncate/src/truncate.rs | 2 +- src/uu/unexpand/src/unexpand.rs | 8 +- src/uu/uniq/benches/uniq_bench.rs | 2 +- src/uucore/build.rs | 10 +- src/uucore/src/lib/features/backup_control.rs | 4 +- src/uucore/src/lib/features/checksum/mod.rs | 4 +- .../src/lib/features/format/num_format.rs | 2 +- src/uucore/src/lib/features/i18n/decimal.rs | 4 +- .../src/lib/features/parser/num_parser.rs | 96 +++++++++---------- .../lib/features/parser/parse_signed_num.rs | 6 +- .../src/lib/features/parser/parse_size.rs | 12 +-- .../features/parser/shortcut_value_parser.rs | 8 +- src/uucore/src/lib/features/perms.rs | 2 +- src/uucore/src/lib/features/proc_info.rs | 2 +- .../src/lib/features/quoting_style/mod.rs | 2 +- src/uucore/src/lib/features/selinux.rs | 2 +- src/uucore/src/lib/features/smack.rs | 8 +- src/uucore/src/lib/features/systemd_logind.rs | 46 ++++----- src/uucore/src/lib/features/utmpx.rs | 2 +- src/uucore/src/lib/mods/clap_localization.rs | 2 +- src/uucore/src/lib/mods/locale.rs | 32 +++---- tests/by-util/test_b2sum.rs | 2 +- tests/by-util/test_chroot.rs | 2 +- tests/by-util/test_cksum.rs | 2 +- tests/by-util/test_cp.rs | 8 +- tests/by-util/test_date.rs | 2 +- tests/by-util/test_dd.rs | 4 +- tests/by-util/test_df.rs | 38 ++++---- tests/by-util/test_env.rs | 2 +- tests/by-util/test_expr.rs | 2 +- tests/by-util/test_id.rs | 2 +- tests/by-util/test_install.rs | 5 +- tests/by-util/test_ls.rs | 36 +++---- tests/by-util/test_mkfifo.rs | 6 +- tests/by-util/test_numfmt.rs | 4 +- tests/by-util/test_od.rs | 2 +- tests/by-util/test_pinky.rs | 2 +- tests/by-util/test_pr.rs | 2 +- tests/by-util/test_rm.rs | 2 +- tests/by-util/test_sort.rs | 8 +- tests/by-util/test_stdbuf.rs | 2 +- tests/by-util/test_stty.rs | 6 +- tests/by-util/test_wc.rs | 8 +- tests/test_util_name.rs | 2 +- tests/test_uudoc.rs | 2 +- tests/uutests/src/lib/util.rs | 28 +++--- 107 files changed, 568 insertions(+), 574 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5b2b1c83c58..dcef39f675c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -693,5 +693,7 @@ flat_map_option = "allow" from_iter_instead_of_collect = "allow" large_types_passed_by_value = "allow" +str_to_string = "warn" + [workspace.metadata.cargo-shear] ignored = ["clap", "fluent", "libstdbuf"] diff --git a/fuzz/fuzz_targets/fuzz_cksum.rs b/fuzz/fuzz_targets/fuzz_cksum.rs index be93a96050e..8458007f0fe 100644 --- a/fuzz/fuzz_targets/fuzz_cksum.rs +++ b/fuzz/fuzz_targets/fuzz_cksum.rs @@ -40,16 +40,16 @@ fn generate_cksum_args() -> Vec { ]; if rng.random_bool(0.3) { - args.push("-a".to_string()); - args.push(digests[rng.random_range(0..digests.len())].to_string()); + args.push("-a".to_owned()); + args.push(digests[rng.random_range(0..digests.len())].to_owned()); } if rng.random_bool(0.2) { - args.push(digest_opts[rng.random_range(0..digest_opts.len())].to_string()); + args.push(digest_opts[rng.random_range(0..digest_opts.len())].to_owned()); } if rng.random_bool(0.15) { - args.push("-l".to_string()); + args.push("-l".to_owned()); args.push(rng.random_range(8..513).to_string()); } @@ -58,7 +58,7 @@ fn generate_cksum_args() -> Vec { args.push(format!("file_{}", generate_random_string(5))); } } else { - args.push("-c".to_string()); + args.push("-c".to_owned()); } if rng.random_bool(0.25) { @@ -68,8 +68,8 @@ fn generate_cksum_args() -> Vec { } if args.is_empty() || !args.iter().any(|arg| arg.starts_with("file_")) { - args.push("-a".to_string()); - args.push(digests[rng.random_range(0..digests.len())].to_string()); + args.push("-a".to_owned()); + args.push(digests[rng.random_range(0..digests.len())].to_owned()); if let Ok(file_path) = generate_random_file() { args.push(file_path); @@ -98,7 +98,7 @@ fn generate_checksum_file( let mut checksum_file = File::create(&checksum_file_path)?; checksum_file.write_all(&output.stdout)?; - Ok(checksum_file_path.to_str().unwrap().to_string()) + Ok(checksum_file_path.to_str().unwrap().to_owned()) } fn select_random_digest_opts<'a>( diff --git a/fuzz/fuzz_targets/fuzz_dirname.rs b/fuzz/fuzz_targets/fuzz_dirname.rs index bfb127a5a5a..26a5f1bf4bb 100644 --- a/fuzz/fuzz_targets/fuzz_dirname.rs +++ b/fuzz/fuzz_targets/fuzz_dirname.rs @@ -23,9 +23,9 @@ fn generate_dirname_args() -> Vec { // 20% chance to include -z/--zero flag if rng.random_bool(0.2) { if rng.random_bool(0.5) { - args.push("-z".to_string()); + args.push("-z".to_owned()); } else { - args.push("--zero".to_string()); + args.push("--zero".to_owned()); } } @@ -77,11 +77,11 @@ fn generate_path() -> String { } // Root path - 2 => "/".to_string(), + 2 => "/".to_owned(), // Absolute paths 3 => { - let mut path = "/".to_string(); + let mut path = "/".to_owned(); let components = rng.random_range(1..=4); for _ in 0..components { path.push_str(&generate_random_string(rng.random_range(1..=8))); @@ -97,7 +97,7 @@ fn generate_path() -> String { // Paths ending with "/." (specific case from issue #8924) 4 => { let base = if rng.random_bool(0.3) { - "/".to_string() + "/".to_owned() } else { format!("/{}", generate_random_string(rng.random_range(1..=10))) }; @@ -132,7 +132,7 @@ fn generate_path() -> String { } // Empty string (edge case) - 8 => "".to_string(), + 8 => "".to_owned(), // Issue #8924 specific cases: paths like "foo//." 9 => { diff --git a/fuzz/fuzz_targets/fuzz_non_utf8_paths.rs b/fuzz/fuzz_targets/fuzz_non_utf8_paths.rs index 56451502ba9..e72150857a7 100644 --- a/fuzz/fuzz_targets/fuzz_non_utf8_paths.rs +++ b/fuzz/fuzz_targets/fuzz_non_utf8_paths.rs @@ -160,7 +160,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult // Use the locally built uutils binary instead of system PATH let local_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); // Build appropriate arguments for each program let local_args = match program { @@ -187,7 +187,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult ], "runcon" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from("system_u:object_r:admin_home_t:s0"), @@ -271,7 +271,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult "tty" => vec![OsString::from(program)], // tty doesn't take file args, but test anyway "env" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from(coreutils_binary), @@ -281,7 +281,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult } "nohup" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from(coreutils_binary), @@ -291,7 +291,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult } "nice" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from(coreutils_binary), @@ -301,7 +301,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult } "timeout" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from("1"), @@ -312,7 +312,7 @@ fn test_program_with_non_utf8_path(program: &str, path: &Path) -> CommandResult } "stdbuf" => { let coreutils_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); vec![ OsString::from(program), OsString::from("-o0"), @@ -413,7 +413,7 @@ fuzz_target!(|_data: &[u8]| { let non_utf8_dir = temp_root.join(non_utf8_dir_name); let local_binary = std::env::var("CARGO_BIN_FILE_COREUTILS") - .unwrap_or_else(|_| "target/release/coreutils".to_string()); + .unwrap_or_else(|_| "target/release/coreutils".to_owned()); let mkdir_args = vec![OsString::from("mkdir"), non_utf8_dir.as_os_str().to_owned()]; let mkdir_result = run_gnu_cmd(&local_binary, &mkdir_args, false, None); diff --git a/fuzz/fuzz_targets/fuzz_test.rs b/fuzz/fuzz_targets/fuzz_test.rs index 176ab9aba8f..23d92db4e67 100644 --- a/fuzz/fuzz_targets/fuzz_test.rs +++ b/fuzz/fuzz_targets/fuzz_test.rs @@ -47,71 +47,71 @@ fn generate_random_path(rng: &mut dyn rand::RngCore) -> &'static str { fn generate_test_args() -> Vec { vec![ TestArg { - arg: "-z".to_string(), + arg: "-z".to_owned(), arg_type: ArgType::STRING, }, TestArg { - arg: "-n".to_string(), + arg: "-n".to_owned(), arg_type: ArgType::STRING, }, TestArg { - arg: "=".to_string(), + arg: "=".to_owned(), arg_type: ArgType::STRINGSTRING, }, TestArg { - arg: "!=".to_string(), + arg: "!=".to_owned(), arg_type: ArgType::STRINGSTRING, }, TestArg { - arg: ">".to_string(), + arg: ">".to_owned(), arg_type: ArgType::STRINGSTRING, }, TestArg { - arg: "<".to_string(), + arg: "<".to_owned(), arg_type: ArgType::STRINGSTRING, }, TestArg { - arg: "-eq".to_string(), + arg: "-eq".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-ne".to_string(), + arg: "-ne".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-gt".to_string(), + arg: "-gt".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-ge".to_string(), + arg: "-ge".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-lt".to_string(), + arg: "-lt".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-le".to_string(), + arg: "-le".to_owned(), arg_type: ArgType::INTEGERINTEGER, }, TestArg { - arg: "-f".to_string(), + arg: "-f".to_owned(), arg_type: ArgType::FILE, }, TestArg { - arg: "-d".to_string(), + arg: "-d".to_owned(), arg_type: ArgType::FILE, }, TestArg { - arg: "-e".to_string(), + arg: "-e".to_owned(), arg_type: ArgType::FILE, }, TestArg { - arg: "-ef".to_string(), + arg: "-ef".to_owned(), arg_type: ArgType::FILEFILE, }, TestArg { - arg: "-nt".to_string(), + arg: "-nt".to_owned(), arg_type: ArgType::FILEFILE, }, ] diff --git a/fuzz/uufuzz/examples/simple_integration.rs b/fuzz/uufuzz/examples/simple_integration.rs index 709fb61b3f1..50bdeac95d8 100644 --- a/fuzz/uufuzz/examples/simple_integration.rs +++ b/fuzz/uufuzz/examples/simple_integration.rs @@ -80,7 +80,7 @@ fn main() { // Simulate our own echo implementation result let our_result = CommandResult { - stdout: "hello world\n".to_string(), + stdout: "hello world\n".to_owned(), stderr: String::new(), exit_code: 0, }; diff --git a/fuzz/uufuzz/src/lib.rs b/fuzz/uufuzz/src/lib.rs index e94ffd8b189..4af9b1c23ad 100644 --- a/fuzz/uufuzz/src/lib.rs +++ b/fuzz/uufuzz/src/lib.rs @@ -72,8 +72,8 @@ where let original_stderr_fd = unsafe { dup(STDERR_FILENO) }; if original_stdout_fd == -1 || original_stderr_fd == -1 { return CommandResult { - stdout: "".to_string(), - stderr: "Failed to duplicate STDOUT_FILENO or STDERR_FILENO".to_string(), + stdout: "".to_owned(), + stderr: "Failed to duplicate STDOUT_FILENO or STDERR_FILENO".to_owned(), exit_code: -1, }; } @@ -87,8 +87,8 @@ where || unsafe { pipe(pipe_stderr_fds.as_mut_ptr()) } == -1 { return CommandResult { - stdout: "".to_string(), - stderr: "Failed to create pipes".to_string(), + stdout: "".to_owned(), + stderr: "Failed to create pipes".to_owned(), exit_code: -1, }; } @@ -104,8 +104,8 @@ where close(pipe_stderr_fds[1]); } return CommandResult { - stdout: "".to_string(), - stderr: "Failed to redirect STDOUT_FILENO or STDERR_FILENO".to_string(), + stdout: "".to_owned(), + stderr: "Failed to redirect STDOUT_FILENO or STDERR_FILENO".to_owned(), exit_code: -1, }; } @@ -120,8 +120,8 @@ where let original_stdin_fd = unsafe { dup(STDIN_FILENO) }; if original_stdin_fd == -1 || unsafe { dup2(input_file.as_raw_fd(), STDIN_FILENO) } == -1 { return CommandResult { - stdout: "".to_string(), - stderr: "Failed to set up stdin redirection".to_string(), + stdout: "".to_owned(), + stderr: "Failed to set up stdin redirection".to_owned(), exit_code: -1, }; } @@ -155,8 +155,8 @@ where || unsafe { dup2(original_stderr_fd, STDERR_FILENO) } == -1 { return CommandResult { - stdout: "".to_string(), - stderr: "Failed to restore the original STDOUT_FILENO or STDERR_FILENO".to_string(), + stdout: "".to_owned(), + stderr: "Failed to restore the original STDOUT_FILENO or STDERR_FILENO".to_owned(), exit_code: -1, }; } @@ -169,8 +169,8 @@ where if let Some(fd) = original_stdin_fd { if unsafe { dup2(fd, STDIN_FILENO) } == -1 { return CommandResult { - stdout: "".to_string(), - stderr: "Failed to restore the original STDIN".to_string(), + stdout: "".to_owned(), + stderr: "Failed to restore the original STDIN".to_owned(), exit_code: -1, }; } @@ -183,8 +183,7 @@ where .split_once(':') .map(|x| x.1) .unwrap_or("") - .trim() - .to_string(), + .trim().to_owned(), exit_code: uumain_exit_status, } } @@ -284,8 +283,7 @@ pub fn run_gnu_cmd( .split_once(':') .map(|x| x.1) .unwrap_or("") - .trim() - .to_string(); + .trim().to_owned(); if output.status.success() || !check_gnu { Ok(CommandResult { @@ -423,7 +421,7 @@ pub fn generate_random_file() -> Result { file.write_all(content.as_bytes())?; - Ok(file_path.to_str().unwrap().to_string()) + Ok(file_path.to_str().unwrap().to_owned()) } #[allow(dead_code)] @@ -442,8 +440,8 @@ mod tests { #[test] fn test_command_result_creation() { let result = CommandResult { - stdout: "Hello, world!".to_string(), - stderr: "".to_string(), + stdout: "Hello, world!".to_owned(), + stderr: "".to_owned(), exit_code: 0, }; @@ -466,8 +464,8 @@ mod tests { #[test] fn test_replace_fuzz_binary_name() { let mut result = CommandResult { - stdout: "fuzz/target/x86_64-unknown-linux-gnu/release/fuzz_echo: error".to_string(), - stderr: "fuzz/target/x86_64-unknown-linux-gnu/release/fuzz_echo failed".to_string(), + stdout: "fuzz/target/x86_64-unknown-linux-gnu/release/fuzz_echo: error".to_owned(), + stderr: "fuzz/target/x86_64-unknown-linux-gnu/release/fuzz_echo failed".to_owned(), exit_code: 1, }; diff --git a/src/bin/uudoc.rs b/src/bin/uudoc.rs index 76f04774ec7..68e38e0ac44 100644 --- a/src/bin/uudoc.rs +++ b/src/bin/uudoc.rs @@ -300,7 +300,7 @@ fn main() -> io::Result<()> { tldr_zip: &mut tldr_zip, utils_per_platform: &utils_per_platform, fluent, - fluent_key: utils_name.to_string(), + fluent_key: utils_name.to_owned(), } .markdown()?; println!("Wrote to '{p}'"); @@ -323,7 +323,7 @@ fn fix_usage(name: &str, usage: String) -> String { if i > 1 { l.replace("test", "[") } else { - l.to_string() + l.to_owned() } }) .collect::>() diff --git a/src/uu/chgrp/src/chgrp.rs b/src/uu/chgrp/src/chgrp.rs index f681da37eed..357bdc7112e 100644 --- a/src/uu/chgrp/src/chgrp.rs +++ b/src/uu/chgrp/src/chgrp.rs @@ -53,7 +53,7 @@ fn get_dest_gid(matches: &ArgMatches) -> UResult<(Option, String)> { .get_one::(options::ARG_GROUP) .map(|s| s.as_str()) .unwrap_or_default(); - raw_group = group.to_string(); + raw_group = group.to_owned(); if group.is_empty() { None } else { diff --git a/src/uu/chmod/src/chmod.rs b/src/uu/chmod/src/chmod.rs index 78dccffdc25..843f425c92a 100644 --- a/src/uu/chmod/src/chmod.rs +++ b/src/uu/chmod/src/chmod.rs @@ -71,7 +71,7 @@ fn extract_negative_modes(mut args: impl uucore::Args) -> (Option, Vec, Vec) = args.by_ref().take_while(|a| a != "--").partition(|arg| { let arg = if let Some(arg) = arg.to_str() { - arg.to_string() + arg.to_owned() } else { return false; }; @@ -720,19 +720,19 @@ mod tests { // "chmod -w -r file" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE. // Therefore, "w" is added as pseudo mode to pass clap. let (c, a) = extract_negative_modes(["-w", "-r", "file"].iter().map(OsString::from)); - assert_eq!(c, Some("-w,-r".to_string())); + assert_eq!(c, Some("-w,-r".to_owned())); assert_eq!(a, ["w", "file"]); // "chmod -w file -r" becomes "chmod -w,-r file". clap does not accept "-w,-r" as MODE. // Therefore, "w" is added as pseudo mode to pass clap. let (c, a) = extract_negative_modes(["-w", "file", "-r"].iter().map(OsString::from)); - assert_eq!(c, Some("-w,-r".to_string())); + assert_eq!(c, Some("-w,-r".to_owned())); assert_eq!(a, ["w", "file"]); // "chmod -w -- -r file" becomes "chmod -w -r file", where "-r" is interpreted as file. // Again, "w" is needed as pseudo mode. let (c, a) = extract_negative_modes(["-w", "--", "-r", "f"].iter().map(OsString::from)); - assert_eq!(c, Some("-w".to_string())); + assert_eq!(c, Some("-w".to_owned())); assert_eq!(a, ["w", "--", "-r", "f"]); // "chmod -- -r file" becomes "chmod -r file". diff --git a/src/uu/chroot/src/chroot.rs b/src/uu/chroot/src/chroot.rs index 04cb8c0c965..f7983e750e5 100644 --- a/src/uu/chroot/src/chroot.rs +++ b/src/uu/chroot/src/chroot.rs @@ -58,15 +58,15 @@ fn parse_userspec(spec: &str) -> UserSpec { // "" None if spec.is_empty() => UserSpec::NeitherGroupNorUser, // "usr" - None => UserSpec::UserOnly(spec.to_string()), + None => UserSpec::UserOnly(spec.to_owned()), // ":" Some(("", "")) => UserSpec::NeitherGroupNorUser, // ":grp" - Some(("", grp)) => UserSpec::GroupOnly(grp.to_string()), + Some(("", grp)) => UserSpec::GroupOnly(grp.to_owned()), // "usr:" - Some((usr, "")) => UserSpec::UserOnly(usr.to_string()), + Some((usr, "")) => UserSpec::UserOnly(usr.to_owned()), // "usr:grp" - Some((usr, grp)) => UserSpec::UserAndGroup(usr.to_string(), grp.to_string()), + Some((usr, grp)) => UserSpec::UserAndGroup(usr.to_owned(), grp.to_owned()), } } @@ -78,15 +78,15 @@ fn parse_group_list(list_str: &str) -> Result, ChrootError> { if name.is_empty() { // --groups=" " // chroot: invalid group ' ' - Err(ChrootError::InvalidGroup(name.to_string())) + Err(ChrootError::InvalidGroup(name.to_owned())) } else { // --groups="blah" - Ok(vec![name.to_string()]) + Ok(vec![name.to_owned()]) } } else if split.iter().all(|s| s.is_empty()) { // --groups="," // chroot: invalid group list ',' - Err(ChrootError::InvalidGroupList(list_str.to_string())) + Err(ChrootError::InvalidGroupList(list_str.to_owned())) } else { let mut result = vec![]; let mut err = false; @@ -100,7 +100,7 @@ fn parse_group_list(list_str: &str) -> Result, ChrootError> { // --groups=", " // chroot: invalid group ' ' - show!(ChrootError::InvalidGroup(name.to_string())); + show!(ChrootError::InvalidGroup(name.to_owned())); err = true; } else { // TODO Figure out a better condition here. @@ -109,10 +109,10 @@ fn parse_group_list(list_str: &str) -> Result, ChrootError> { { // --groups="0trail" // chroot: invalid group '0trail' - show!(ChrootError::InvalidGroup(name.to_string())); + show!(ChrootError::InvalidGroup(name.to_owned())); err = true; } else { - result.push(trimmed_name.to_string()); + result.push(trimmed_name.to_owned()); } } } diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 04a3c1c0110..83e1e2449f3 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -103,7 +103,7 @@ pub enum CpError { // Manual impl for &str impl From<&'static str> for CpError { fn from(s: &'static str) -> Self { - Self::Error(s.to_string()) + Self::Error(s.to_owned()) } } @@ -1022,7 +1022,7 @@ impl Options { && matches.value_source(not_implemented_opt) == Some(clap::parser::ValueSource::CommandLine) { - return Err(CpError::NotImplemented(not_implemented_opt.to_string())); + return Err(CpError::NotImplemented(not_implemented_opt.to_owned())); } } diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index c52a95c3a10..bb1a48aac7d 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -366,7 +366,7 @@ impl SplitWriter<'_> { input_iter.rewind_buffer(); input_iter.set_size_of_buffer(1); - let mut ret = Err(CsplitError::LineOutOfRange(pattern_as_str.to_string())); + let mut ret = Err(CsplitError::LineOutOfRange(pattern_as_str.to_owned())); while let Some((ln, line)) = input_iter.next() { let line = line?; match n.cmp(&(&ln + 1)) { @@ -457,7 +457,7 @@ impl SplitWriter<'_> { self.writeln(&line?)?; } else { self.finish_split()?; - return Err(CsplitError::LineOutOfRange(pattern_as_str.to_string())); + return Err(CsplitError::LineOutOfRange(pattern_as_str.to_owned())); } offset -= 1; } @@ -504,7 +504,7 @@ impl SplitWriter<'_> { self.finish_split()?; if input_iter.buffer_len() < offset_usize { - return Err(CsplitError::LineOutOfRange(pattern_as_str.to_string())); + return Err(CsplitError::LineOutOfRange(pattern_as_str.to_owned())); } return Ok(()); } @@ -519,7 +519,7 @@ impl SplitWriter<'_> { } self.finish_split()?; - Err(CsplitError::MatchNotFound(pattern_as_str.to_string())) + Err(CsplitError::MatchNotFound(pattern_as_str.to_owned())) } } diff --git a/src/uu/csplit/src/patterns.rs b/src/uu/csplit/src/patterns.rs index 6710484e9e5..010ba5f3339 100644 --- a/src/uu/csplit/src/patterns.rs +++ b/src/uu/csplit/src/patterns.rs @@ -185,7 +185,7 @@ mod tests { #[test] fn bad_pattern() { - let input = vec!["bad".to_string()]; + let input = vec!["bad".to_owned()]; assert!(get_patterns(input.as_slice()).is_err()); } @@ -193,7 +193,7 @@ mod tests { fn up_to_line_pattern() { let input: Vec = vec!["24", "42", "{*}", "50", "{4}"] .into_iter() - .map(|v| v.to_string()) + .map(|v| v.to_owned()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 3); @@ -225,7 +225,7 @@ mod tests { "/test6.*end$/-3", ] .into_iter() - .map(|v| v.to_string()) + .map(|v| v.to_owned()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 6); @@ -287,7 +287,7 @@ mod tests { "%test6.*end$%-3", ] .into_iter() - .map(|v| v.to_string()) + .map(|v| v.to_owned()) .collect(); let patterns = get_patterns(input.as_slice()).unwrap(); assert_eq!(patterns.len(), 6); @@ -346,7 +346,7 @@ mod tests { #[test] fn line_number_smaller_than_previous() { - let input: Vec = vec!["10".to_string(), "5".to_string()]; + let input: Vec = vec!["10".to_owned(), "5".to_owned()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (), _ => panic!("expected LineNumberSmallerThanPrevious error"), @@ -355,7 +355,7 @@ mod tests { #[test] fn line_number_smaller_than_previous_separate() { - let input: Vec = vec!["10".to_string(), "/20/".to_string(), "5".to_string()]; + let input: Vec = vec!["10".to_owned(), "/20/".to_owned(), "5".to_owned()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberSmallerThanPrevious(5, 10)) => (), _ => panic!("expected LineNumberSmallerThanPrevious error"), @@ -364,7 +364,7 @@ mod tests { #[test] fn line_number_zero_separate() { - let input: Vec = vec!["10".to_string(), "/20/".to_string(), "0".to_string()]; + let input: Vec = vec!["10".to_owned(), "/20/".to_owned(), "0".to_owned()]; match get_patterns(input.as_slice()) { Err(CsplitError::LineNumberIsZero) => (), _ => panic!("expected LineNumberIsZero error"), diff --git a/src/uu/csplit/src/split_name.rs b/src/uu/csplit/src/split_name.rs index 33c606b4888..cffa4c49a3e 100644 --- a/src/uu/csplit/src/split_name.rs +++ b/src/uu/csplit/src/split_name.rs @@ -36,7 +36,7 @@ impl SplitName { n_digits_opt: Option, ) -> Result { // get the prefix - let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); + let prefix = prefix_opt.unwrap_or_else(|| "xx".to_owned()); // the width for the split offset let n_digits = n_digits_opt diff --git a/src/uu/date/src/date.rs b/src/uu/date/src/date.rs index 5e84e5d6ce5..21e9a48e2a3 100644 --- a/src/uu/date/src/date.rs +++ b/src/uu/date/src/date.rs @@ -253,7 +253,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { Format::Custom(form) } else if let Some(fmt) = matches .get_many::(OPT_ISO_8601) - .map(|mut iter| iter.next().unwrap_or(&DATE.to_string()).as_str().into()) + .map(|mut iter| iter.next().unwrap_or(&DATE.to_owned()).as_str().into()) { Format::Iso8601(fmt) } else if matches.get_flag(OPT_RFC_EMAIL) { @@ -710,7 +710,7 @@ fn build_tz_abbrev_map() -> HashMap { // First, add preferred mappings (these take precedence) for (abbrev, iana) in PREFERRED_TZ_MAPPINGS { - map.insert((*abbrev).to_string(), (*iana).to_string()); + map.insert((*abbrev).to_owned(), (*iana).to_owned()); } // Then, try to find additional abbreviations from IANA database @@ -731,7 +731,7 @@ fn build_tz_abbrev_map() -> HashMap { && potential_abbrev.chars().all(|c| c.is_ascii_uppercase()) { map.entry(potential_abbrev) - .or_insert_with(|| tz_str.to_string()); + .or_insert_with(|| tz_str.to_owned()); } } } diff --git a/src/uu/date/src/locale.rs b/src/uu/date/src/locale.rs index c190c1a0dad..bda7de7f372 100644 --- a/src/uu/date/src/locale.rs +++ b/src/uu/date/src/locale.rs @@ -86,14 +86,14 @@ cfg_langinfo! { return None; } - Some(format.to_string()) + Some(format.to_owned()) } } /// Ensures the format string includes timezone (%Z) fn ensure_timezone_in_format(format: &str) -> String { if format.contains("%Z") { - return format.to_string(); + return format.to_owned(); } // Try to insert %Z before year specifier (%Y or %y) @@ -105,7 +105,7 @@ cfg_langinfo! { result } else { // No year found, append %Z at the end - format.to_string() + " %Z" + format.to_owned() + " %Z" } } } @@ -188,7 +188,7 @@ mod tests { if ptr.is_null() { None } else { - CStr::from_ptr(ptr).to_str().ok().map(|s| s.to_string()) + CStr::from_ptr(ptr).to_str().ok().map(|s| s.to_owned()) } }; diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index 3a37d97ffb9..38d123c08ec 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -249,7 +249,7 @@ impl Parser { if skip > i64::MAX as u64 { return Err(ParseError::InvalidNumberWithErrMsg( format!("{skip}"), - "Value too large for defined data type".to_string(), + "Value too large for defined data type".to_owned(), )); } @@ -261,7 +261,7 @@ impl Parser { if seek > i64::MAX as u64 { return Err(ParseError::InvalidNumberWithErrMsg( format!("{seek}"), - "Value too large for defined data type".to_string(), + "Value too large for defined data type".to_owned(), )); } @@ -286,7 +286,7 @@ impl Parser { fn parse_operand(&mut self, operand: &str) -> Result<(), ParseError> { match operand.split_once('=') { - None => return Err(ParseError::UnrecognizedOperand(operand.to_string())), + None => return Err(ParseError::UnrecognizedOperand(operand.to_owned())), Some((k, v)) => match k { "bs" => self.bs = Some(Self::parse_bytes(k, v)?), "cbs" => self.cbs = Some(Self::parse_bytes(k, v)?), @@ -296,15 +296,15 @@ impl Parser { } "count" => self.count = Some(Self::parse_n(v)?), "ibs" => self.ibs = Some(Self::parse_bytes(k, v)?), - "if" => self.infile = Some(v.to_string()), + "if" => self.infile = Some(v.to_owned()), "iflag" => self.parse_input_flags(v)?, "obs" => self.obs = Some(Self::parse_bytes(k, v)?), - "of" => self.outfile = Some(v.to_string()), + "of" => self.outfile = Some(v.to_owned()), "oflag" => self.parse_output_flags(v)?, "seek" | "oseek" => self.seek = Self::parse_n(v)?, "skip" | "iseek" => self.skip = Self::parse_n(v)?, "status" => self.status = Some(Self::parse_status_level(v)?), - _ => return Err(ParseError::UnrecognizedOperand(operand.to_string())), + _ => return Err(ParseError::UnrecognizedOperand(operand.to_owned())), }, } Ok(()) @@ -322,7 +322,7 @@ impl Parser { fn parse_bytes(arg: &str, val: &str) -> Result { parse_bytes_with_opt_multiplier(val)? .try_into() - .map_err(|_| ParseError::BsOutOfRange(arg.to_string())) + .map_err(|_| ParseError::BsOutOfRange(arg.to_owned())) } fn parse_status_level(val: &str) -> Result { @@ -330,7 +330,7 @@ impl Parser { "none" => Ok(StatusLevel::None), "noxfer" => Ok(StatusLevel::Noxfer), "progress" => Ok(StatusLevel::Progress), - _ => Err(ParseError::StatusLevelNotRecognized(val.to_string())), + _ => Err(ParseError::StatusLevelNotRecognized(val.to_owned())), } } @@ -340,7 +340,7 @@ impl Parser { for f in val.split(',') { match f { // Common flags - "cio" => return Err(ParseError::Unimplemented(f.to_string())), + "cio" => return Err(ParseError::Unimplemented(f.to_owned())), "direct" => linux_only!(f, i.direct = true), "directory" => linux_only!(f, i.directory = true), "dsync" => linux_only!(f, i.dsync = true), @@ -350,9 +350,9 @@ impl Parser { "noatime" => linux_only!(f, i.noatime = true), "noctty" => linux_only!(f, i.noctty = true), "nofollow" => linux_only!(f, i.nofollow = true), - "nolinks" => return Err(ParseError::Unimplemented(f.to_string())), - "binary" => return Err(ParseError::Unimplemented(f.to_string())), - "text" => return Err(ParseError::Unimplemented(f.to_string())), + "nolinks" => return Err(ParseError::Unimplemented(f.to_owned())), + "binary" => return Err(ParseError::Unimplemented(f.to_owned())), + "text" => return Err(ParseError::Unimplemented(f.to_owned())), // Input-only flags "fullblock" => i.fullblock = true, @@ -360,7 +360,7 @@ impl Parser { "skip_bytes" => i.skip_bytes = true, // GNU silently ignores oflags given as iflag. "append" | "seek_bytes" => {} - _ => return Err(ParseError::FlagNoMatch(f.to_string())), + _ => return Err(ParseError::FlagNoMatch(f.to_owned())), } } Ok(()) @@ -372,7 +372,7 @@ impl Parser { for f in val.split(',') { match f { // Common flags - "cio" => return Err(ParseError::Unimplemented(val.to_string())), + "cio" => return Err(ParseError::Unimplemented(val.to_owned())), "direct" => linux_only!(f, o.direct = true), "directory" => linux_only!(f, o.directory = true), "dsync" => linux_only!(f, o.dsync = true), @@ -382,16 +382,16 @@ impl Parser { "noatime" => linux_only!(f, o.noatime = true), "noctty" => linux_only!(f, o.noctty = true), "nofollow" => linux_only!(f, o.nofollow = true), - "nolinks" => return Err(ParseError::Unimplemented(f.to_string())), - "binary" => return Err(ParseError::Unimplemented(f.to_string())), - "text" => return Err(ParseError::Unimplemented(f.to_string())), + "nolinks" => return Err(ParseError::Unimplemented(f.to_owned())), + "binary" => return Err(ParseError::Unimplemented(f.to_owned())), + "text" => return Err(ParseError::Unimplemented(f.to_owned())), // Output-only flags "append" => o.append = true, "seek_bytes" => o.seek_bytes = true, // GNU silently ignores iflags given as oflag. "fullblock" | "count_bytes" | "skip_bytes" => {} - _ => return Err(ParseError::FlagNoMatch(f.to_string())), + _ => return Err(ParseError::FlagNoMatch(f.to_owned())), } } Ok(()) @@ -426,7 +426,7 @@ impl Parser { "notrunc" => c.notrunc = true, "fdatasync" => c.fdatasync = true, "fsync" => c.fsync = true, - _ => return Err(ParseError::ConvFlagNoMatch(f.to_string())), + _ => return Err(ParseError::ConvFlagNoMatch(f.to_owned())), } } Ok(()) @@ -450,7 +450,7 @@ fn show_zero_multiplier_warning() { fn parse_bytes_only(s: &str, i: usize) -> Result { s[..i] .parse() - .map_err(|_| ParseError::MultiplierStringParseFailure(s.to_string())) + .map_err(|_| ParseError::MultiplierStringParseFailure(s.to_owned())) } /// Parse a number of bytes from the given string, assuming no `'x'` characters. @@ -490,15 +490,15 @@ fn parse_bytes_no_x(full: &str, s: &str) -> Result { (None, None, None) => match parser.parse_u64(s) { Ok(n) => (n, 1), Err(ParseSizeError::SizeTooBig(_)) => (u64::MAX, 1), - Err(_) => return Err(ParseError::InvalidNumber(full.to_string())), + Err(_) => return Err(ParseError::InvalidNumber(full.to_owned())), }, (Some(i), None, None) => (parse_bytes_only(s, i)?, 1), (None, Some(i), None) => (parse_bytes_only(s, i)?, 2), (None, None, Some(i)) => (parse_bytes_only(s, i)?, 512), - _ => return Err(ParseError::MultiplierStringParseFailure(full.to_string())), + _ => return Err(ParseError::MultiplierStringParseFailure(full.to_owned())), }; num.checked_mul(multiplier) - .ok_or_else(|| ParseError::MultiplierStringOverflow(full.to_string())) + .ok_or_else(|| ParseError::MultiplierStringOverflow(full.to_owned())) } /// Parse byte and multiplier like 512, 5KiB, or 1G. @@ -531,7 +531,7 @@ pub fn parse_bytes_with_opt_multiplier(s: &str) -> Result { let num = parse_bytes_no_x(s, part)?; total = total .checked_mul(num) - .ok_or_else(|| ParseError::InvalidNumber(s.to_string()))?; + .ok_or_else(|| ParseError::InvalidNumber(s.to_owned()))?; } Ok(total) } diff --git a/src/uu/df/src/columns.rs b/src/uu/df/src/columns.rs index 0fcd20865d5..c2d13270e26 100644 --- a/src/uu/df/src/columns.rs +++ b/src/uu/df/src/columns.rs @@ -104,7 +104,7 @@ impl Column { let mut columns = vec![]; for name in names { if seen.contains(&name) { - return Err(ColumnError::MultipleColumns(name.to_string())); + return Err(ColumnError::MultipleColumns(name.to_owned())); } seen.push(name); // Unwrapping here should not panic because the diff --git a/src/uu/df/src/filesystem.rs b/src/uu/df/src/filesystem.rs index 858e86917dc..ad08154a2ee 100644 --- a/src/uu/df/src/filesystem.rs +++ b/src/uu/df/src/filesystem.rs @@ -247,7 +247,7 @@ impl Filesystem { let mount_info = MountInfo { dev_id: String::new(), - dev_name: "-".to_string(), + dev_name: "-".to_owned(), fs_type, mount_dir: mount_dir.into_os_string(), mount_option: String::new(), diff --git a/src/uu/df/src/table.rs b/src/uu/df/src/table.rs index d4cf1ddfd17..be06a3f3db2 100644 --- a/src/uu/df/src/table.rs +++ b/src/uu/df/src/table.rs @@ -337,7 +337,7 @@ impl<'a> RowFormatter<'a> { /// If `None`, return the string `"-"` instead. fn percentage(fraction: Option) -> Cell { let s = match fraction { - None => "-".to_string(), + None => "-".to_owned(), Some(x) => format!("{:.0}%", (100.0 * x).ceil()), }; Cell::from_ascii_string(s) @@ -609,8 +609,8 @@ mod tests { fn default() -> Self { Self { file: Some("/path/to/file".into()), - fs_device: "my_device".to_string(), - fs_type: "my_type".to_string(), + fs_device: "my_device".to_owned(), + fs_type: "my_type".to_owned(), fs_mount: "my_mount".into(), bytes: BytesCell::new(100, &BlockSize::Bytes(1)), @@ -776,7 +776,7 @@ mod tests { ..Default::default() }; let row = Row { - fs_device: "my_device".to_string(), + fs_device: "my_device".to_owned(), fs_mount: "my_mount".into(), bytes: BytesCell::new(100, &BlockSize::Bytes(1)), @@ -802,8 +802,8 @@ mod tests { ..Default::default() }; let row = Row { - fs_device: "my_device".to_string(), - fs_type: "my_type".to_string(), + fs_device: "my_device".to_owned(), + fs_type: "my_type".to_owned(), fs_mount: "my_mount".into(), bytes: BytesCell::new(100, &BlockSize::Bytes(1)), @@ -829,7 +829,7 @@ mod tests { ..Default::default() }; let row = Row { - fs_device: "my_device".to_string(), + fs_device: "my_device".to_owned(), fs_mount: "my_mount".into(), inodes: 10, @@ -872,8 +872,8 @@ mod tests { ..Default::default() }; let row = Row { - fs_device: "my_device".to_string(), - fs_type: "my_type".to_string(), + fs_device: "my_device".to_owned(), + fs_type: "my_type".to_owned(), fs_mount: "my_mount".into(), bytes: BytesCell::new(40000, &BlockSize::default()), @@ -907,8 +907,8 @@ mod tests { ..Default::default() }; let row = Row { - fs_device: "my_device".to_string(), - fs_type: "my_type".to_string(), + fs_device: "my_device".to_owned(), + fs_type: "my_type".to_owned(), fs_mount: "my_mount".into(), bytes: BytesCell::new(4096, &BlockSize::default()), @@ -992,11 +992,11 @@ mod tests { let d = crate::Filesystem { file: None, mount_info: crate::MountInfo { - dev_id: "28".to_string(), - dev_name: "none".to_string(), - fs_type: "9p".to_string(), + dev_id: "28".to_owned(), + dev_name: "none".to_owned(), + fs_type: "9p".to_owned(), mount_dir: "/usr/lib/wsl/drivers".into(), - mount_option: "ro,nosuid,nodev,noatime".to_string(), + mount_option: "ro,nosuid,nodev,noatime".to_owned(), mount_root: "/".into(), remote: false, dummy: false, @@ -1023,11 +1023,11 @@ mod tests { let d1 = crate::Filesystem { file: None, mount_info: crate::MountInfo { - dev_id: "28".to_string(), - dev_name: "none".to_string(), - fs_type: "9p".to_string(), + dev_id: "28".to_owned(), + dev_name: "none".to_owned(), + fs_type: "9p".to_owned(), mount_dir: "/usr/lib/wsl/drivers".into(), - mount_option: "ro,nosuid,nodev,noatime".to_string(), + mount_option: "ro,nosuid,nodev,noatime".to_owned(), mount_root: "/".into(), remote: false, dummy: false, @@ -1094,11 +1094,11 @@ mod tests { let d1 = crate::Filesystem { file: None, mount_info: crate::MountInfo { - dev_id: "28".to_string(), - dev_name: "none".to_string(), - fs_type: "9p".to_string(), + dev_id: "28".to_owned(), + dev_name: "none".to_owned(), + fs_type: "9p".to_owned(), mount_dir: bad_unicode_os_str, - mount_option: "ro,nosuid,nodev,noatime".to_string(), + mount_option: "ro,nosuid,nodev,noatime".to_owned(), mount_root: "/".into(), remote: false, dummy: false, diff --git a/src/uu/dircolors/src/dircolors.rs b/src/uu/dircolors/src/dircolors.rs index 72e18d55d4f..f0a0f575a23 100644 --- a/src/uu/dircolors/src/dircolors.rs +++ b/src/uu/dircolors/src/dircolors.rs @@ -57,15 +57,15 @@ pub fn guess_syntax() -> OutputFmt { fn get_colors_format_strings(fmt: &OutputFmt) -> (String, String) { let prefix = match fmt { - OutputFmt::Shell => "LS_COLORS='".to_string(), - OutputFmt::CShell => "setenv LS_COLORS '".to_string(), + OutputFmt::Shell => "LS_COLORS='".to_owned(), + OutputFmt::CShell => "setenv LS_COLORS '".to_owned(), OutputFmt::Display => String::new(), OutputFmt::Unknown => unreachable!(), }; let suffix = match fmt { - OutputFmt::Shell => "';\nexport LS_COLORS".to_string(), - OutputFmt::CShell => "'".to_string(), + OutputFmt::Shell => "';\nexport LS_COLORS".to_owned(), + OutputFmt::CShell => "'".to_owned(), OutputFmt::Display => String::new(), OutputFmt::Unknown => unreachable!(), }; @@ -436,7 +436,7 @@ fn append_entry( let entry = if key.starts_with('.') { format!("*{key}") } else { - key.to_string() + key.to_owned() }; let disp = if *fmt == OutputFmt::Display { format!("\x1b[{val}m{entry}\t{val}\x1b[0m\n") diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index a1b3596cc4c..d5a1f1a2ffc 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -1084,7 +1084,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let time_format = if time.is_some() { parse_time_style(matches.get_one::("time-style"))? } else { - format::LONG_ISO.to_string() + format::LONG_ISO.to_owned() }; let stat_printer = StatPrinter { @@ -1245,7 +1245,7 @@ fn parse_time_style(s: Option<&String>) -> UResult { }; match s { "locale" => None, - _ => Some(s.to_string()), + _ => Some(s.to_owned()), } } Err(_) => None, @@ -1254,15 +1254,15 @@ fn parse_time_style(s: Option<&String>) -> UResult { }; match s { Some(s) => match s.as_ref() { - "full-iso" => Ok(format::FULL_ISO.to_string()), - "long-iso" => Ok(format::LONG_ISO.to_string()), - "iso" => Ok(format::ISO.to_string()), + "full-iso" => Ok(format::FULL_ISO.to_owned()), + "long-iso" => Ok(format::LONG_ISO.to_owned()), + "iso" => Ok(format::ISO.to_owned()), _ => match s.chars().next().unwrap() { '+' => Ok(s[1..].to_string()), _ => Err(DuError::InvalidTimeStyleArg(s).into()), }, }, - None => Ok(format::LONG_ISO.to_string()), + None => Ok(format::LONG_ISO.to_owned()), } } @@ -1508,7 +1508,7 @@ impl FromStr for Threshold { // Threshold of '-0' excludes everything besides 0 sized entries // GNU's du treats '-0' as an invalid argument if size == 0 { - return Err(ParseSizeError::ParseFailure(s.to_string())); + return Err(ParseSizeError::ParseFailure(s.to_owned())); } Ok(Self::Upper(size)) } else { @@ -1549,7 +1549,7 @@ mod test_du { #[test] fn test_read_block_size() { - let test_data = [Some("1024".to_string()), Some("K".to_string()), None]; + let test_data = [Some("1024".to_owned()), Some("K".to_owned()), None]; for it in &test_data { assert!(matches!(read_block_size(it.as_deref()), Ok(1024))); } diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 685cb44ac98..f4dc5b7961e 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -122,9 +122,9 @@ fn tabstops_parse(s: &str) -> Result<(RemainingMode, Vec), ParseError> { if is_specifier_already_used { let specifier = if remaining_mode == RemainingMode::Slash { - "/".to_string() + "/".to_owned() } else { - "+".to_string() + "+".to_owned() }; return Err(ParseError::SpecifierOnlyAllowedWithLastValue( specifier, @@ -139,17 +139,17 @@ fn tabstops_parse(s: &str) -> Result<(RemainingMode, Vec), ParseError> { } Err(e) => { if *e.kind() == IntErrorKind::PosOverflow { - return Err(ParseError::TabSizeTooLarge(s.to_string())); + return Err(ParseError::TabSizeTooLarge(s.to_owned())); } let s = s.trim_start_matches(char::is_numeric); return if s.starts_with('/') || s.starts_with('+') { Err(ParseError::SpecifierNotAtStartOfNumber( s[0..1].to_string(), - s.to_string(), + s.to_owned(), )) } else { - Err(ParseError::InvalidCharacter(s.to_string())) + Err(ParseError::InvalidCharacter(s.to_owned())) }; } } diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index a5c453c1745..5874ab9f4f8 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -405,7 +405,7 @@ fn find_match(regex: Regex, re_string: String, left_bytes: Vec) -> String { if regex.captures_len() > 0 { String::new() } else { - "0".to_string() + "0".to_owned() } } } else { @@ -446,14 +446,14 @@ fn find_match(regex: Regex, re_string: String, left_bytes: Vec) -> String { .unwrap_or_default() } else { // No capture groups - return 0 for invalid UTF-8 in UTF-8 locale - "0".to_string() + "0".to_owned() } } else { // No match if re_ascii.captures_len() > 0 { String::new() } else { - "0".to_string() + "0".to_owned() } } } else { @@ -461,7 +461,7 @@ fn find_match(regex: Regex, re_string: String, left_bytes: Vec) -> String { if regex.captures_len() > 0 { String::new() } else { - "0".to_string() + "0".to_owned() } } } @@ -496,7 +496,7 @@ fn find_match(regex: Regex, re_string: String, left_bytes: Vec) -> String { if regex.captures_len() > 0 { String::new() } else { - "0".to_string() + "0".to_owned() } } } @@ -1090,11 +1090,11 @@ mod test { fn missing_closing_parenthesis() { assert_eq!( AstNode::parse(&["(", "42"]), - Err(ExprError::ExpectedClosingBraceAfter("42".to_string())) + Err(ExprError::ExpectedClosingBraceAfter("42".to_owned())) ); assert_eq!( AstNode::parse(&["(", "42", "a"]), - Err(ExprError::ExpectedClosingBraceInsteadOf("a".to_string())) + Err(ExprError::ExpectedClosingBraceInsteadOf("a".to_owned())) ); } diff --git a/src/uu/fmt/src/fmt.rs b/src/uu/fmt/src/fmt.rs index c06c5702b41..0dc1779f4ff 100644 --- a/src/uu/fmt/src/fmt.rs +++ b/src/uu/fmt/src/fmt.rs @@ -334,7 +334,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { && first_arg.chars().skip(2).any(|c| !c.is_ascii_digit()); if malformed_number { return Err(FmtError::InvalidWidthMalformed( - first_arg.strip_prefix('-').unwrap().to_string(), + first_arg.strip_prefix('-').unwrap().to_owned(), ) .into()); } diff --git a/src/uu/fold/src/fold.rs b/src/uu/fold/src/fold.rs index 17b58e18b42..57c98983d52 100644 --- a/src/uu/fold/src/fold.rs +++ b/src/uu/fold/src/fold.rs @@ -155,7 +155,7 @@ fn fold( stdin_buf = stdin(); &mut stdin_buf as &mut dyn Read } else { - file_buf = File::open(Path::new(filename)).map_err_context(|| filename.to_string())?; + file_buf = File::open(Path::new(filename)).map_err_context(|| filename.to_owned())?; &mut file_buf as &mut dyn Read }); diff --git a/src/uu/head/src/parse.rs b/src/uu/head/src/parse.rs index daf87c54d87..87c1b9b4c0e 100644 --- a/src/uu/head/src/parse.rs +++ b/src/uu/head/src/parse.rs @@ -140,7 +140,7 @@ mod tests { #[expect(clippy::unnecessary_wraps, reason = "test helper")] fn obsolete_result(src: &[&str]) -> Option, ParseError>> { - Some(Ok(src.iter().map(|&s| s.to_string()).collect())) + Some(Ok(src.iter().map(|&s| s.to_owned()).collect())) } #[test] diff --git a/src/uu/install/src/install.rs b/src/uu/install/src/install.rs index a3cd779312a..b0468db088d 100644 --- a/src/uu/install/src/install.rs +++ b/src/uu/install/src/install.rs @@ -399,7 +399,7 @@ fn behavior(matches: &ArgMatches) -> UResult { let owner = matches .get_one::(OPT_OWNER) .map_or("", |s| s.as_str()) - .to_string(); + .to_owned(); let owner_id = if owner.is_empty() { None @@ -413,7 +413,7 @@ fn behavior(matches: &ArgMatches) -> UResult { let group = matches .get_one::(OPT_GROUP) .map_or("", |s| s.as_str()) - .to_string(); + .to_owned(); let group_id = if group.is_empty() { None @@ -1269,7 +1269,7 @@ fn derive_context_from_parent(parent_context: &str) -> String { } } else { // Fallback if we can't parse the parent context - parent_context.to_string() + parent_context.to_owned() } } diff --git a/src/uu/join/benches/join_bench.rs b/src/uu/join/benches/join_bench.rs index 800bfa96d73..c0473fcb969 100644 --- a/src/uu/join/benches/join_bench.rs +++ b/src/uu/join/benches/join_bench.rs @@ -23,8 +23,8 @@ fn create_join_files(temp_dir: &TempDir, num_lines: usize) -> (String, String) { } ( - file1_path.to_str().unwrap().to_string(), - file2_path.to_str().unwrap().to_string(), + file1_path.to_str().unwrap().to_owned(), + file2_path.to_str().unwrap().to_owned(), ) } @@ -54,8 +54,8 @@ fn create_partial_overlap_files( } ( - file1_path.to_str().unwrap().to_string(), - file2_path.to_str().unwrap().to_string(), + file1_path.to_str().unwrap().to_owned(), + file2_path.to_str().unwrap().to_owned(), ) } @@ -146,8 +146,8 @@ fn create_unicode_join_files(temp_dir: &TempDir, num_lines: usize) -> (String, S } ( - file1_path.to_str().unwrap().to_string(), - file2_path.to_str().unwrap().to_string(), + file1_path.to_str().unwrap().to_owned(), + file2_path.to_str().unwrap().to_owned(), ) } diff --git a/src/uu/ln/src/ln.rs b/src/uu/ln/src/ln.rs index 541586625f9..a0131520368 100644 --- a/src/uu/ln/src/ln.rs +++ b/src/uu/ln/src/ln.rs @@ -273,7 +273,7 @@ fn exec(files: &[PathBuf], settings: &Settings) -> UResult<()> { if files.len() > 2 { return Err(LnError::ExtraOperand( files[2].clone().into(), - uucore::execution_phrase().to_string(), + uucore::execution_phrase().to_owned(), ) .into()); } diff --git a/src/uu/ls/src/colors.rs b/src/uu/ls/src/colors.rs index fa9a8903bb8..8221c4250fa 100644 --- a/src/uu/ls/src/colors.rs +++ b/src/uu/ls/src/colors.rs @@ -842,7 +842,7 @@ mod tests { fn has_indicator_style_detects_raw_codes() { let colors = LsColors::empty(); let mut indicator_codes = HashMap::new(); - indicator_codes.insert(Indicator::Directory, "01;34".to_string()); + indicator_codes.insert(Indicator::Directory, "01;34".to_owned()); let manager = style_manager(&colors, indicator_codes); assert!(manager.has_indicator_style(Indicator::Directory)); } diff --git a/src/uu/ls/src/dired.rs b/src/uu/ls/src/dired.rs index 69122ccd08b..1f554b92939 100644 --- a/src/uu/ls/src/dired.rs +++ b/src/uu/ls/src/dired.rs @@ -192,8 +192,8 @@ mod tests { #[test] fn test_calculate_dired() { - let output_display = "sample_output".to_string(); - let dfn = "sample_file".to_string(); + let output_display = "sample_output".to_owned(); + let dfn = "sample_file".to_owned(); let dired_positions = vec![BytePosition { start: 5, end: 10 }]; let (start, end) = calculate_dired(&dired_positions, output_display.len(), dfn.len()); diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index 489fa301b97..1bc530aec78 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -264,7 +264,7 @@ fn parse_time_style(options: &clap::ArgMatches) -> Result<(String, Option)) -> Result<(String, Option), LsError> { - Ok((recent.to_string(), older.map(String::from))) + Ok((recent.to_owned(), older.map(String::from))) } if let Some(field) = options @@ -300,8 +300,8 @@ fn parse_time_style(options: &clap::ArgMatches) -> Result<(String, Option ok((format::LONG_ISO, None)), // ISO older format needs extra padding. "iso" => Ok(( - "%m-%d %H:%M".to_string(), - Some(format::ISO.to_string() + " "), + "%m-%d %H:%M".to_owned(), + Some(format::ISO.to_owned() + " "), )), "locale" => ok(LOCALE_FORMAT), _ => match field.chars().next().unwrap() { @@ -761,7 +761,7 @@ fn extract_quoting_style( Some(pair) => return pair, None => eprintln!( "{}", - translate!("ls-invalid-quoting-style", "program" => std::env::args().next().unwrap_or_else(|| "ls".to_string()), "style" => style.clone()) + translate!("ls-invalid-quoting-style", "program" => std::env::args().next().unwrap_or_else(|| "ls".to_owned()), "style" => style.clone()) ), } } @@ -3444,7 +3444,7 @@ fn display_item_name( if config.context { if let Some(pad_count) = prefix_context { let security_context = if matches!(config.format, Format::Commas) { - path.security_context(config).to_string() + path.security_context(config).to_owned() } else { pad_left(path.security_context(config), pad_count) }; diff --git a/src/uu/mktemp/src/mktemp.rs b/src/uu/mktemp/src/mktemp.rs index 3efd0690188..8bcb3704dbf 100644 --- a/src/uu/mktemp/src/mktemp.rs +++ b/src/uu/mktemp/src/mktemp.rs @@ -221,7 +221,7 @@ impl Params { // The template argument must end in 'X' if a suffix option is given. if options.suffix.is_some() && !template_str.ends_with('X') { - return Err(MkTempError::MustEndInX(template_str.to_string())); + return Err(MkTempError::MustEndInX(template_str.to_owned())); } // Get the start and end indices of the randomized part of the template. @@ -234,7 +234,7 @@ impl Params { .chars() .take(template_str.len()) .collect::(), - None => template_str.to_string(), + None => template_str.to_owned(), }; return Err(MkTempError::TooFewXs(s)); }; @@ -249,7 +249,7 @@ impl Params { let prefix_path = Path::new(&prefix_from_option).join(prefix_from_template); if options.treat_as_template && prefix_from_template.contains(MAIN_SEPARATOR) { return Err(MkTempError::PrefixContainsDirSeparator( - template_str.to_string(), + template_str.to_owned(), )); } if tmpdir.is_some() && Path::new(prefix_from_template).is_absolute() { @@ -271,7 +271,7 @@ impl Params { }; let prefix = match prefix_path.file_name() { None => String::new(), - Some(f) => f.to_str().unwrap().to_string(), + Some(f) => f.to_str().unwrap().to_owned(), }; (directory, prefix) } diff --git a/src/uu/more/src/more.rs b/src/uu/more/src/more.rs index f31521a6e08..ec2ae060391 100644 --- a/src/uu/more/src/more.rs +++ b/src/uu/more/src/more.rs @@ -538,7 +538,7 @@ impl<'a> Pager<'a> { self.cumulative_line_sizes .push(last_pos + bytes_read as u64); // Remove trailing whitespace - line = line.trim_end().to_string(); + line = line.trim_end().to_owned(); // Store the line (using mem::take to avoid clone) self.lines.push(std::mem::take(&mut line)); } @@ -849,11 +849,11 @@ impl<'a> Pager<'a> { .copied() .unwrap_or_default(); if file_size == 0 { - " (END)".to_string() + " (END)".to_owned() } else { let percentage = (position as f64 / file_size as f64 * 100.0).round() as u16; if percentage >= 100 { - " (END)".to_string() + " (END)".to_owned() } else { format!(" ({percentage}%)") } @@ -953,7 +953,7 @@ mod tests { impl TestPagerBuilder { fn new(content: &str) -> Self { Self { - content: content.to_string(), + content: content.to_owned(), ..Default::default() } } diff --git a/src/uu/mv/benches/mv_bench.rs b/src/uu/mv/benches/mv_bench.rs index 80c5500fb00..08a4173cf19 100644 --- a/src/uu/mv/benches/mv_bench.rs +++ b/src/uu/mv/benches/mv_bench.rs @@ -20,8 +20,8 @@ fn mv_single_file(bencher: Bencher) { let src = temp_dir.path().join(format!("f{i}")); let dst = temp_dir.path().join(format!("moved_{i}")); ( - src.to_str().unwrap().to_string(), - dst.to_str().unwrap().to_string(), + src.to_str().unwrap().to_owned(), + dst.to_str().unwrap().to_owned(), ) }) .collect(); @@ -52,10 +52,10 @@ fn mv_multiple_to_dir(bencher: Bencher) { .join(format!("f{i}")) .to_str() .unwrap() - .to_string() + .to_owned() }) .collect(); - args.push(dest_dir.to_str().unwrap().to_string()); + args.push(dest_dir.to_str().unwrap().to_owned()); (temp_dir, args) }) .bench_values(|(temp_dir, args)| { @@ -78,8 +78,8 @@ fn mv_directory(bencher: Bencher) { let dst_dir = temp_dir.path().join("dest_tree"); ( temp_dir, - src_dir.to_str().unwrap().to_string(), - dst_dir.to_str().unwrap().to_string(), + src_dir.to_str().unwrap().to_owned(), + dst_dir.to_str().unwrap().to_owned(), ) }) .bench_values(|(temp_dir, src, dst)| { @@ -100,8 +100,8 @@ fn mv_force_overwrite(bencher: Bencher) { let src = temp_dir.path().join(format!("f{i}")); let dst = temp_dir.path().join(format!("f{}", i + 1000)); ( - src.to_str().unwrap().to_string(), - dst.to_str().unwrap().to_string(), + src.to_str().unwrap().to_owned(), + dst.to_str().unwrap().to_owned(), ) }) .collect(); diff --git a/src/uu/nohup/src/nohup.rs b/src/uu/nohup/src/nohup.rs index 6280d44e1e3..65cad0cabe4 100644 --- a/src/uu/nohup/src/nohup.rs +++ b/src/uu/nohup/src/nohup.rs @@ -167,7 +167,7 @@ fn find_stdout() -> UResult { Err(e2) => Err(NohupError::OpenFailed2( internal_failure_code, e1, - homeout_str.to_string(), + homeout_str.to_owned(), e2, ) .into()), diff --git a/src/uu/numfmt/benches/numfmt_bench.rs b/src/uu/numfmt/benches/numfmt_bench.rs index aed3fb03583..59b56ef06a3 100644 --- a/src/uu/numfmt/benches/numfmt_bench.rs +++ b/src/uu/numfmt/benches/numfmt_bench.rs @@ -13,7 +13,7 @@ fn numfmt_to_si(bencher: Bencher, count: usize) { bencher .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); - let mut args: Vec = vec!["--to=si".to_string()]; + let mut args: Vec = vec!["--to=si".to_owned()]; args.extend(numbers); args }) @@ -29,7 +29,7 @@ fn numfmt_to_si_precision(bencher: Bencher, count: usize) { bencher .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); - let mut args: Vec = vec!["--to=si".to_string(), "--format=%.6f".to_string()]; + let mut args: Vec = vec!["--to=si".to_owned(), "--format=%.6f".to_owned()]; args.extend(numbers); args }) @@ -45,7 +45,7 @@ fn numfmt_to_iec(bencher: Bencher, count: usize) { bencher .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); - let mut args: Vec = vec!["--to=iec".to_string()]; + let mut args: Vec = vec!["--to=iec".to_owned()]; args.extend(numbers); args }) @@ -62,7 +62,7 @@ fn numfmt_from_si(bencher: Bencher, count: usize) { .with_inputs(|| { // Generate SI formatted data (e.g., "1K", "2K", etc.) let numbers: Vec = (1..=count).map(|n| format!("{n}K")).collect(); - let mut args: Vec = vec!["--from=si".to_string()]; + let mut args: Vec = vec!["--from=si".to_owned()]; args.extend(numbers); args }) @@ -83,7 +83,7 @@ fn numfmt_large_numbers_si(bencher: Bencher, count: usize) { .map(|n| ((n % 9) + 1) * 1_000_000) .map(|n| n.to_string()) .collect(); - let mut args: Vec = vec!["--to=si".to_string()]; + let mut args: Vec = vec!["--to=si".to_owned()]; args.extend(numbers); args }) @@ -99,7 +99,7 @@ fn numfmt_padding(bencher: Bencher, (count, padding): (usize, usize)) { bencher .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); - let mut args: Vec = vec!["--to=si".to_string(), format!("--padding={padding}")]; + let mut args: Vec = vec!["--to=si".to_owned(), format!("--padding={padding}")]; args.extend(numbers); args }) @@ -116,7 +116,7 @@ fn numfmt_round_modes(bencher: Bencher, (round_mode, count): (&str, usize)) { .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); let mut args: Vec = - vec!["--to=si".to_string(), format!("--round={round_mode}")]; + vec!["--to=si".to_owned(), format!("--round={round_mode}")]; args.extend(numbers); args }) diff --git a/src/uu/od/src/parse_formats.rs b/src/uu/od/src/parse_formats.rs index 1103b77cac3..d7794b5f82f 100644 --- a/src/uu/od/src/parse_formats.rs +++ b/src/uu/od/src/parse_formats.rs @@ -374,7 +374,7 @@ fn parse_type_string(params: &str) -> Result, Strin #[cfg(test)] pub fn parse_format_flags_str(args_str: &[&'static str]) -> Result, String> { - let args: Vec = args_str.iter().map(|s| (*s).to_string()).collect(); + let args: Vec = args_str.iter().map(|s| (*s).to_owned()).collect(); parse_format_flags(&args).map(|v| { // tests using this function assume add_ascii_dump is not set v.into_iter() @@ -472,7 +472,7 @@ fn test_long_format_a() { #[test] fn test_long_format_cz() { assert_eq!( - parse_format_flags(&["od".to_string(), "--format=cz".to_string()]).unwrap(), + parse_format_flags(&["od".to_owned(), "--format=cz".to_owned()]).unwrap(), vec![ParsedFormatterItemInfo::new(FORMAT_ITEM_C, true)] ); } @@ -561,20 +561,20 @@ fn test_format_next_arg_invalid() { fn test_mixed_formats() { assert_eq!( parse_format_flags(&[ - "od".to_string(), - "--skip-bytes=2".to_string(), - "-vItu1z".to_string(), - "-N".to_string(), - "1000".to_string(), - "-xt".to_string(), - "acdx1".to_string(), - "--format=u2c".to_string(), - "--format".to_string(), - "f".to_string(), - "-xAx".to_string(), - "--".to_string(), - "-h".to_string(), - "--format=f8".to_string(), + "od".to_owned(), + "--skip-bytes=2".to_owned(), + "-vItu1z".to_owned(), + "-N".to_owned(), + "1000".to_owned(), + "-xt".to_owned(), + "acdx1".to_owned(), + "--format=u2c".to_owned(), + "--format".to_owned(), + "f".to_owned(), + "-xAx".to_owned(), + "--".to_owned(), + "-h".to_owned(), + "--format=f8".to_owned(), ]) .unwrap(), vec![ diff --git a/src/uu/od/src/parse_inputs.rs b/src/uu/od/src/parse_inputs.rs index b6f763b2e52..e3021cacf65 100644 --- a/src/uu/od/src/parse_inputs.rs +++ b/src/uu/od/src/parse_inputs.rs @@ -73,11 +73,11 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result { // if there is just 1 input (stdin), an offset must start with '+' if input_strings.len() == 1 && input_strings[0].starts_with('+') { - return Ok(CommandLineInputs::FileAndOffset(("-".to_string(), n, None))); + return Ok(CommandLineInputs::FileAndOffset(("-".to_owned(), n, None))); } if input_strings.len() == 2 { return Ok(CommandLineInputs::FileAndOffset(( - input_strings[0].to_string(), + input_strings[0].to_owned(), n, None, ))); @@ -88,7 +88,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result Result Result Result { match input_strings.len() { - 0 => Ok(CommandLineInputs::FileNames(vec!["-".to_string()])), + 0 => Ok(CommandLineInputs::FileNames(vec!["-".to_owned()])), 1 => { let offset0 = parse_offset_operand(input_strings[0]); Ok(match offset0 { - Ok(n) => CommandLineInputs::FileAndOffset(("-".to_string(), n, None)), + Ok(n) => CommandLineInputs::FileAndOffset(("-".to_owned(), n, None)), _ => CommandLineInputs::FileNames( - input_strings.iter().map(|&s| s.to_string()).collect(), + input_strings.iter().map(|&s| s.to_owned()).collect(), ), }) } @@ -127,12 +127,12 @@ pub fn parse_inputs_traditional(input_strings: &[&str]) -> Result Ok(CommandLineInputs::FileAndOffset(( - "-".to_string(), + "-".to_owned(), n, Some(m), ))), (_, Ok(m)) => Ok(CommandLineInputs::FileAndOffset(( - input_strings[0].to_string(), + input_strings[0].to_owned(), m, None, ))), @@ -144,7 +144,7 @@ pub fn parse_inputs_traditional(input_strings: &[&str]) -> Result Ok(CommandLineInputs::FileAndOffset(( - input_strings[0].to_string(), + input_strings[0].to_owned(), n, Some(m), ))), @@ -212,7 +212,7 @@ pub fn parse_offset_operand(s: &str) -> Result { let err = std::io::Error::from_raw_os_error(libc::ERANGE); let msg = err.to_string(); // Strip "(os error N)" if present to match Perl's $! - let msg = msg.split(" (os error").next().unwrap_or(&msg).to_string(); + let msg = msg.split(" (os error").next().unwrap_or(&msg).to_owned(); Err(msg) } } @@ -224,7 +224,7 @@ pub fn parse_offset_operand(s: &str) -> Result { IntErrorKind::PosOverflow => { let err = std::io::Error::from_raw_os_error(libc::ERANGE); let msg = err.to_string(); - let msg = msg.split(" (os error").next().unwrap_or(&msg).to_string(); + let msg = msg.split(" (os error").next().unwrap_or(&msg).to_owned(); Err(msg) } _ => Err(translate!("od-error-parse-failed")), @@ -241,30 +241,30 @@ mod tests { #[test] fn test_parse_inputs_normal() { assert_eq!( - CommandLineInputs::FileNames(vec!["-".to_string()]), + CommandLineInputs::FileNames(vec!["-".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["-".to_string()]), + CommandLineInputs::FileNames(vec!["-".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "-"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["file1".to_string()]), + CommandLineInputs::FileNames(vec!["file1".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "file1"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["file1".to_string(), "file2".to_string()]), + CommandLineInputs::FileNames(vec!["file1".to_owned(), "file2".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "file1", "file2"])).unwrap() ); assert_eq!( CommandLineInputs::FileNames(vec![ - "-".to_string(), - "file1".to_string(), - "file2".to_string(), + "-".to_owned(), + "file1".to_owned(), + "file2".to_owned(), ]), parse_inputs(&uu_app().get_matches_from(vec!["od", "-", "file1", "file2"])).unwrap() ); @@ -275,58 +275,58 @@ mod tests { fn test_parse_inputs_with_offset() { // offset is found without filename, so stdin will be used. assert_eq!( - CommandLineInputs::FileAndOffset(("-".to_string(), 8, None)), + CommandLineInputs::FileAndOffset(("-".to_owned(), 8, None)), parse_inputs(&uu_app().get_matches_from(vec!["od", "+10"])).unwrap() ); // offset must start with "+" if no input is specified. assert_eq!( - CommandLineInputs::FileNames(vec!["10".to_string()]), + CommandLineInputs::FileNames(vec!["10".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "10"])).unwrap() ); // offset is not valid, so it is considered a filename. assert_eq!( - CommandLineInputs::FileNames(vec!["+10a".to_string()]), + CommandLineInputs::FileNames(vec!["+10a".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "+10a"])).unwrap() ); // if -j is included in the command line, there cannot be an offset. assert_eq!( - CommandLineInputs::FileNames(vec!["+10".to_string()]), + CommandLineInputs::FileNames(vec!["+10".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "-j10", "+10"])).unwrap() ); // if -v is included in the command line, there cannot be an offset. assert_eq!( - CommandLineInputs::FileNames(vec!["+10".to_string()]), + CommandLineInputs::FileNames(vec!["+10".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "-o", "-v", "+10"])).unwrap() ); assert_eq!( - CommandLineInputs::FileAndOffset(("file1".to_string(), 8, None)), + CommandLineInputs::FileAndOffset(("file1".to_owned(), 8, None)), parse_inputs(&uu_app().get_matches_from(vec!["od", "file1", "+10"])).unwrap() ); // offset does not need to start with "+" if a filename is included. assert_eq!( - CommandLineInputs::FileAndOffset(("file1".to_string(), 8, None)), + CommandLineInputs::FileAndOffset(("file1".to_owned(), 8, None)), parse_inputs(&uu_app().get_matches_from(vec!["od", "file1", "10"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["file1".to_string(), "+10a".to_string()]), + CommandLineInputs::FileNames(vec!["file1".to_owned(), "+10a".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "file1", "+10a"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["file1".to_string(), "+10".to_string()]), + CommandLineInputs::FileNames(vec!["file1".to_owned(), "+10".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "-j10", "file1", "+10"])).unwrap() ); // offset must be last on the command line assert_eq!( - CommandLineInputs::FileNames(vec!["+10".to_string(), "file1".to_string()]), + CommandLineInputs::FileNames(vec!["+10".to_owned(), "file1".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "+10", "file1"])).unwrap() ); } @@ -335,30 +335,30 @@ mod tests { fn test_parse_inputs_traditional() { // it should not return FileAndOffset to signal no offset was entered on the command line. assert_eq!( - CommandLineInputs::FileNames(vec!["-".to_string()]), + CommandLineInputs::FileNames(vec!["-".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "--traditional"])).unwrap() ); assert_eq!( - CommandLineInputs::FileNames(vec!["file1".to_string()]), + CommandLineInputs::FileNames(vec!["file1".to_owned()]), parse_inputs(&uu_app().get_matches_from(vec!["od", "--traditional", "file1"])).unwrap() ); // offset does not need to start with a + assert_eq!( - CommandLineInputs::FileAndOffset(("-".to_string(), 8, None)), + CommandLineInputs::FileAndOffset(("-".to_owned(), 8, None)), parse_inputs(&uu_app().get_matches_from(vec!["od", "--traditional", "10"])).unwrap() ); // valid offset and valid label assert_eq!( - CommandLineInputs::FileAndOffset(("-".to_string(), 8, Some(8))), + CommandLineInputs::FileAndOffset(("-".to_owned(), 8, Some(8))), parse_inputs(&uu_app().get_matches_from(vec!["od", "--traditional", "10", "10"])) .unwrap() ); assert_eq!( - CommandLineInputs::FileAndOffset(("file1".to_string(), 8, None)), + CommandLineInputs::FileAndOffset(("file1".to_owned(), 8, None)), parse_inputs(&uu_app().get_matches_from(vec!["od", "--traditional", "file1", "10"])) .unwrap() ); @@ -368,7 +368,7 @@ mod tests { .unwrap_err(); assert_eq!( - CommandLineInputs::FileAndOffset(("file1".to_string(), 8, Some(8))), + CommandLineInputs::FileAndOffset(("file1".to_owned(), 8, Some(8))), parse_inputs(&uu_app().get_matches_from(vec![ "od", "--traditional", diff --git a/src/uu/od/src/parse_nrofbytes.rs b/src/uu/od/src/parse_nrofbytes.rs index 241e1c6e7ca..d2096916cc6 100644 --- a/src/uu/od/src/parse_nrofbytes.rs +++ b/src/uu/od/src/parse_nrofbytes.rs @@ -63,7 +63,7 @@ pub fn parse_number_of_bytes(s: &str) -> Result { Some('P') => 1000 * 1000 * 1000 * 1000 * 1000, #[cfg(target_pointer_width = "64")] Some('E') => 1000 * 1000 * 1000 * 1000 * 1000 * 1000, - _ => return Err(ParseSizeError::ParseFailure(s.to_string())), + _ => return Err(ParseSizeError::ParseFailure(s.to_owned())), } } _ => {} @@ -75,7 +75,7 @@ pub fn parse_number_of_bytes(s: &str) -> Result { }; factor .checked_mul(multiply) - .ok_or_else(|| ParseSizeError::SizeTooBig(s.to_string())) + .ok_or_else(|| ParseSizeError::SizeTooBig(s.to_owned())) } #[test] diff --git a/src/uu/od/src/prn_float.rs b/src/uu/od/src/prn_float.rs index c93b02d25cb..a12afe0fa0b 100644 --- a/src/uu/od/src/prn_float.rs +++ b/src/uu/od/src/prn_float.rs @@ -43,7 +43,7 @@ pub static FORMAT_ITEM_BF16: FormatterItemInfo = FormatterItemInfo { /// - Leave the exponent part (e/E...) untouched. fn trim_float_repr(raw: &str) -> String { // Drop padding added by `format!` width specification - let mut s = raw.trim_start().to_string(); + let mut s = raw.trim_start().to_owned(); // Keep NaN/Inf representations as-is let lower = s.to_ascii_lowercase(); diff --git a/src/uu/pathchk/src/pathchk.rs b/src/uu/pathchk/src/pathchk.rs index d0a35c33160..2e42f7429f7 100644 --- a/src/uu/pathchk/src/pathchk.rs +++ b/src/uu/pathchk/src/pathchk.rs @@ -68,7 +68,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let path_str = p.to_string_lossy(); let mut path = Vec::new(); for path_segment in path_str.split('/') { - path.push(path_segment.to_string()); + path.push(path_segment.to_owned()); } res &= check_path(&mode, &path); } diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 25a1e2e3e96..5990a4c98cb 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -443,8 +443,7 @@ fn get_date_format(matches: &ArgMatches) -> String { format::LONG_ISO } } - } - .to_string() + }.to_owned() } #[allow(clippy::cognitive_complexity)] @@ -484,8 +483,7 @@ fn build_options( paths[0] }, |s| s.as_str(), - ) - .to_string(); + ).to_owned(); let default_first_number = NumberingMode::default().first_number; let first_number = @@ -528,10 +526,10 @@ fn build_options( let content_line_separator = if double_space { "\n".repeat(2) } else { - "\n".to_string() + "\n".to_owned() }; - let line_separator = "\n".to_string(); + let line_separator = "\n".to_owned(); let last_modified_time = { let time = if is_merge_mode || paths[0].eq(FILE_STDIN) { @@ -560,7 +558,7 @@ fn build_options( let res = 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() + x[0].to_owned() .parse::() .map_err(|_e| PrError::EncounteredErrors { msg: format!("invalid {} argument {}", "+", unparsed_num.quote()), @@ -577,7 +575,7 @@ fn build_options( .filter(|i| i.contains(':')) .map(|unparsed_num| { let x: Vec<_> = unparsed_num.split(':').collect(); - x[1].to_string() + x[1].to_owned() .parse::() .map_err(|_e| PrError::EncounteredErrors { msg: format!("invalid {} argument {}", "+", unparsed_num.quote()), @@ -599,7 +597,7 @@ fn build_options( .get_one::(options::PAGES) .map(|i| { let x: Vec<_> = i.split(':').collect(); - x[0].to_string() + x[0].to_owned() }) .map(invalid_pages_map); let start_page = match res { @@ -612,7 +610,7 @@ fn build_options( .filter(|i| i.contains(':')) .map(|i| { let x: Vec<_> = i.split(':').collect(); - x[1].to_string() + x[1].to_owned() }) .map(invalid_pages_map); let end_page = match res { @@ -653,7 +651,7 @@ fn build_options( let bytes = vec![FF]; String::from_utf8(bytes).unwrap() } else { - "\n".to_string() + "\n".to_owned() }; let across_mode = matches.get_flag(options::ACROSS); diff --git a/src/uu/rm/benches/rm_bench.rs b/src/uu/rm/benches/rm_bench.rs index 1e37bb130ff..3db347e38a9 100644 --- a/src/uu/rm/benches/rm_bench.rs +++ b/src/uu/rm/benches/rm_bench.rs @@ -21,8 +21,7 @@ fn rm_single_file(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap() - .to_string() + .unwrap().to_owned() }) .collect(); (temp_dir, paths) @@ -48,8 +47,7 @@ fn rm_multiple_files(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap() - .to_string() + .unwrap().to_owned() }) .collect(); (temp_dir, paths) @@ -71,7 +69,7 @@ fn rm_recursive_tree(bencher: Bencher) { std::fs::create_dir(&test_dir).unwrap(); // Increase depth and width for longer benchmark fs_tree::create_balanced_tree(&test_dir, 5, 5, 10); - (temp_dir, test_dir.to_str().unwrap().to_string()) + (temp_dir, test_dir.to_str().unwrap().to_owned()) }) .bench_values(|(temp_dir, path)| { black_box(run_util_function(uumain, &["-r", &path])); @@ -92,8 +90,7 @@ fn rm_force_files(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap() - .to_string() + .unwrap().to_owned() }) .collect(); (temp_dir, paths) diff --git a/src/uu/sort/benches/sort_locale_c_bench.rs b/src/uu/sort/benches/sort_locale_c_bench.rs index 378a2abb9ac..cfffac3ef3d 100644 --- a/src/uu/sort/benches/sort_locale_c_bench.rs +++ b/src/uu/sort/benches/sort_locale_c_bench.rs @@ -19,7 +19,7 @@ fn sort_ascii_c_locale(bencher: Bencher) { let data = text_data::generate_ascii_data_simple(100_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); bencher.bench(|| { black_box(run_util_function( @@ -35,7 +35,7 @@ fn sort_mixed_c_locale(bencher: Bencher) { let data = text_data::generate_mixed_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); bencher.bench(|| { black_box(run_util_function( @@ -51,7 +51,7 @@ fn sort_german_c_locale(bencher: Bencher) { let data = text_data::generate_german_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); bencher.bench(|| { black_box(run_util_function( diff --git a/src/uu/sort/benches/sort_locale_de_bench.rs b/src/uu/sort/benches/sort_locale_de_bench.rs index 5c760a694e8..69bdf9270aa 100644 --- a/src/uu/sort/benches/sort_locale_de_bench.rs +++ b/src/uu/sort/benches/sort_locale_de_bench.rs @@ -19,7 +19,7 @@ fn sort_german_de_locale(bencher: Bencher) { let data = text_data::generate_german_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); bencher.bench(|| { black_box(run_util_function( diff --git a/src/uu/sort/benches/sort_locale_utf8_bench.rs b/src/uu/sort/benches/sort_locale_utf8_bench.rs index 6f61dc322d0..74da77082ac 100644 --- a/src/uu/sort/benches/sort_locale_utf8_bench.rs +++ b/src/uu/sort/benches/sort_locale_utf8_bench.rs @@ -19,7 +19,7 @@ fn sort_ascii_utf8_locale(bencher: Bencher) { let data = text_data::generate_ascii_data_simple(100_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); let args = ["-o", &output_path, file_path.to_str().unwrap()]; black_box(run_util_function(uumain, &args)); @@ -34,7 +34,7 @@ fn sort_mixed_utf8_locale(bencher: Bencher) { let data = text_data::generate_mixed_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); let args = ["-o", &output_path, file_path.to_str().unwrap()]; black_box(run_util_function(uumain, &args)); @@ -53,7 +53,7 @@ fn sort_numeric_utf8_locale(bencher: Bencher) { } let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); let args = ["-n", "-o", &output_path, file_path.to_str().unwrap()]; black_box(run_util_function(uumain, &args)); @@ -68,7 +68,7 @@ fn sort_reverse_utf8_locale(bencher: Bencher) { let data = text_data::generate_mixed_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); let args = ["-r", "-o", &output_path, file_path.to_str().unwrap()]; black_box(run_util_function(uumain, &args)); @@ -83,7 +83,7 @@ fn sort_unique_utf8_locale(bencher: Bencher) { let data = text_data::generate_mixed_locale_data(50_000); let file_path = setup_test_file(&data); let output_file = NamedTempFile::new().unwrap(); - let output_path = output_file.path().to_str().unwrap().to_string(); + let output_path = output_file.path().to_str().unwrap().to_owned(); let args = ["-u", "-o", &output_path, file_path.to_str().unwrap()]; black_box(run_util_function(uumain, &args)); diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index ceaf5125612..d93dbb9a790 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -1559,7 +1559,7 @@ fn parse_legacy_part(spec: &str) -> Option { Some(LegacyKeyPart { field, char_pos, - opts: rest.to_string(), + opts: rest.to_owned(), }) } @@ -2096,7 +2096,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { // "0" is default - threads = num of cores settings.threads = matches .get_one::(options::PARALLEL) - .map_or_else(|| "0".to_string(), String::from); + .map_or_else(|| "0".to_owned(), String::from); let num_threads = match settings.threads.parse::() { Ok(0) | Err(_) => std::thread::available_parallelism().map_or(1, NonZero::get), Ok(n) => n, @@ -3089,7 +3089,7 @@ mod tests { #[test] fn test_get_hash() { - let a = "Ted".to_string(); + let a = "Ted".to_owned(); assert_eq!(2_646_829_031_758_483_623, get_hash(&a)); } diff --git a/src/uu/split/benches/split_bench.rs b/src/uu/split/benches/split_bench.rs index d09d658b01d..ace3850431d 100644 --- a/src/uu/split/benches/split_bench.rs +++ b/src/uu/split/benches/split_bench.rs @@ -18,7 +18,7 @@ fn split_lines(bencher: Bencher) { .with_inputs(|| { let output_dir = TempDir::new().unwrap(); let prefix = output_dir.path().join("x"); - (output_dir, prefix.to_str().unwrap().to_string()) + (output_dir, prefix.to_str().unwrap().to_owned()) }) .bench_values(|(output_dir, prefix)| { black_box(run_util_function( @@ -39,7 +39,7 @@ fn split_bytes(bencher: Bencher) { .with_inputs(|| { let output_dir = TempDir::new().unwrap(); let prefix = output_dir.path().join("x"); - (output_dir, prefix.to_str().unwrap().to_string()) + (output_dir, prefix.to_str().unwrap().to_owned()) }) .bench_values(|(output_dir, prefix)| { black_box(run_util_function( @@ -60,7 +60,7 @@ fn split_number_chunks(bencher: Bencher) { .with_inputs(|| { let output_dir = TempDir::new().unwrap(); let prefix = output_dir.path().join("x"); - (output_dir, prefix.to_str().unwrap().to_string()) + (output_dir, prefix.to_str().unwrap().to_owned()) }) .bench_values(|(output_dir, prefix)| { black_box(run_util_function( @@ -81,7 +81,7 @@ fn split_numeric_suffix(bencher: Bencher) { .with_inputs(|| { let output_dir = TempDir::new().unwrap(); let prefix = output_dir.path().join("x"); - (output_dir, prefix.to_str().unwrap().to_string()) + (output_dir, prefix.to_str().unwrap().to_owned()) }) .bench_values(|(output_dir, prefix)| { black_box(run_util_function( diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 6e1a8227900..f714d852a4e 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -486,7 +486,7 @@ impl Settings { match first.as_str() { "\\0" => b'\0', s if s.len() == 1 => s.as_bytes()[0], - s => return Err(SettingsError::MultiCharacterSeparator(s.to_string())), + s => return Err(SettingsError::MultiCharacterSeparator(s.to_owned())), } } None => b'\n', diff --git a/src/uu/split/src/strategy.rs b/src/uu/split/src/strategy.rs index 6d567637d07..efe09098aa8 100644 --- a/src/uu/split/src/strategy.rs +++ b/src/uu/split/src/strategy.rs @@ -122,56 +122,56 @@ impl NumberType { match (parts.next(), parts.next(), parts.next(), parts.next()) { (Some(n_str), None, None, None) => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; if num_chunks > 0 { Ok(Self::Bytes(num_chunks)) } else { - Err(NumberTypeError::NumberOfChunks(s.to_string())) + Err(NumberTypeError::NumberOfChunks(s.to_owned())) } } (Some(k_str), Some(n_str), None, None) if !k_str.starts_with('l') && !k_str.starts_with('r') => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; let chunk_number = parse_size_u64(k_str) - .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?; + .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_owned()))?; if is_invalid_chunk(chunk_number, num_chunks) { - return Err(NumberTypeError::ChunkNumber(k_str.to_string())); + return Err(NumberTypeError::ChunkNumber(k_str.to_owned())); } Ok(Self::KthBytes(chunk_number, num_chunks)) } (Some("l"), Some(n_str), None, None) => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; Ok(Self::Lines(num_chunks)) } (Some("l"), Some(k_str), Some(n_str), None) => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; let chunk_number = parse_size_u64(k_str) - .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?; + .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_owned()))?; if is_invalid_chunk(chunk_number, num_chunks) { - return Err(NumberTypeError::ChunkNumber(k_str.to_string())); + return Err(NumberTypeError::ChunkNumber(k_str.to_owned())); } Ok(Self::KthLines(chunk_number, num_chunks)) } (Some("r"), Some(n_str), None, None) => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; Ok(Self::RoundRobin(num_chunks)) } (Some("r"), Some(k_str), Some(n_str), None) => { let num_chunks = parse_size_u64(n_str) - .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_string()))?; + .map_err(|_| NumberTypeError::NumberOfChunks(n_str.to_owned()))?; let chunk_number = parse_size_u64(k_str) - .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_string()))?; + .map_err(|_| NumberTypeError::ChunkNumber(k_str.to_owned()))?; if is_invalid_chunk(chunk_number, num_chunks) { - return Err(NumberTypeError::ChunkNumber(k_str.to_string())); + return Err(NumberTypeError::ChunkNumber(k_str.to_owned())); } Ok(Self::KthRoundRobin(chunk_number, num_chunks)) } - _ => Err(NumberTypeError::NumberOfChunks(s.to_string())), + _ => Err(NumberTypeError::NumberOfChunks(s.to_owned())), } } } @@ -245,7 +245,7 @@ impl Strategy { ) { (Some(v), false, false, false, false) => { let v = parse_size_u64_max(v).map_err(|_| { - StrategyError::Lines(ParseSizeError::ParseFailure(v.to_string())) + StrategyError::Lines(ParseSizeError::ParseFailure(v.to_owned())) })?; if v > 0 { Ok(Self::Lines(v)) @@ -306,31 +306,31 @@ mod tests { fn test_number_type_from_error() { assert_eq!( NumberType::from("xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("l/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("l/123/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("l/abc/456").unwrap_err(), - NumberTypeError::ChunkNumber("abc".to_string()) + NumberTypeError::ChunkNumber("abc".to_owned()) ); assert_eq!( NumberType::from("l/456/123").unwrap_err(), - NumberTypeError::ChunkNumber("456".to_string()) + NumberTypeError::ChunkNumber("456".to_owned()) ); assert_eq!( NumberType::from("r/456/123").unwrap_err(), - NumberTypeError::ChunkNumber("456".to_string()) + NumberTypeError::ChunkNumber("456".to_owned()) ); assert_eq!( NumberType::from("456/123").unwrap_err(), - NumberTypeError::ChunkNumber("456".to_string()) + NumberTypeError::ChunkNumber("456".to_owned()) ); // In GNU split, the number of chunks get precedence: // @@ -339,19 +339,19 @@ mod tests { // assert_eq!( NumberType::from("l/abc/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("r/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("r/123/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); assert_eq!( NumberType::from("r/abc/456").unwrap_err(), - NumberTypeError::ChunkNumber("abc".to_string()) + NumberTypeError::ChunkNumber("abc".to_owned()) ); // In GNU split, the number of chunks get precedence: // @@ -360,7 +360,7 @@ mod tests { // assert_eq!( NumberType::from("r/abc/xyz").unwrap_err(), - NumberTypeError::NumberOfChunks("xyz".to_string()) + NumberTypeError::NumberOfChunks("xyz".to_owned()) ); } diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index 8e044ed77ec..6d85cf5cd0a 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -190,7 +190,7 @@ impl std::str::FromStr for QuotingStyle { "shell-escape-always" => Ok(Self::ShellEscapeAlways), // The others aren't exposed to the user _ => Err(StatError::InvalidQuotingStyle { - style: s.to_string(), + style: s.to_owned(), }), } } @@ -445,7 +445,7 @@ fn quote_file_name(file_name: &str, quoting_style: &QuotingStyle) -> String { let quote = if file_name.contains('\'') { '"' } else { '\'' }; format!("{quote}{file_name}{quote}") } - QuotingStyle::Quote => file_name.to_string(), + QuotingStyle::Quote => file_name.to_owned(), } } @@ -508,7 +508,7 @@ fn process_token_filesystem(t: &Token, meta: &StatFs, display_name: &str) { // maximum length of filenames 'l' => OutputType::Unsigned(meta.namelen()), // file name - 'n' => OutputType::Str(display_name.to_string()), + 'n' => OutputType::Str(display_name.to_owned()), // block size (for faster transfers) 's' => OutputType::Unsigned(meta.io_size()), // fundamental block size (for block counts) @@ -1099,7 +1099,7 @@ impl Stater { None => OutputType::Str(String::new()), }, // file name - 'n' => OutputType::Str(display_name.to_string()), + 'n' => OutputType::Str(display_name.to_owned()), // quoted file name with dereference if symbolic link 'N' => { let file_name = @@ -1401,7 +1401,7 @@ fn pretty_time(meta: &Metadata, md_time_field: MetadataTimeField) -> String { return String::from_utf8(tmp).unwrap(); } } - "-".to_string() + "-".to_owned() } #[cfg(test)] diff --git a/src/uu/stdbuf/build.rs b/src/uu/stdbuf/build.rs index d844f37907a..c2a833cb3bf 100644 --- a/src/uu/stdbuf/build.rs +++ b/src/uu/stdbuf/build.rs @@ -56,7 +56,7 @@ fn main() { } let out_dir = env::var("OUT_DIR").expect("OUT_DIR not set"); - let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_string()); + let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_owned()); // Check if we're building from the repository (where src/libstdbuf exists) // or from crates.io (where it doesn't) @@ -79,7 +79,7 @@ fn main() { fs::create_dir_all(&build_dir).expect("Failed to create build directory"); // Get the cargo executable - let cargo = env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + let cargo = env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned()); // This manual cargo call ensures that libstdbuf is built before stdbuf.rs is compiled, which is necessary // for include_bytes!(..."/libstdbuf.so") to work. @@ -92,7 +92,7 @@ fn main() { .args(["build", "--target-dir", build_dir.to_str().unwrap()]); // Get the current profile - let profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_string()); + let profile = env::var("PROFILE").unwrap_or_else(|_| "debug".to_owned()); // Pass the release flag if we're in release mode if profile == "release" || profile == "bench" { diff --git a/src/uu/stdbuf/src/libstdbuf/build.rs b/src/uu/stdbuf/src/libstdbuf/build.rs index 7584bf31f8e..c756fd0df49 100644 --- a/src/uu/stdbuf/src/libstdbuf/build.rs +++ b/src/uu/stdbuf/src/libstdbuf/build.rs @@ -10,7 +10,7 @@ fn main() { // Make sure we're building position-independent code for use with LD_PRELOAD println!("cargo:rustc-link-arg=-fPIC"); - let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_string()); + let target = env::var("TARGET").unwrap_or_else(|_| "unknown".to_owned()); // Ensure the library doesn't have any undefined symbols (-z flag not supported on macOS and Cygwin) if !target.contains("apple-darwin") && !target.contains("cygwin") { println!("cargo:rustc-link-arg=-z"); diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index bffe1f7b145..f96465e1c1f 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -137,7 +137,7 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result UResult<()> { let mut command_values = matches .get_many::(options::COMMAND) - .ok_or_else(|| UUsageError::new(125, "no command specified".to_string()))?; + .ok_or_else(|| UUsageError::new(125, "no command specified".to_owned()))?; let Some(first_command) = command_values.next() else { - return Err(UUsageError::new(125, "no command specified".to_string())); + return Err(UUsageError::new(125, "no command specified".to_owned())); }; let mut command = process::Command::new(first_command); let command_params: Vec<&OsString> = command_values.collect(); diff --git a/src/uu/stty/src/stty.rs b/src/uu/stty/src/stty.rs index af54db3e9fe..03d990653d3 100644 --- a/src/uu/stty/src/stty.rs +++ b/src/uu/stty/src/stty.rs @@ -203,7 +203,7 @@ impl<'a> Options<'a> { // Per POSIX, stdin is used for TTY operations when no device is specified. // This matches GNU coreutils behavior: if stdin is not a TTY, // tcgetattr will fail with "Inappropriate ioctl for device". - None => (Device::Stdin(stdin()), "standard input".to_string()), + None => (Device::Stdin(stdin()), "standard input".to_owned()), }; Ok(Self { all: matches.get_flag(options::ALL), @@ -1065,7 +1065,7 @@ fn string_to_control_char(s: &str) -> Result { if let Some(val) = ascii_num { if val > 255 { - return Err(ControlCharMappingError::IntOutOfRange(s.to_string())); + return Err(ControlCharMappingError::IntOutOfRange(s.to_owned())); } return Ok(val as u8); } @@ -1081,7 +1081,7 @@ fn string_to_control_char(s: &str) -> Result { Ok((c.to_ascii_uppercase() as u8).wrapping_sub(b'@')) } (Some(c), None) => Ok(c as u8), - (Some(_), Some(_)) => Err(ControlCharMappingError::MultipleChars(s.to_string())), + (Some(_), Some(_)) => Err(ControlCharMappingError::MultipleChars(s.to_owned())), _ => unreachable!("No arguments provided: must have been caught earlier"), } } diff --git a/src/uu/sync/src/sync.rs b/src/uu/sync/src/sync.rs index 0e5b864b9cd..ea3e1aed945 100644 --- a/src/uu/sync/src/sync.rs +++ b/src/uu/sync/src/sync.rs @@ -57,7 +57,7 @@ mod platform { /// Logs a warning if fcntl fails but doesn't abort the operation. #[cfg(any(target_os = "linux", target_os = "android"))] fn open_and_reset_nonblock(path: &str) -> UResult { - let f = File::open(path).map_err_context(|| path.to_string())?; + let f = File::open(path).map_err_context(|| path.to_owned())?; // Reset O_NONBLOCK flag if it was set (matches GNU behavior) // This is non-critical, so we log errors but don't fail if let Err(e) = fcntl(&f, FcntlArg::F_SETFL(OFlag::empty())) { diff --git a/src/uu/timeout/src/timeout.rs b/src/uu/timeout/src/timeout.rs index 6944794f19c..50a9526304f 100644 --- a/src/uu/timeout/src/timeout.rs +++ b/src/uu/timeout/src/timeout.rs @@ -225,9 +225,9 @@ fn install_signal_handlers(term_signal: usize) { fn report_if_verbose(signal: usize, cmd: &str, verbose: bool) { if verbose { let s = if signal == 0 { - "0".to_string() + "0".to_owned() } else { - signal_name_by_value(signal).unwrap().to_string() + signal_name_by_value(signal).unwrap().to_owned() }; let mut stderr = std::io::stderr(); let _ = writeln!( diff --git a/src/uu/touch/src/touch.rs b/src/uu/touch/src/touch.rs index e50686417e2..24964b2a4bc 100644 --- a/src/uu/touch/src/touch.rs +++ b/src/uu/touch/src/touch.rs @@ -193,7 +193,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { .ok_or_else(|| { USimpleError::new( 1, - translate!("touch-error-missing-file-operand", "help_command" => uucore::execution_phrase().to_string(),), + translate!("touch-error-missing-file-operand", "help_command" => uucore::execution_phrase().to_owned(),), ) })? .collect(); @@ -214,7 +214,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { timestamp = if first_file.len() == 10 { Some(shr2(first_file)) } else { - Some(first_file.to_string()) + Some(first_file.to_owned()) }; filenames = filenames[1..].to_vec(); } @@ -810,7 +810,7 @@ fn pathbuf_from_stdout() -> Result { 0 => { return Err(TouchError::WindowsStdoutPathError(translate!( "touch-error-windows-stdout-path-failed", - "code".to_string() => + "code".to_owned() => format!( "{}", // SAFETY: GetLastError is thread-safe and has no documented memory unsafety. diff --git a/src/uu/truncate/src/truncate.rs b/src/uu/truncate/src/truncate.rs index 997916b24a8..73421fee3c5 100644 --- a/src/uu/truncate/src/truncate.rs +++ b/src/uu/truncate/src/truncate.rs @@ -333,7 +333,7 @@ fn parse_mode_and_size(size_string: &str) -> Result TruncateMode::Absolute, }) } else { - Err(ParseSizeError::ParseFailure(size_string.to_string())) + Err(ParseSizeError::ParseFailure(size_string.to_owned())) } } diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 14c2b8b0b0a..7309e9723d8 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -41,7 +41,7 @@ fn parse_tab_num(word: &str, allow_zero: bool) -> Result { Err(e) => match e.kind() { IntErrorKind::PosOverflow => Err(ParseError::TabSizeTooLarge), _ => Err(ParseError::InvalidCharacter( - word.trim_start_matches(char::is_numeric).to_string(), + word.trim_start_matches(char::is_numeric).to_owned(), )), }, } @@ -63,7 +63,7 @@ fn parse_tabstops(s: &str) -> Result { if let Some(word) = word.strip_prefix('+') { // +N means N positions after the last tab stop (only allowed at end) if increment_size.is_some() || extend_size.is_some() { - return Err(ParseError::InvalidCharacter("+".to_string())); + return Err(ParseError::InvalidCharacter("+".to_owned())); } let value = parse_tab_num(word, true)?; if nums.is_empty() { @@ -81,7 +81,7 @@ fn parse_tabstops(s: &str) -> Result { } else if let Some(word) = word.strip_prefix('/') { // /N means repeat every N positions after the last tab stop if increment_size.is_some() || extend_size.is_some() { - return Err(ParseError::InvalidCharacter("/".to_string())); + return Err(ParseError::InvalidCharacter("/".to_owned())); } let value = parse_tab_num(word, true)?; if nums.is_empty() { @@ -99,7 +99,7 @@ fn parse_tabstops(s: &str) -> Result { } else { // Regular number if increment_size.is_some() || extend_size.is_some() { - return Err(ParseError::InvalidCharacter(word.to_string())); + return Err(ParseError::InvalidCharacter(word.to_owned())); } nums.push(parse_tab_num(word, false)?); } diff --git a/src/uu/uniq/benches/uniq_bench.rs b/src/uu/uniq/benches/uniq_bench.rs index ab5e5703853..9086d6e71e0 100644 --- a/src/uu/uniq/benches/uniq_bench.rs +++ b/src/uu/uniq/benches/uniq_bench.rs @@ -81,7 +81,7 @@ fn uniq_case_insensitive(bencher: Bencher, num_lines: usize) { let variation = match i % 4 { 0 => word.to_lowercase(), 1 => word.to_uppercase(), - 2 => word.to_string(), + 2 => word.to_owned(), _ => { // Mixed case word.chars() diff --git a/src/uucore/build.rs b/src/uucore/build.rs index 15068f28aab..21a50a9229c 100644 --- a/src/uucore/build.rs +++ b/src/uucore/build.rs @@ -94,7 +94,7 @@ fn detect_target_utility() -> Option { if let Ok(pkg_name) = env::var("CARGO_PKG_NAME") { if let Some(util_name) = pkg_name.strip_prefix("uu_") { println!("cargo:warning=Auto-detected utility name: {util_name}"); - return Some(util_name.to_string()); + return Some(util_name.to_owned()); } } @@ -104,7 +104,7 @@ fn detect_target_utility() -> Option { if let Ok(content) = fs::read_to_string(&config_path) { let util_name = content.trim(); if !util_name.is_empty() && util_name != "multicall" { - return Some(util_name.to_string()); + return Some(util_name.to_owned()); } } } @@ -115,7 +115,7 @@ fn detect_target_utility() -> Option { if let Ok(content) = fs::read_to_string(&config_path) { let util_name = content.trim(); if !util_name.is_empty() && util_name != "multicall" { - return Some(util_name.to_string()); + return Some(util_name.to_owned()); } } } @@ -188,7 +188,7 @@ fn embed_all_utility_locales( let entry = entry?; if entry.file_type()?.is_dir() { if let Some(dir_name) = entry.file_name().to_str() { - util_dirs.push(dir_name.to_string()); + util_dirs.push(dir_name.to_owned()); } } } @@ -282,7 +282,7 @@ fn get_locales_to_embed() -> (String, Option) { None } }); - ("en-US".to_string(), system_locale) + ("en-US".to_owned(), system_locale) } /// Helper function to iterate over the locales to embed. diff --git a/src/uucore/src/lib/features/backup_control.rs b/src/uucore/src/lib/features/backup_control.rs index 6c26b9d5809..36b3d8df311 100644 --- a/src/uucore/src/lib/features/backup_control.rs +++ b/src/uucore/src/lib/features/backup_control.rs @@ -407,9 +407,9 @@ fn match_method(method: &str, origin: &str) -> UResult { // from the list above. } } else if matches.is_empty() { - Err(BackupError::InvalidArgument(method.to_string(), origin.to_string()).into()) + Err(BackupError::InvalidArgument(method.to_owned(), origin.to_owned()).into()) } else { - Err(BackupError::AmbiguousArgument(method.to_string(), origin.to_string()).into()) + Err(BackupError::AmbiguousArgument(method.to_owned(), origin.to_owned()).into()) } } diff --git a/src/uucore/src/lib/features/checksum/mod.rs b/src/uucore/src/lib/features/checksum/mod.rs index 0c6dc54f3b5..d77464817da 100644 --- a/src/uucore/src/lib/features/checksum/mod.rs +++ b/src/uucore/src/lib/features/checksum/mod.rs @@ -114,7 +114,7 @@ impl AlgoKind { ALGORITHM_OPTIONS_SHA256 => Sha256, ALGORITHM_OPTIONS_SHA384 => Sha384, ALGORITHM_OPTIONS_SHA512 => Sha512, - _ => return Err(ChecksumError::UnknownAlgorithm(algo.as_ref().to_string()).into()), + _ => return Err(ChecksumError::UnknownAlgorithm(algo.as_ref().to_owned()).into()), }) } @@ -131,7 +131,7 @@ impl AlgoKind { "sha3sum" => Sha3, "b2sum" => Blake2b, - _ => return Err(ChecksumError::UnknownAlgorithm(algo.as_ref().to_string()).into()), + _ => return Err(ChecksumError::UnknownAlgorithm(algo.as_ref().to_owned()).into()), }) } diff --git a/src/uucore/src/lib/features/format/num_format.rs b/src/uucore/src/lib/features/format/num_format.rs index 9a09b3f7dec..3547eb0475e 100644 --- a/src/uucore/src/lib/features/format/num_format.rs +++ b/src/uucore/src/lib/features/format/num_format.rs @@ -645,7 +645,7 @@ fn format_float_hexadecimal( let (first_digit, remaining_digits) = digits.split_at(1); let exponent = exp2 + (4 * max_precision) as i64; - let mut remaining_digits = remaining_digits.to_string(); + let mut remaining_digits = remaining_digits.to_owned(); if precision.is_none() { // Trim trailing zeros strip_fractional_zeroes(&mut remaining_digits); diff --git a/src/uucore/src/lib/features/i18n/decimal.rs b/src/uucore/src/lib/features/i18n/decimal.rs index a7ceca2efa3..be3e9defd86 100644 --- a/src/uucore/src/lib/features/i18n/decimal.rs +++ b/src/uucore/src/lib/features/i18n/decimal.rs @@ -23,7 +23,7 @@ fn get_decimal_separator(loc: Locale) -> String { let response: DataResponse = icu_decimal::provider::Baked.load(request).unwrap(); - response.payload.get().decimal_separator().to_string() + response.payload.get().decimal_separator().to_owned() } /// Return the decimal separator from the language we're working with. @@ -49,7 +49,7 @@ fn get_grouping_separator(loc: Locale) -> String { let response: DataResponse = icu_decimal::provider::Baked.load(request).unwrap(); - response.payload.get().grouping_separator().to_string() + response.payload.get().grouping_separator().to_owned() } /// Return the grouping separator from the language we're working with. diff --git a/src/uucore/src/lib/features/parser/num_parser.rs b/src/uucore/src/lib/features/parser/num_parser.rs index f87be3052b4..4d13f0f6f6e 100644 --- a/src/uucore/src/lib/features/parser/num_parser.rs +++ b/src/uucore/src/lib/features/parser/num_parser.rs @@ -370,7 +370,7 @@ fn parse_special_value( return if rest.is_empty() { Ok(special) } else { - Err(ExtendedParserError::PartialMatch(special, rest.to_string())) + Err(ExtendedParserError::PartialMatch(special, rest.to_owned())) }; } } @@ -533,7 +533,7 @@ pub(crate) fn parse( } else { ExtendedBigDecimal::zero() }; - return Err(ExtendedParserError::PartialMatch(ebd, partial.to_string())); + return Err(ExtendedParserError::PartialMatch(ebd, partial.to_owned())); } return if target == ParseTarget::Integral { @@ -557,7 +557,7 @@ pub(crate) fn parse( } else { Err(ExtendedParserError::PartialMatch( ebd_result.unwrap_or_else(|e| e.extract()), - rest.to_string(), + rest.to_owned(), )) } } @@ -605,11 +605,11 @@ mod tests { )); assert_eq!( u64::extended_parse("123.15"), - Err(ExtendedParserError::PartialMatch(123, ".15".to_string())) + Err(ExtendedParserError::PartialMatch(123, ".15".to_owned())) ); assert_eq!( u64::extended_parse("123e10"), - Err(ExtendedParserError::PartialMatch(123, "e10".to_string())) + Err(ExtendedParserError::PartialMatch(123, "e10".to_owned())) ); } @@ -634,7 +634,7 @@ mod tests { )); assert_eq!( i64::extended_parse("-123e10"), - Err(ExtendedParserError::PartialMatch(-123, "e10".to_string())) + Err(ExtendedParserError::PartialMatch(-123, "e10".to_owned())) ); assert!(matches!( i64::extended_parse(&format!("{}", -(u64::MAX as i128))), @@ -689,31 +689,31 @@ mod tests { ); assert_eq!( f64::extended_parse("123.15e"), - Err(ExtendedParserError::PartialMatch(123.15, "e".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "e".to_owned())) ); assert_eq!( f64::extended_parse("123.15E"), - Err(ExtendedParserError::PartialMatch(123.15, "E".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "E".to_owned())) ); assert_eq!( f64::extended_parse("123.15e-"), - Err(ExtendedParserError::PartialMatch(123.15, "e-".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "e-".to_owned())) ); assert_eq!( f64::extended_parse("123.15e+"), - Err(ExtendedParserError::PartialMatch(123.15, "e+".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "e+".to_owned())) ); assert_eq!( f64::extended_parse("123.15e."), - Err(ExtendedParserError::PartialMatch(123.15, "e.".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "e.".to_owned())) ); assert_eq!( f64::extended_parse("1.2.3"), - Err(ExtendedParserError::PartialMatch(1.2, ".3".to_string())) + Err(ExtendedParserError::PartialMatch(1.2, ".3".to_owned())) ); assert_eq!( f64::extended_parse("123.15p5"), - Err(ExtendedParserError::PartialMatch(123.15, "p5".to_string())) + Err(ExtendedParserError::PartialMatch(123.15, "p5".to_owned())) ); // Minus zero. 0.0 == -0.0 so we explicitly check the sign. assert_eq!(Ok(0.0), f64::extended_parse("-0.0")); @@ -741,14 +741,14 @@ mod tests { f64::extended_parse("-infinit"), Err(ExtendedParserError::PartialMatch( f64::NEG_INFINITY, - "init".to_string() + "init".to_owned() )) ); assert_eq!( f64::extended_parse("-infinity00"), Err(ExtendedParserError::PartialMatch( f64::NEG_INFINITY, - "00".to_string() + "00".to_owned() )) ); assert!(f64::extended_parse(&format!("{}", u64::MAX)).is_ok()); @@ -937,19 +937,19 @@ mod tests { assert_eq!( f64::extended_parse("0x0.1p"), - Err(ExtendedParserError::PartialMatch(0.0625, "p".to_string())) + Err(ExtendedParserError::PartialMatch(0.0625, "p".to_owned())) ); assert_eq!( f64::extended_parse("0x0.1p-"), - Err(ExtendedParserError::PartialMatch(0.0625, "p-".to_string())) + Err(ExtendedParserError::PartialMatch(0.0625, "p-".to_owned())) ); assert_eq!( f64::extended_parse("0x.1p+"), - Err(ExtendedParserError::PartialMatch(0.0625, "p+".to_string())) + Err(ExtendedParserError::PartialMatch(0.0625, "p+".to_owned())) ); assert_eq!( f64::extended_parse("0x.1p."), - Err(ExtendedParserError::PartialMatch(0.0625, "p.".to_string())) + Err(ExtendedParserError::PartialMatch(0.0625, "p.".to_owned())) ); assert_eq!( @@ -1012,55 +1012,55 @@ mod tests { // Not actually hex numbers, but the prefixes look like it. assert_eq!( f64::extended_parse("0x"), - Err(ExtendedParserError::PartialMatch(0.0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "x".to_owned())) ); assert_eq!( f64::extended_parse("0x."), - Err(ExtendedParserError::PartialMatch(0.0, "x.".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "x.".to_owned())) ); assert_eq!( f64::extended_parse("0xp"), - Err(ExtendedParserError::PartialMatch(0.0, "xp".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "xp".to_owned())) ); assert_eq!( f64::extended_parse("0xp-2"), - Err(ExtendedParserError::PartialMatch(0.0, "xp-2".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "xp-2".to_owned())) ); assert_eq!( f64::extended_parse("0x.p-2"), - Err(ExtendedParserError::PartialMatch(0.0, "x.p-2".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "x.p-2".to_owned())) ); assert_eq!( f64::extended_parse("0X"), - Err(ExtendedParserError::PartialMatch(0.0, "X".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "X".to_owned())) ); assert_eq!( f64::extended_parse("-0x"), - Err(ExtendedParserError::PartialMatch(0.0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "x".to_owned())) ); assert_eq!( f64::extended_parse("+0x"), - Err(ExtendedParserError::PartialMatch(0.0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0.0, "x".to_owned())) ); assert_eq!( f64::extended_parse("-0x."), - Err(ExtendedParserError::PartialMatch(-0.0, "x.".to_string())) + Err(ExtendedParserError::PartialMatch(-0.0, "x.".to_owned())) ); assert_eq!( u64::extended_parse("0x"), - Err(ExtendedParserError::PartialMatch(0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0, "x".to_owned())) ); assert_eq!( u64::extended_parse("-0x"), - Err(ExtendedParserError::PartialMatch(0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0, "x".to_owned())) ); assert_eq!( i64::extended_parse("0x"), - Err(ExtendedParserError::PartialMatch(0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0, "x".to_owned())) ); assert_eq!( i64::extended_parse("-0x"), - Err(ExtendedParserError::PartialMatch(0, "x".to_string())) + Err(ExtendedParserError::PartialMatch(0, "x".to_owned())) ); } @@ -1074,15 +1074,15 @@ mod tests { assert_eq!(Ok(0), u64::extended_parse("00")); assert_eq!( u64::extended_parse("008"), - Err(ExtendedParserError::PartialMatch(0, "8".to_string())) + Err(ExtendedParserError::PartialMatch(0, "8".to_owned())) ); assert_eq!( u64::extended_parse("08"), - Err(ExtendedParserError::PartialMatch(0, "8".to_string())) + Err(ExtendedParserError::PartialMatch(0, "8".to_owned())) ); assert_eq!( u64::extended_parse("0."), - Err(ExtendedParserError::PartialMatch(0, ".".to_string())) + Err(ExtendedParserError::PartialMatch(0, ".".to_owned())) ); // No float tests, leading zeros get parsed as decimal anyway. @@ -1097,35 +1097,35 @@ mod tests { assert_eq!( u64::extended_parse("0b"), - Err(ExtendedParserError::PartialMatch(0, "b".to_string())) + Err(ExtendedParserError::PartialMatch(0, "b".to_owned())) ); assert_eq!( u64::extended_parse("0b."), - Err(ExtendedParserError::PartialMatch(0, "b.".to_string())) + Err(ExtendedParserError::PartialMatch(0, "b.".to_owned())) ); assert_eq!( u64::extended_parse("-0b"), - Err(ExtendedParserError::PartialMatch(0, "b".to_string())) + Err(ExtendedParserError::PartialMatch(0, "b".to_owned())) ); assert_eq!( i64::extended_parse("0b"), - Err(ExtendedParserError::PartialMatch(0, "b".to_string())) + Err(ExtendedParserError::PartialMatch(0, "b".to_owned())) ); assert_eq!( i64::extended_parse("-0b"), - Err(ExtendedParserError::PartialMatch(0, "b".to_string())) + Err(ExtendedParserError::PartialMatch(0, "b".to_owned())) ); // Binary not allowed for floats assert_eq!( f64::extended_parse("0b100"), - Err(ExtendedParserError::PartialMatch(0f64, "b100".to_string())) + Err(ExtendedParserError::PartialMatch(0f64, "b100".to_owned())) ); assert_eq!( f64::extended_parse("0b100.1"), Err(ExtendedParserError::PartialMatch( 0f64, - "b100.1".to_string() + "b100.1".to_owned() )) ); @@ -1133,7 +1133,7 @@ mod tests { ExtendedBigDecimal::extended_parse("0b100.1"), Err(ExtendedParserError::PartialMatch( ExtendedBigDecimal::zero(), - "b100.1".to_string() + "b100.1".to_owned() )) ); @@ -1141,14 +1141,14 @@ mod tests { ExtendedBigDecimal::extended_parse("0b"), Err(ExtendedParserError::PartialMatch( ExtendedBigDecimal::zero(), - "b".to_string() + "b".to_owned() )) ); assert_eq!( ExtendedBigDecimal::extended_parse("0b."), Err(ExtendedParserError::PartialMatch( ExtendedBigDecimal::zero(), - "b.".to_string() + "b.".to_owned() )) ); } @@ -1163,15 +1163,15 @@ mod tests { // Ensure that trailing whitespace is still a partial match assert_eq!( - Err(ExtendedParserError::PartialMatch(6, " ".to_string())), + Err(ExtendedParserError::PartialMatch(6, " ".to_owned())), u64::extended_parse("0x6 ") ); assert_eq!( - Err(ExtendedParserError::PartialMatch(7, "\t".to_string())), + Err(ExtendedParserError::PartialMatch(7, "\t".to_owned())), u64::extended_parse("0x7\t") ); assert_eq!( - Err(ExtendedParserError::PartialMatch(8, "\n".to_string())), + Err(ExtendedParserError::PartialMatch(8, "\n".to_owned())), u64::extended_parse("0x8\n") ); diff --git a/src/uucore/src/lib/features/parser/parse_signed_num.rs b/src/uucore/src/lib/features/parser/parse_signed_num.rs index 82ffcaaca43..a87d4c57d36 100644 --- a/src/uucore/src/lib/features/parser/parse_signed_num.rs +++ b/src/uucore/src/lib/features/parser/parse_signed_num.rs @@ -79,7 +79,7 @@ pub fn parse_signed_num_max(src: &str) -> Result { // Empty string after stripping sign is an error if size_string.is_empty() { - return Err(ParseSizeError::ParseFailure(src.to_string())); + return Err(ParseSizeError::ParseFailure(src.to_owned())); } // Remove leading zeros so size is interpreted as decimal, not octal @@ -106,13 +106,13 @@ pub fn parse_signed_num(src: &str) -> Result { // Empty string after stripping sign is an error if size_string.is_empty() { - return Err(ParseSizeError::ParseFailure(src.to_string())); + return Err(ParseSizeError::ParseFailure(src.to_owned())); } // Use parse_size_u64 but on failure, create our own error with the raw string // (without quotes) so callers can format it as needed let value = parse_size_u64(size_string) - .map_err(|_| ParseSizeError::ParseFailure(size_string.to_string()))?; + .map_err(|_| ParseSizeError::ParseFailure(size_string.to_owned()))?; Ok(SignedNum { value, sign }) } diff --git a/src/uucore/src/lib/features/parser/parse_size.rs b/src/uucore/src/lib/features/parser/parse_size.rs index 05c270e4cf8..0ac4212dcbc 100644 --- a/src/uucore/src/lib/features/parser/parse_size.rs +++ b/src/uucore/src/lib/features/parser/parse_size.rs @@ -220,7 +220,7 @@ impl<'parser> Parser<'parser> { let number: u128 = Self::parse_number(&numeric_string, 10, size)?; return match total_physical_memory() { Ok(total) => Ok((number / 100) * total), - Err(_) => Err(ParseSizeError::PhysicalMem(size.to_string())), + Err(_) => Err(ParseSizeError::PhysicalMem(size.to_owned())), }; } @@ -368,7 +368,7 @@ impl<'parser> Parser<'parser> { ) -> Result { u128::from_str_radix(numeric_string, radix).map_err(|e| match e.kind() { IntErrorKind::PosOverflow => ParseSizeError::size_too_big(original_size), - _ => ParseSizeError::ParseFailure(original_size.to_string()), + _ => ParseSizeError::ParseFailure(original_size.to_owned()), }) } } @@ -400,7 +400,7 @@ pub fn parse_size_u64(size: &str) -> Result { pub fn parse_size_non_zero_u64(size: &str) -> Result { let v = Parser::default().parse_u64(size)?; if v == 0 { - return Err(ParseSizeError::ParseFailure("0".to_string())); + return Err(ParseSizeError::ParseFailure("0".to_owned())); } Ok(v) } @@ -594,15 +594,15 @@ mod tests { )); assert_eq!( - ParseSizeError::SizeTooBig("'1Y': Value too large for defined data type".to_string()), + ParseSizeError::SizeTooBig("'1Y': Value too large for defined data type".to_owned()), parse_size_u64("1Y").unwrap_err() ); assert_eq!( - ParseSizeError::SizeTooBig("'1R': Value too large for defined data type".to_string()), + ParseSizeError::SizeTooBig("'1R': Value too large for defined data type".to_owned()), parse_size_u64("1R").unwrap_err() ); assert_eq!( - ParseSizeError::SizeTooBig("'1Q': Value too large for defined data type".to_string()), + ParseSizeError::SizeTooBig("'1Q': Value too large for defined data type".to_owned()), parse_size_u64("1Q").unwrap_err() ); } diff --git a/src/uucore/src/lib/features/parser/shortcut_value_parser.rs b/src/uucore/src/lib/features/parser/shortcut_value_parser.rs index 5800a91f8a2..199ff4a9d0b 100644 --- a/src/uucore/src/lib/features/parser/shortcut_value_parser.rs +++ b/src/uucore/src/lib/features/parser/shortcut_value_parser.rs @@ -45,12 +45,12 @@ impl ShortcutValueParser { err.insert( ContextKind::InvalidValue, - ContextValue::String(value.to_string()), + ContextValue::String(value.to_owned()), ); err.insert( ContextKind::ValidValue, - ContextValue::Strings(self.0.iter().map(|x| x.get_name().to_string()).collect()), + ContextValue::Strings(self.0.iter().map(|x| x.get_name().to_owned()).collect()), ); // if `possible_values` is not empty then that means this error is because of an ambiguous value. @@ -106,10 +106,10 @@ impl TypedValueParser for ShortcutValueParser { match matched_values.len() { 0 => Err(self.generate_clap_error(cmd, arg, value, &[])), - 1 => Ok(matched_values[0].get_name().to_string()), + 1 => Ok(matched_values[0].get_name().to_owned()), _ => { if let Some(direct_match) = matched_values.iter().find(|x| x.get_name() == value) { - Ok(direct_match.get_name().to_string()) + Ok(direct_match.get_name().to_owned()) } else { Err(self.generate_clap_error(cmd, arg, value, &matched_values)) } diff --git a/src/uucore/src/lib/features/perms.rs b/src/uucore/src/lib/features/perms.rs index e9aaf875dc6..f78ecdd2baa 100644 --- a/src/uucore/src/lib/features/perms.rs +++ b/src/uucore/src/lib/features/perms.rs @@ -832,7 +832,7 @@ pub fn configure_symlink_and_recursion( if dereference == Some(true) { return Err(USimpleError::new( 1, - "-R --dereference requires -H or -L".to_string(), + "-R --dereference requires -H or -L".to_owned(), )); } dereference = Some(false); diff --git a/src/uucore/src/lib/features/proc_info.rs b/src/uucore/src/lib/features/proc_info.rs index 0d99cb8a8b9..3d86aa7c8e5 100644 --- a/src/uucore/src/lib/features/proc_info.rs +++ b/src/uucore/src/lib/features/proc_info.rs @@ -205,7 +205,7 @@ impl ProcessInformation { .inner_status .lines() .filter_map(|it| it.split_once(':')) - .map(|it| (it.0.to_string(), it.1.trim_start().to_string())) + .map(|it| (it.0.to_owned(), it.1.trim_start().to_owned())) .collect::>(); let result = Rc::new(result); diff --git a/src/uucore/src/lib/features/quoting_style/mod.rs b/src/uucore/src/lib/features/quoting_style/mod.rs index 9613e579d9e..000cf59db70 100644 --- a/src/uucore/src/lib/features/quoting_style/mod.rs +++ b/src/uucore/src/lib/features/quoting_style/mod.rs @@ -236,7 +236,7 @@ impl fmt::Display for QuotingStyle { always_quote, show_control, } => { - let mut style = "shell".to_string(); + let mut style = "shell".to_owned(); if escape { style.push_str("-escape"); } diff --git a/src/uucore/src/lib/features/selinux.rs b/src/uucore/src/lib/features/selinux.rs index ed79be414ef..9f3f311f258 100644 --- a/src/uucore/src/lib/features/selinux.rs +++ b/src/uucore/src/lib/features/selinux.rs @@ -387,7 +387,7 @@ pub fn get_getfattr_output(f: &str) -> String { .split('"') .nth(1) .unwrap_or("") - .to_string() + .to_owned() } #[cfg(test)] diff --git a/src/uucore/src/lib/features/smack.rs b/src/uucore/src/lib/features/smack.rs index d901bde00be..c69a3e27c2a 100644 --- a/src/uucore/src/lib/features/smack.rs +++ b/src/uucore/src/lib/features/smack.rs @@ -63,7 +63,7 @@ pub fn get_smack_label_for_self() -> Result { .read_to_string(&mut label) .map_err(SmackError::LabelRetrievalFailure)?; - Ok(label.trim().to_string()) + Ok(label.trim().to_owned()) } /// Sets the SMACK label for the current process. @@ -74,7 +74,7 @@ pub fn set_smack_label_for_self(label: &str) -> Result<(), SmackError> { fs::File::create("/proc/self/attr/current") .and_then(|mut f| f.write_all(label.as_bytes())) - .map_err(|e| SmackError::LabelSetFailure(label.to_string(), e)) + .map_err(|e| SmackError::LabelSetFailure(label.to_owned(), e)) } /// Gets the SMACK label for a filesystem path via xattr. @@ -84,7 +84,7 @@ pub fn get_smack_label_for_path(path: &Path) -> Result { } match xattr::get(path, "security.SMACK64") { - Ok(Some(value)) => Ok(String::from_utf8_lossy(&value).trim().to_string()), + Ok(Some(value)) => Ok(String::from_utf8_lossy(&value).trim().to_owned()), Ok(None) => Err(SmackError::LabelRetrievalFailure(io::Error::new( io::ErrorKind::NotFound, translate!("smack-error-no-label-set"), @@ -100,7 +100,7 @@ pub fn set_smack_label_for_path(path: &Path, label: &str) -> Result<(), SmackErr } xattr::set(path, "security.SMACK64", label.as_bytes()) - .map_err(|e| SmackError::LabelSetFailure(label.to_string(), e)) + .map_err(|e| SmackError::LabelSetFailure(label.to_owned(), e)) } /// Sets SMACK label for a new path, calling cleanup on failure. diff --git a/src/uucore/src/lib/features/systemd_logind.rs b/src/uucore/src/lib/features/systemd_logind.rs index 9efd46a3945..8d3d4b68522 100644 --- a/src/uucore/src/lib/features/systemd_logind.rs +++ b/src/uucore/src/lib/features/systemd_logind.rs @@ -328,9 +328,9 @@ pub fn read_login_records() -> UResult> { // Add boot time record first if let Ok(boot_time) = login::get_boot_time() { let boot_record = SystemdLoginRecord { - user: "reboot".to_string(), - session_id: "boot".to_string(), - seat_or_tty: "~".to_string(), // Traditional boot time indicator + user: "reboot".to_owned(), + session_id: "boot".to_owned(), + seat_or_tty: "~".to_owned(), // Traditional boot time indicator raw_device: String::new(), host: String::new(), login_time: boot_time, @@ -675,22 +675,22 @@ mod tests { // Create iterator with mock records let mock_records = vec![ SystemdLoginRecord { - session_id: "session1".to_string(), - user: "user1".to_string(), - seat_or_tty: "tty1".to_string(), - raw_device: "tty1".to_string(), - host: "host1".to_string(), + session_id: "session1".to_owned(), + user: "user1".to_owned(), + seat_or_tty: "tty1".to_owned(), + raw_device: "tty1".to_owned(), + host: "host1".to_owned(), login_time: UNIX_EPOCH, pid: 1234, session_leader_pid: 1234, record_type: SystemdRecordType::UserProcess, }, SystemdLoginRecord { - session_id: "session2".to_string(), - user: "user2".to_string(), - seat_or_tty: "pts/0".to_string(), - raw_device: "pts/0".to_string(), - host: "host2".to_string(), + session_id: "session2".to_owned(), + user: "user2".to_owned(), + seat_or_tty: "pts/0".to_owned(), + raw_device: "pts/0".to_owned(), + host: "host2".to_owned(), login_time: UNIX_EPOCH, pid: 5678, session_leader_pid: 5678, @@ -723,11 +723,11 @@ mod tests { #[test] fn test_get_all_records() { let mock_records = vec![SystemdLoginRecord { - session_id: "session1".to_string(), - user: "user1".to_string(), - seat_or_tty: "tty1".to_string(), - raw_device: "tty1".to_string(), - host: "host1".to_string(), + session_id: "session1".to_owned(), + user: "user1".to_owned(), + seat_or_tty: "tty1".to_owned(), + raw_device: "tty1".to_owned(), + host: "host1".to_owned(), login_time: UNIX_EPOCH, pid: 1234, session_leader_pid: 1234, @@ -747,11 +747,11 @@ mod tests { fn test_systemd_record_conversion() { // Test that SystemdLoginRecord converts correctly to SystemdUtmpxCompat let record = SystemdLoginRecord { - session_id: "c1".to_string(), - user: "testuser".to_string(), - seat_or_tty: "seat0".to_string(), - raw_device: "seat0".to_string(), - host: "localhost".to_string(), + session_id: "c1".to_owned(), + user: "testuser".to_owned(), + seat_or_tty: "seat0".to_owned(), + raw_device: "seat0".to_owned(), + host: "localhost".to_owned(), login_time: UNIX_EPOCH + std::time::Duration::from_secs(1000), pid: 9999, session_leader_pid: 9999, diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index 8a6d03fd546..aca4f52599e 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -295,7 +295,7 @@ impl Utmpx { } } else { // GNU coreutils has this behavior - return Ok(hostname.to_string()); + return Ok(hostname.to_owned()); } } diff --git a/src/uucore/src/lib/mods/clap_localization.rs b/src/uucore/src/lib/mods/clap_localization.rs index cfc30ab22fd..9b3dec5b4c7 100644 --- a/src/uucore/src/lib/mods/clap_localization.rs +++ b/src/uucore/src/lib/mods/clap_localization.rs @@ -74,7 +74,7 @@ impl ColorManager { if self.0 { format!("\x1b[{}m{text}\x1b[0m", color.code()) } else { - text.to_string() + text.to_owned() } } } diff --git a/src/uucore/src/lib/mods/locale.rs b/src/uucore/src/lib/mods/locale.rs index b670f897620..163ed7f2a70 100644 --- a/src/uucore/src/lib/mods/locale.rs +++ b/src/uucore/src/lib/mods/locale.rs @@ -102,7 +102,7 @@ impl Localizer { } // Return the key ID if not found anywhere - id.to_string() + id.to_owned() } } @@ -220,21 +220,20 @@ fn init_localization( /// Helper function to parse FluentResource from content string fn parse_fluent_resource(content: &str) -> Result { - FluentResource::try_new(content.to_string()).map_err( + FluentResource::try_new(content.to_owned()).map_err( |(_partial_resource, errs): (FluentResource, Vec)| { if let Some(first_err) = errs.into_iter().next() { let snippet = first_err .slice .clone() .and_then(|range| content.get(range)) - .unwrap_or("") - .to_string(); + .unwrap_or("").to_owned(); LocalizationError::ParseResource { error: first_err, snippet, } } else { - LocalizationError::LocalesDirNotFound("Parse error without details".to_string()) + LocalizationError::LocalesDirNotFound("Parse error without details".to_owned()) } }, ) @@ -248,7 +247,7 @@ fn create_english_bundle_from_embedded( // Only support English from embedded files if *locale != "en-US" { return Err(LocalizationError::LocalesDirNotFound( - "Embedded locales only support en-US".to_string(), + "Embedded locales only support en-US".to_owned(), )); } @@ -289,7 +288,7 @@ fn create_english_bundle_from_embedded( fn get_message_internal(id: &str, args: Option) -> String { LOCALIZER.with(|lock| { lock.get() - .map_or_else(|| id.to_string(), |loc| loc.format(id, args.as_ref())) // Return the key ID if localizer not initialized + .map_or_else(|| id.to_owned(), |loc| loc.format(id, args.as_ref())) // Return the key ID if localizer not initialized }) } @@ -359,11 +358,10 @@ pub fn get_message_with_args(id: &str, ftl_args: FluentArgs) -> String { /// Function to detect system locale from environment variables fn detect_system_locale() -> Result { let locale_str = std::env::var("LANG") - .unwrap_or_else(|_| DEFAULT_LOCALE.to_string()) + .unwrap_or_else(|_| DEFAULT_LOCALE.to_owned()) .split('.') .next() - .unwrap_or(DEFAULT_LOCALE) - .to_string(); + .unwrap_or(DEFAULT_LOCALE).to_owned(); LanguageIdentifier::from_str(&locale_str).map_err(|_| { LocalizationError::ParseLocale(format!("Failed to parse locale: {locale_str}")) }) @@ -927,7 +925,7 @@ invalid-syntax = This is { $missing init_test_localization(&locale, temp_dir.path()).unwrap(); let mut args = FluentArgs::new(); - args.set("name".to_string(), "Bob".to_string()); + args.set("name".to_owned(), "Bob".to_owned()); let message = get_message_with_args("welcome", args); assert_eq!(message, "Welcome, Bob!"); @@ -1018,13 +1016,13 @@ invalid-syntax = This is { $missing // Test Japanese with arguments let mut args = FluentArgs::new(); - args.set("name".to_string(), "田中".to_string()); + args.set("name".to_owned(), "田中".to_owned()); let welcome = get_message_with_args("welcome", args); assert_eq!(welcome, "ようこそ、田中さん!"); // Test Japanese count (no pluralization) let mut count_args = FluentArgs::new(); - count_args.set("count".to_string(), "5".to_string()); + count_args.set("count".to_owned(), "5".to_owned()); let count_message = get_message_with_args("count-items", count_args); assert_eq!(count_message, "5個のアイテムがあります"); }) @@ -1048,7 +1046,7 @@ invalid-syntax = This is { $missing // Test Arabic with arguments let mut args = FluentArgs::new(); - args.set("name", "أحمد".to_string()); + args.set("name", "أحمد".to_owned()); let welcome = get_message_with_args("welcome", args); assert_eq!(welcome, "أهلاً وسهلاً، أحمد!"); @@ -1160,7 +1158,7 @@ invalid-syntax = This is { $missing // Test that Latin script names are NOT isolated in RTL context // since we disabled Unicode directional isolation let mut args = FluentArgs::new(); - args.set("name".to_string(), "John Smith".to_string()); + args.set("name".to_owned(), "John Smith".to_owned()); let message = get_message_with_args("welcome", args); // The Latin name should NOT be wrapped in directional isolate characters @@ -1209,7 +1207,7 @@ invalid-syntax = This is { $missing #[test] fn test_localization_error_uerror_impl() { - let error = LocalizationError::Bundle("some error".to_string()); + let error = LocalizationError::Bundle("some error".to_owned()); assert_eq!(error.code(), 1); } @@ -1365,7 +1363,7 @@ invalid-syntax = This is { $missing assert!(error_string.contains("I/O error loading")); assert!(error_string.contains("/test/path.ftl")); - let bundle_error = LocalizationError::Bundle("Bundle creation failed".to_string()); + let bundle_error = LocalizationError::Bundle("Bundle creation failed".to_owned()); let bundle_string = format!("{bundle_error}"); assert!(bundle_string.contains("Bundle error: Bundle creation failed")); } diff --git a/tests/by-util/test_b2sum.rs b/tests/by-util/test_b2sum.rs index 2bbc15a8c64..49ba54cb07d 100644 --- a/tests/by-util/test_b2sum.rs +++ b/tests/by-util/test_b2sum.rs @@ -266,7 +266,7 @@ fn test_check_b2sum_strict_check() { at.write("ck", &checksums.join("")); - let output = "f: OK\n".to_string().repeat(checksums.len()); + let output = "f: OK\n".to_owned().repeat(checksums.len()); scene .ccmd("b2sum") diff --git a/tests/by-util/test_chroot.rs b/tests/by-util/test_chroot.rs index adeaf32bf6c..f305b046dc5 100644 --- a/tests/by-util/test_chroot.rs +++ b/tests/by-util/test_chroot.rs @@ -178,7 +178,7 @@ fn test_default_shell() { let dir = "CHROOT_DIR"; at.mkdir(dir); - let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); + let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_owned()); let expected = format!("chroot: failed to run command '{shell}': No such file or directory"); if let Ok(result) = run_ucmd_as_root(&ts, &[dir]) { diff --git a/tests/by-util/test_cksum.rs b/tests/by-util/test_cksum.rs index daa69047f00..05b872faa8e 100644 --- a/tests/by-util/test_cksum.rs +++ b/tests/by-util/test_cksum.rs @@ -2210,7 +2210,7 @@ mod gnu_cksum_base64 { fn output_format(algo: &str, digest: &str) -> String { if ["sysv", "bsd", "crc", "crc32b"].contains(&algo) { - digest.to_string() + digest.to_owned() } else { format!("{} (f) = {digest}", algo.to_uppercase()).replace("BLAKE2B", "BLAKE2b") } diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index f01619af261..0e3f1554dd8 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -2069,7 +2069,7 @@ fn test_cp_no_preserve_mode() { let metadata_b = std::fs::metadata(at.subdir.join("b")).unwrap(); let permission_b = uufs::display_permissions(&metadata_b, false); - assert_eq!(permission_b, "rw-------".to_string()); + assert_eq!(permission_b, "rw-------".to_owned()); } #[test] @@ -3168,7 +3168,7 @@ fn test_cp_fifo() { let metadata = std::fs::metadata(at.subdir.join("fifo2")).unwrap(); let permission = uucore::fs::display_permissions(&metadata, true); - assert_eq!(permission, "prwx-wx--x".to_string()); + assert_eq!(permission, "prwx-wx--x".to_owned()); } #[test] @@ -3189,7 +3189,7 @@ fn test_cp_socket() { let metadata = std::fs::metadata(at.subdir.join("socket2")).unwrap(); let permission = uucore::fs::display_permissions(&metadata, true); assert!(metadata.file_type().is_socket()); - assert_eq!(permission, "srwx-wx--x".to_string()); + assert_eq!(permission, "srwx-wx--x".to_owned()); } #[cfg(all(unix, not(target_vendor = "apple")))] @@ -6744,7 +6744,7 @@ fn test_cp_preserve_selinux_admin_context() { .split_whitespace() .nth(1) .unwrap_or_default() - .to_string(); + .to_owned(); assert!( !default_context.is_empty(), diff --git a/tests/by-util/test_date.rs b/tests/by-util/test_date.rs index 923922f2b04..906be4748ec 100644 --- a/tests/by-util/test_date.rs +++ b/tests/by-util/test_date.rs @@ -1948,7 +1948,7 @@ fn check_date(locale: &str, date: &str, fmt: &str, expected: &str) { .succeeds() .stdout_str() .trim() - .to_string(); + .to_owned(); assert_eq!(actual, expected, "LC_ALL={locale} date -d '{date}' '{fmt}'"); } diff --git a/tests/by-util/test_dd.rs b/tests/by-util/test_dd.rs index 828a1e04311..b7aad29322e 100644 --- a/tests/by-util/test_dd.rs +++ b/tests/by-util/test_dd.rs @@ -1866,9 +1866,9 @@ fn test_oflag_direct_partial_block() { .args(&[ format!("if={}", input_path.display()), format!("of={}", output_path.display()), - "oflag=direct".to_string(), + "oflag=direct".to_owned(), format!("bs={block_size}"), - "status=none".to_string(), + "status=none".to_owned(), ]) .succeeds() .stdout_is("") diff --git a/tests/by-util/test_df.rs b/tests/by-util/test_df.rs index c1cf50d2518..cacfad6fab9 100644 --- a/tests/by-util/test_df.rs +++ b/tests/by-util/test_df.rs @@ -563,7 +563,7 @@ fn test_default_block_size() { .arg("--output=size") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, "1K-blocks"); @@ -572,7 +572,7 @@ fn test_default_block_size() { .env("POSIXLY_CORRECT", "1") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, "512B-blocks"); } @@ -583,12 +583,12 @@ fn test_default_block_size_in_posix_portability_mode() { s.lines() .next() .unwrap() - .to_string() + .to_owned() .split_whitespace() .nth(1) .unwrap() .trim() - .to_string() + .to_owned() } let output = new_ucmd!().arg("-P").succeeds().stdout_str_lossy(); @@ -609,7 +609,7 @@ fn test_block_size_1024() { .args(&["-B", &format!("{block_size}"), "--output=size"]) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } assert_eq!(get_header(1024), "1K-blocks"); @@ -633,7 +633,7 @@ fn test_block_size_with_suffix() { .args(&["-B", block_size, "--output=size"]) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } assert_eq!(get_header("K"), "1K-blocks"); @@ -657,7 +657,7 @@ fn test_df_binary_block_size() { .args(&["-B", block_size, "--output=size"]) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } let test_cases = [ @@ -685,7 +685,7 @@ fn test_df_binary_env_block_size() { .args(&["--output=size"]) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } let binary_header = get_header("DF_BLOCK_SIZE", "0b10000000000"); @@ -708,12 +708,12 @@ fn test_block_size_in_posix_portability_mode() { .lines() .next() .unwrap() - .to_string() + .to_owned() .split_whitespace() .nth(1) .unwrap() .trim() - .to_string() + .to_owned() } assert_eq!(get_header("1024"), "1024-blocks"); @@ -731,7 +731,7 @@ fn test_block_size_from_env() { .env(env_var, env_value) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } assert_eq!(get_header("DF_BLOCK_SIZE", "111"), "111B-blocks"); @@ -747,7 +747,7 @@ fn test_block_size_from_env_zero() { .env(env_var, env_value) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } let default_block_size_header = "1K-blocks"; @@ -768,7 +768,7 @@ fn test_block_size_from_env_precedences() { .env(k2, v2) .succeeds() .stdout_str_lossy(); - output.lines().next().unwrap().trim().to_string() + output.lines().next().unwrap().trim().to_owned() } let df_block_size = ("DF_BLOCK_SIZE", "111"); @@ -787,7 +787,7 @@ fn test_precedence_of_block_size_arg_over_env() { .env("DF_BLOCK_SIZE", "111") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, "999B-blocks"); } @@ -801,7 +801,7 @@ fn test_invalid_block_size_from_env() { .env("DF_BLOCK_SIZE", "invalid") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, default_block_size_header); @@ -811,7 +811,7 @@ fn test_invalid_block_size_from_env() { .env("BLOCK_SIZE", "222") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, default_block_size_header); @@ -821,7 +821,7 @@ fn test_invalid_block_size_from_env() { .env("BLOCK_SIZE", "222") .succeeds() .stdout_str_lossy(); - let header = output.lines().next().unwrap().trim().to_string(); + let header = output.lines().next().unwrap().trim().to_owned(); assert_eq!(header, default_block_size_header); } @@ -841,12 +841,12 @@ fn test_ignore_block_size_from_env_in_posix_portability_mode() { .lines() .next() .unwrap() - .to_string() + .to_owned() .split_whitespace() .nth(1) .unwrap() .trim() - .to_string(); + .to_owned(); assert_eq!(header, default_block_size_header); } diff --git a/tests/by-util/test_env.rs b/tests/by-util/test_env.rs index 8c488e9f3c1..25ba5e2b866 100644 --- a/tests/by-util/test_env.rs +++ b/tests/by-util/test_env.rs @@ -589,7 +589,7 @@ fn test_gnu_e20() { String::from(r#"-SA="B\_C=D" "#) + env_bin.escape_default().to_string().as_str() + "", ]; - let mut output = "A=B C=D\n".to_string(); + let mut output = "A=B C=D\n".to_owned(); // Workaround for the test to pass when coverage is being run. // If enabled, the binary called by env_bin will most probably be diff --git a/tests/by-util/test_expr.rs b/tests/by-util/test_expr.rs index ec1cf91598f..7029a126656 100644 --- a/tests/by-util/test_expr.rs +++ b/tests/by-util/test_expr.rs @@ -607,7 +607,7 @@ fn test_long_input() { #[cfg(windows)] const RESULT: &str = "845650\n"; - let mut args: Vec = vec!["1".to_string()]; + let mut args: Vec = vec!["1".to_owned()]; for i in 2..=MAX_NUMBER { args.push('+'.to_string()); diff --git a/tests/by-util/test_id.rs b/tests/by-util/test_id.rs index ec96e3c23e8..0a4b122ca02 100644 --- a/tests/by-util/test_id.rs +++ b/tests/by-util/test_id.rs @@ -32,7 +32,7 @@ fn test_id_no_specified_user() { let ts = TestScenario::new(util_name!()); let result = ts.ucmd().run(); let exp_result = unwrap_or_return!(expected_result(&ts, &[])); - let mut exp_stdout = exp_result.stdout_str().to_string(); + let mut exp_stdout = exp_result.stdout_str().to_owned(); #[cfg(not(feature = "feat_selinux"))] { diff --git a/tests/by-util/test_install.rs b/tests/by-util/test_install.rs index 32cdbee8ca0..f65308ae0c7 100644 --- a/tests/by-util/test_install.rs +++ b/tests/by-util/test_install.rs @@ -1941,8 +1941,9 @@ fn test_install_compare_group_ownership() { .arg("-nrg") .output() .map_or_else( - |_| "users".to_string(), - |output| String::from_utf8_lossy(&output.stdout).trim().to_string(), + |_| "users".to_owned(), + |output| + String::from_utf8_lossy(&output.stdout).trim().to_owned(), ); // fallback group name // Install with explicit group diff --git a/tests/by-util/test_ls.rs b/tests/by-util/test_ls.rs index 41b72af6b04..f0dabd1d3a5 100644 --- a/tests/by-util/test_ls.rs +++ b/tests/by-util/test_ls.rs @@ -1334,7 +1334,7 @@ fn test_ls_long_symlink_color() { .last() .unwrap(); // `target` is whatever comes after the arrow. - let target = s.split(" -> ").last().unwrap().to_string(); + let target = s.split(" -> ").last().unwrap().to_owned(); Some((c, name, target)) } None => None, @@ -1374,14 +1374,14 @@ fn test_ls_long_symlink_color() { let colored_name = Regex::new(r"(?:\x1b\[0m\x1b)?\[([0-9;]+)m(.+)\x1b\[0m").unwrap(); match colored_name.captures(input) { Some(captures) => { - dbg!(captures.get(1).unwrap().as_str().to_string()); - dbg!(captures.get(2).unwrap().as_str().to_string()); + dbg!(captures.get(1).unwrap().as_str().to_owned()); + dbg!(captures.get(2).unwrap().as_str().to_owned()); ( - captures.get(1).unwrap().as_str().to_string(), - captures.get(2).unwrap().as_str().to_string(), + captures.get(1).unwrap().as_str().to_owned(), + captures.get(2).unwrap().as_str().to_owned(), ) } - None => (String::new(), input.to_string()), + None => (String::new(), input.to_owned()), } } @@ -1493,7 +1493,7 @@ fn test_ls_dangling_symlink_or_and_missing_colors() { .arg("dangling") .succeeds() .stdout_str() - .to_string(); + .to_owned(); let color_regex = Regex::new( r"\x1b\[0m\x1b\[(?P[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P[0-9;]*)m", @@ -1523,7 +1523,7 @@ fn test_ls_dangling_symlink_ln_or_priority() { .arg("dangling") .succeeds() .stdout_str() - .to_string(); + .to_owned(); let color_regex = Regex::new( r"\x1b\[0m\x1b\[(?P[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P[0-9;]*)m", @@ -1552,7 +1552,7 @@ fn test_ls_dangling_symlink_ln_and_missing_colors() { .arg("dangling") .succeeds() .stdout_str() - .to_string(); + .to_owned(); let color_regex = Regex::new( r"\x1b\[0m\x1b\[(?P[0-9;]*)mdangling\x1b\[0m -> \x1b\[(?P[0-9;]*)m", @@ -1579,7 +1579,7 @@ fn test_ls_dangling_symlink_blank_or_still_emits_reset() { .arg("dangling") .succeeds() .stdout_str() - .to_string(); + .to_owned(); assert!( stdout.contains("\u{1b}[0m\u{1b}[mdangling\u{1b}[0m"), @@ -1602,7 +1602,7 @@ fn test_ls_dangling_symlink_blank_or_in_directory_listing() { .arg("dir") .succeeds() .stdout_str() - .to_string(); + .to_owned(); assert!( stdout.contains("\u{1b}[0m\u{1b}[mentry\u{1b}[0m"), @@ -1624,7 +1624,7 @@ fn test_ls_dangling_symlink_uses_ln_when_or_blank() { .arg("dangling") .succeeds() .stdout_str() - .to_string(); + .to_owned(); assert!( stdout.contains("\u{1b}[0m\u{1b}[1;36mdangling\u{1b}[0m"), @@ -1647,7 +1647,7 @@ fn test_ls_directory_dangling_symlink_uses_ln_when_or_blank() { .arg("dir") .succeeds() .stdout_str() - .to_string(); + .to_owned(); assert!( stdout.contains("\u{1b}[0m\u{1b}[1;36mentry\u{1b}[0m"), @@ -5259,7 +5259,7 @@ fn test_ls_dired_recursive_multiple() { let result = cmd.succeeds(); - let output = result.stdout_str().to_string(); + let output = result.stdout_str().to_owned(); println!("Output:\n{output}"); let dired_line = output @@ -5282,7 +5282,7 @@ fn test_ls_dired_recursive_multiple() { let filename = String::from_utf8(output.as_bytes()[start_pos..=end_pos].to_vec()) .unwrap() .trim() - .to_string(); + .to_owned(); println!("Extracted filename: {filename}"); filename }) @@ -5357,7 +5357,7 @@ fn test_ls_dired_complex() { result.stdout_contains(" total 4"); } - let output = result.stdout_str().to_string(); + let output = result.stdout_str().to_owned(); println!("Output:\n{output}"); let dired_line = output @@ -5381,7 +5381,7 @@ fn test_ls_dired_complex() { let filename = String::from_utf8(output.as_bytes()[start_pos..=end_pos].to_vec()) .unwrap() .trim() - .to_string(); + .to_owned(); println!("Extracted filename: {filename}"); filename }) @@ -5408,7 +5408,7 @@ fn test_ls_subdired_complex() { cmd.arg("--dired").arg("-l").arg("-R").arg("dir1"); let result = cmd.succeeds(); - let output = result.stdout_str().to_string(); + let output = result.stdout_str().to_owned(); println!("Output:\n{output}"); let dired_line = output diff --git a/tests/by-util/test_mkfifo.rs b/tests/by-util/test_mkfifo.rs index 4d19da636a2..5f22d6aee5e 100644 --- a/tests/by-util/test_mkfifo.rs +++ b/tests/by-util/test_mkfifo.rs @@ -100,7 +100,7 @@ fn test_create_fifo_with_mode_and_umask() { let metadata = std::fs::metadata(at.subdir.join(format!("fifo_test_{mode}"))).unwrap(); let permissions = display_permissions(&metadata, true); - assert_eq!(permissions, expected.to_string()); + assert_eq!(permissions, expected.to_owned()); }; test_fifo_creation("734", 0o077, "prwx-wxr--"); // spell-checker:disable-line @@ -134,7 +134,7 @@ fn test_create_fifo_with_umask() { let metadata = std::fs::metadata(at.subdir.join("fifo_test")).unwrap(); let permissions = display_permissions(&metadata, true); - assert_eq!(permissions, expected.to_string()); + assert_eq!(permissions, expected.to_owned()); at.remove("fifo_test"); }; @@ -237,5 +237,5 @@ fn test_mkfifo_permission_unchanged_when_failed() { let metadata = std::fs::metadata(at.subdir.join(file_name)).unwrap(); let permissions = display_permissions(&metadata, true); let expected = "-rw-------"; - assert_eq!(permissions, expected.to_string()); + assert_eq!(permissions, expected.to_owned()); } diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index 44d3b6a057f..d049e9c680a 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -1006,8 +1006,8 @@ fn test_format_with_precision_and_to_arg() { new_ucmd!() .args(&[ format!("--format={format}"), - "9991239123".to_string(), - "--to=si".to_string(), + "9991239123".to_owned(), + "--to=si".to_owned(), ]) .succeeds() .stdout_is(format!("{expected}\n")); diff --git a/tests/by-util/test_od.rs b/tests/by-util/test_od.rs index 21cef8404ea..6b7383eab40 100644 --- a/tests/by-util/test_od.rs +++ b/tests/by-util/test_od.rs @@ -24,7 +24,7 @@ static ALPHA_OUT: &str = " fn erange_message() -> String { let err = std::io::Error::from_raw_os_error(libc::ERANGE); let msg = err.to_string(); - msg.split(" (os error").next().unwrap_or(&msg).to_string() + msg.split(" (os error").next().unwrap_or(&msg).to_owned() } fn run_skip_across_inputs(files: &[(&str, &str)], skip: u64, expected: &str) { diff --git a/tests/by-util/test_pinky.rs b/tests/by-util/test_pinky.rs index 98eefc7818a..93e882757ce 100644 --- a/tests/by-util/test_pinky.rs +++ b/tests/by-util/test_pinky.rs @@ -117,7 +117,7 @@ fn test_lookup() { } true }) - .map(|(_, s)| (*s).to_string()) + .map(|(_, s)| (*s).to_owned()) .collect() } let v_actual_filtered = filter_idle_times(&v_actual); diff --git a/tests/by-util/test_pr.rs b/tests/by-util/test_pr.rs index 9c8c4264eb0..30cd7bcda23 100644 --- a/tests/by-util/test_pr.rs +++ b/tests/by-util/test_pr.rs @@ -41,7 +41,7 @@ fn all_minutes(from: Timestamp, to: Timestamp) -> Vec { fn valid_last_modified_template_vars(from: Timestamp) -> Vec> { all_minutes(from, Timestamp::now()) .into_iter() - .map(|time| vec![("{last_modified_time}".to_string(), time)]) + .map(|time| vec![("{last_modified_time}".to_owned(), time)]) .collect() } diff --git a/tests/by-util/test_rm.rs b/tests/by-util/test_rm.rs index c303a4bab66..539b9163c45 100644 --- a/tests/by-util/test_rm.rs +++ b/tests/by-util/test_rm.rs @@ -587,7 +587,7 @@ fn test_prompts() { let mut trimmed_output = Vec::new(); for string in result.stderr_str().split("rm: ") { if !string.is_empty() { - let trimmed_string = format!("rm: {string}").trim().to_string(); + let trimmed_string = format!("rm: {string}").trim().to_owned(); trimmed_output.push(trimmed_string); } } diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 42cbcff5ad4..660f93f26d1 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -1712,7 +1712,7 @@ fn test_human_numeric_blank_thousands_sep_locale() { if sep.is_empty() || sep.len() != 1 || !sep.chars().all(|c| c.is_whitespace()) { return None; } - Some(sep.to_string()) + Some(sep.to_owned()) } let candidates = ["sv_SE.UTF-8", "sv_SE"]; @@ -1720,7 +1720,7 @@ fn test_human_numeric_blank_thousands_sep_locale() { let mut thousands_sep = None; for candidate in candidates { if let Some(sep) = thousands_sep_for(candidate) { - selected_locale = Some(candidate.to_string()); + selected_locale = Some(candidate.to_owned()); thousands_sep = Some(sep); break; } @@ -2163,9 +2163,9 @@ fn test_debug_key_annotations_locale() { .lines() .map(|line| { if line.starts_with("^^ ") { - "^ no match for key".to_string() + "^ no match for key".to_owned() } else { - line.to_string() + line.to_owned() } }) .collect::>() diff --git a/tests/by-util/test_stdbuf.rs b/tests/by-util/test_stdbuf.rs index 00e117f47e4..ca656d768d0 100644 --- a/tests/by-util/test_stdbuf.rs +++ b/tests/by-util/test_stdbuf.rs @@ -321,7 +321,7 @@ fn test_stdbuf_no_fork_regression() { // Wait for exec to complete (process name changes from original binary to target) // Handle both multicall binary (coreutils) and individual utilities (stdbuf) if !name.contains("coreutils") && !name.contains("stdbuf") && !name.is_empty() { - break name.to_string(); + break name.to_owned(); } } diff --git a/tests/by-util/test_stty.rs b/tests/by-util/test_stty.rs index 79f9c12839b..e2af492062b 100644 --- a/tests/by-util/test_stty.rs +++ b/tests/by-util/test_stty.rs @@ -1272,8 +1272,8 @@ fn test_saved_state_invalid_formats() { // Cannot test single value since it would be interpreted as baud rate let invalid_states = vec![ - "500:5:4bf".to_string(), // fewer than expected parts - "500:5:4bf:8a3b".to_string(), // only 4 parts + "500:5:4bf".to_owned(), // fewer than expected parts + "500:5:4bf:8a3b".to_owned(), // only 4 parts format!("500:5:{}:8a3b:{}", cc_zeros, "extra"), // too many parts format!("500::4bf:8a3b:{}", cc_zeros), // empty hex value in flags format!("500:5:4bf:8a3b:{}", cc_with_empty), // empty hex value in cc @@ -1605,7 +1605,7 @@ fn test_stty_uses_stdin() { .succeeds() .stdout_str() .trim() - .to_string(); + .to_owned(); assert!(saved.contains(':'), "Expected colon-separated saved state"); let stdin = File::open(&path).unwrap(); diff --git a/tests/by-util/test_wc.rs b/tests/by-util/test_wc.rs index d62c1da6e8e..c636fbbc78d 100644 --- a/tests/by-util/test_wc.rs +++ b/tests/by-util/test_wc.rs @@ -845,7 +845,7 @@ fn test_simd_respects_glibc_tunables() { .env("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2,-AVX512F") .succeeds() .stderr_str() - .to_string(); + .to_owned(); assert!( !debug_output.contains("using hardware support"), "SIMD should be reported as disabled when GLIBC_TUNABLES blocks AVX features: {debug_output}" @@ -871,7 +871,7 @@ fn test_simd_respects_glibc_tunables() { .succeeds() .stdout_str() .trim() - .to_string(); + .to_owned(); let no_avx512 = new_ucmd!() .arg("-l") @@ -880,7 +880,7 @@ fn test_simd_respects_glibc_tunables() { .succeeds() .stdout_str() .trim() - .to_string(); + .to_owned(); let no_avx2_avx512 = new_ucmd!() .arg("-l") @@ -889,7 +889,7 @@ fn test_simd_respects_glibc_tunables() { .succeeds() .stdout_str() .trim() - .to_string(); + .to_owned(); assert_eq!( base, no_avx512, diff --git a/tests/test_util_name.rs b/tests/test_util_name.rs index 745e6814b76..18349ef2b17 100644 --- a/tests/test_util_name.rs +++ b/tests/test_util_name.rs @@ -45,7 +45,7 @@ fn execution_phrase_double() { assert!( String::from_utf8(output.stderr) .unwrap() - .contains(&"Usage: ls".to_string()) + .contains(&"Usage: ls".to_owned()) ); } diff --git a/tests/test_uudoc.rs b/tests/test_uudoc.rs index b4f12c0999e..fafce7098be 100644 --- a/tests/test_uudoc.rs +++ b/tests/test_uudoc.rs @@ -56,7 +56,7 @@ fn get_doc_file_from_output(output: &str) -> (String, String) { .unwrap() .strip_suffix("'") .unwrap() - .to_string(); + .to_owned(); let content = std::fs::read_to_string(&correct_path_test); let content = match content { Ok(content) => content, diff --git a/tests/uutests/src/lib/util.rs b/tests/uutests/src/lib/util.rs index eaa9c868d03..ef08dde8623 100644 --- a/tests/uutests/src/lib/util.rs +++ b/tests/uutests/src/lib/util.rs @@ -314,7 +314,7 @@ impl CmdResult { panic!( "Expected process to be terminated by the '{value}' signal, but exit status is: '{}'", self.try_exit_status() - .map_or("Not available".to_string(), |e| e.to_string()) + .map_or("Not available".to_owned(), |e| e.to_string()) ) }); @@ -344,7 +344,7 @@ impl CmdResult { panic!( "Expected process to be terminated by the '{name}' signal, but exit status is: '{}'", self.try_exit_status() - .map_or("Not available".to_string(), |e| e.to_string()) + .map_or("Not available".to_owned(), |e| e.to_string()) ) }); @@ -1406,7 +1406,7 @@ impl TestScenario { #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] pub fn mount_temp_fs(&mut self, mount_point: &str) -> core::result::Result<(), String> { if self.tmp_fs_mountpoint.is_some() { - return Err("already mounted".to_string()); + return Err("already mounted".to_owned()); } let cmd_result = self .cmd("mount") @@ -1420,7 +1420,7 @@ impl TestScenario { if !cmd_result.succeeded() { return Err(format!("mount failed: {}", cmd_result.stderr_str())); } - self.tmp_fs_mountpoint = Some(mount_point.to_string()); + self.tmp_fs_mountpoint = Some(mount_point.to_owned()); Ok(()) } @@ -1917,7 +1917,7 @@ impl UCommand { captured_stdout = Self::spawn_reader_thread( captured_stdout, po_master, - "stdout_reader".to_string(), + "stdout_reader".to_owned(), ); command.stdout(po_slave); } @@ -1930,7 +1930,7 @@ impl UCommand { captured_stderr = Self::spawn_reader_thread( captured_stderr, pe_master, - "stderr_reader".to_string(), + "stderr_reader".to_owned(), ); command.stderr(pe_slave); } @@ -2513,7 +2513,7 @@ impl UChild { let (sender, receiver) = mpsc::channel(); let handle = thread::Builder::new() - .name("wait_with_output".to_string()) + .name("wait_with_output".to_owned()) .spawn(move || sender.send(child.wait_with_output())) .unwrap(); @@ -2766,7 +2766,7 @@ impl UChild { let mut writer = self.take_stdin_as_writer(); let join_handle = thread::Builder::new() - .name("pipe_in".to_string()) + .name("pipe_in".to_owned()) .spawn( move || match writer.write_all(&content).and_then(|()| writer.flush()) { Err(error) if !ignore_stdin_write_error => Err(io::Error::other(format!( @@ -2882,7 +2882,7 @@ pub fn whoami() -> String { .or_else(|_| env::var("USERNAME")) .unwrap_or_else(|e| { println!("{UUTILS_WARNING}: {e}, using \"nobody\" instead"); - "nobody".to_string() + "nobody".to_owned() }) } @@ -3054,7 +3054,7 @@ pub fn gnu_cmd_result( let (stdout, stderr): (String, String) = if cfg!(target_os = "linux") { ( - result.stdout_str().to_string(), + result.stdout_str().to_owned(), result.stderr_str_lossy().to_string(), ) } else { @@ -3068,7 +3068,7 @@ pub fn gnu_cmd_result( }; Ok(CmdResult::new( - ts.bin_path.as_os_str().to_str().unwrap().to_string(), + ts.bin_path.as_os_str().to_str().unwrap().to_owned(), Some(ts.util_name.clone()), Some(result.tmpd()), result.exit_status, @@ -3174,9 +3174,9 @@ pub fn run_ucmd_as_root_with_stdin_stdout( Ok(output) if String::from_utf8_lossy(&output.stderr).eq("sudo: a password is required\n") => { - Err("Cannot run non-interactive sudo".to_string()) + Err("Cannot run non-interactive sudo".to_owned()) } - Ok(_output) => Err("\"sudo whoami\" didn't return \"root\"".to_string()), + Ok(_output) => Err("\"sudo whoami\" didn't return \"root\"".to_owned()), Err(e) => Err(format!("{UUTILS_WARNING}: {e}")), } } @@ -3446,7 +3446,7 @@ mod tests { check_coreutil_version("no test name", VERSION_MIN), Err("uutils-tests-warning: 'no test name' \ No such file or directory (os error 2)" - .to_string()) + .to_owned()) ); } From ad8db27d6996881559a61bafb88b3e52fc30d042 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 5 Feb 2026 17:05:41 +0000 Subject: [PATCH 2/3] fmt --- fuzz/uufuzz/src/lib.rs | 6 ++++-- src/uu/ls/src/ls.rs | 5 +---- src/uu/numfmt/benches/numfmt_bench.rs | 3 +-- src/uu/pr/src/pr.rs | 6 ++++-- src/uu/rm/benches/rm_bench.rs | 9 ++++++--- src/uucore/src/lib/features/parser/num_parser.rs | 5 +---- src/uucore/src/lib/mods/locale.rs | 6 ++++-- tests/by-util/test_install.rs | 3 +-- 8 files changed, 22 insertions(+), 21 deletions(-) diff --git a/fuzz/uufuzz/src/lib.rs b/fuzz/uufuzz/src/lib.rs index 4af9b1c23ad..300f372f281 100644 --- a/fuzz/uufuzz/src/lib.rs +++ b/fuzz/uufuzz/src/lib.rs @@ -183,7 +183,8 @@ where .split_once(':') .map(|x| x.1) .unwrap_or("") - .trim().to_owned(), + .trim() + .to_owned(), exit_code: uumain_exit_status, } } @@ -283,7 +284,8 @@ pub fn run_gnu_cmd( .split_once(':') .map(|x| x.1) .unwrap_or("") - .trim().to_owned(); + .trim() + .to_owned(); if output.status.success() || !check_gnu { Ok(CommandResult { diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index 1bc530aec78..e36bd430011 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -299,10 +299,7 @@ fn parse_time_style(options: &clap::ArgMatches) -> Result<(String, Option ok((format::FULL_ISO, None)), "long-iso" => ok((format::LONG_ISO, None)), // ISO older format needs extra padding. - "iso" => Ok(( - "%m-%d %H:%M".to_owned(), - Some(format::ISO.to_owned() + " "), - )), + "iso" => Ok(("%m-%d %H:%M".to_owned(), Some(format::ISO.to_owned() + " "))), "locale" => ok(LOCALE_FORMAT), _ => match field.chars().next().unwrap() { '+' => { diff --git a/src/uu/numfmt/benches/numfmt_bench.rs b/src/uu/numfmt/benches/numfmt_bench.rs index 59b56ef06a3..8da4c5faebd 100644 --- a/src/uu/numfmt/benches/numfmt_bench.rs +++ b/src/uu/numfmt/benches/numfmt_bench.rs @@ -115,8 +115,7 @@ fn numfmt_round_modes(bencher: Bencher, (round_mode, count): (&str, usize)) { bencher .with_inputs(|| { let numbers: Vec = (1..=count).map(|n| n.to_string()).collect(); - let mut args: Vec = - vec!["--to=si".to_owned(), format!("--round={round_mode}")]; + let mut args: Vec = vec!["--to=si".to_owned(), format!("--round={round_mode}")]; args.extend(numbers); args }) diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 5990a4c98cb..b4f55c3c63c 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -443,7 +443,8 @@ fn get_date_format(matches: &ArgMatches) -> String { format::LONG_ISO } } - }.to_owned() + } + .to_owned() } #[allow(clippy::cognitive_complexity)] @@ -483,7 +484,8 @@ fn build_options( paths[0] }, |s| s.as_str(), - ).to_owned(); + ) + .to_owned(); let default_first_number = NumberingMode::default().first_number; let first_number = diff --git a/src/uu/rm/benches/rm_bench.rs b/src/uu/rm/benches/rm_bench.rs index 3db347e38a9..22bff5f1fe8 100644 --- a/src/uu/rm/benches/rm_bench.rs +++ b/src/uu/rm/benches/rm_bench.rs @@ -21,7 +21,8 @@ fn rm_single_file(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap().to_owned() + .unwrap() + .to_owned() }) .collect(); (temp_dir, paths) @@ -47,7 +48,8 @@ fn rm_multiple_files(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap().to_owned() + .unwrap() + .to_owned() }) .collect(); (temp_dir, paths) @@ -90,7 +92,8 @@ fn rm_force_files(bencher: Bencher) { .path() .join(format!("f{i}")) .to_str() - .unwrap().to_owned() + .unwrap() + .to_owned() }) .collect(); (temp_dir, paths) diff --git a/src/uucore/src/lib/features/parser/num_parser.rs b/src/uucore/src/lib/features/parser/num_parser.rs index 4d13f0f6f6e..4eacdb16ee9 100644 --- a/src/uucore/src/lib/features/parser/num_parser.rs +++ b/src/uucore/src/lib/features/parser/num_parser.rs @@ -1123,10 +1123,7 @@ mod tests { ); assert_eq!( f64::extended_parse("0b100.1"), - Err(ExtendedParserError::PartialMatch( - 0f64, - "b100.1".to_owned() - )) + Err(ExtendedParserError::PartialMatch(0f64, "b100.1".to_owned())) ); assert_eq!( diff --git a/src/uucore/src/lib/mods/locale.rs b/src/uucore/src/lib/mods/locale.rs index 163ed7f2a70..43a0440e13a 100644 --- a/src/uucore/src/lib/mods/locale.rs +++ b/src/uucore/src/lib/mods/locale.rs @@ -227,7 +227,8 @@ fn parse_fluent_resource(content: &str) -> Result Result { .unwrap_or_else(|_| DEFAULT_LOCALE.to_owned()) .split('.') .next() - .unwrap_or(DEFAULT_LOCALE).to_owned(); + .unwrap_or(DEFAULT_LOCALE) + .to_owned(); LanguageIdentifier::from_str(&locale_str).map_err(|_| { LocalizationError::ParseLocale(format!("Failed to parse locale: {locale_str}")) }) diff --git a/tests/by-util/test_install.rs b/tests/by-util/test_install.rs index f65308ae0c7..6b6f70ae2ec 100644 --- a/tests/by-util/test_install.rs +++ b/tests/by-util/test_install.rs @@ -1942,8 +1942,7 @@ fn test_install_compare_group_ownership() { .output() .map_or_else( |_| "users".to_owned(), - |output| - String::from_utf8_lossy(&output.stdout).trim().to_owned(), + |output| String::from_utf8_lossy(&output.stdout).trim().to_owned(), ); // fallback group name // Install with explicit group From 904a96bc4b2ac371c5638c718edcde3ebafc8945 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 5 Feb 2026 18:29:04 +0000 Subject: [PATCH 3/3] fixup --- src/uu/chgrp/src/chgrp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/uu/chgrp/src/chgrp.rs b/src/uu/chgrp/src/chgrp.rs index 357bdc7112e..e4689082702 100644 --- a/src/uu/chgrp/src/chgrp.rs +++ b/src/uu/chgrp/src/chgrp.rs @@ -53,7 +53,7 @@ fn get_dest_gid(matches: &ArgMatches) -> UResult<(Option, String)> { .get_one::(options::ARG_GROUP) .map(|s| s.as_str()) .unwrap_or_default(); - raw_group = group.to_owned(); + group.clone_into(&mut raw_group); if group.is_empty() { None } else {