diff --git a/Cargo.toml b/Cargo.toml index 8cdfc04167d..163a1e53e3c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -664,7 +664,6 @@ match_same_arms = "allow" # 204 redundant_closure_for_method_calls = "allow" # 125 cast_possible_truncation = "allow" # 122 too_many_lines = "allow" # 101 -trivially_copy_pass_by_ref = "allow" # 84 cast_possible_wrap = "allow" # 78 cast_sign_loss = "allow" # 70 struct_excessive_bools = "allow" # 68 diff --git a/src/uu/comm/src/comm.rs b/src/uu/comm/src/comm.rs index be77debc052..c72bbcc8a2e 100644 --- a/src/uu/comm/src/comm.rs +++ b/src/uu/comm/src/comm.rs @@ -40,7 +40,7 @@ enum FileNumber { } impl FileNumber { - fn as_str(&self) -> &'static str { + fn as_str(self) -> &'static str { match self { Self::One => "1", Self::Two => "2", diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 4f093bda1ad..17931d73112 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -1360,7 +1360,7 @@ fn show_error_if_needed(error: &CpError) { /// Behavior is determined by the `options` parameter, see [`Options`] for details. pub fn copy(sources: &[PathBuf], target: &Path, options: &Options) -> CopyResult<()> { let target_type = TargetType::determine(sources, target); - verify_target_type(target, &target_type)?; + verify_target_type(target, target_type)?; let mut non_fatal_errors = false; let mut seen_sources = HashSet::with_capacity(sources.len()); @@ -1614,8 +1614,8 @@ fn file_mode_for_interactive_overwrite( } impl OverwriteMode { - fn verify(&self, path: &Path, debug: bool) -> CopyResult<()> { - match *self { + fn verify(self, path: &Path, debug: bool) -> CopyResult<()> { + match self { Self::NoClobber => { if debug { println!("{}", translate!("cp-debug-skipped", "path" => path.quote())); @@ -1652,12 +1652,12 @@ impl OverwriteMode { /// Note: ENOTSUP/EOPNOTSUPP errors are silently ignored when not required, as per GNU cp /// documentation: "Try to preserve SELinux security context and extended attributes (xattr), /// but ignore any failure to do that and print no corresponding diagnostic." -fn handle_preserve CopyResult<()>>(p: &Preserve, f: F) -> CopyResult<()> { +fn handle_preserve CopyResult<()>>(p: Preserve, f: F) -> CopyResult<()> { match p { Preserve::No { .. } => {} Preserve::Yes { required } => { let result = f(); - if *required { + if required { result?; } else if let Err(ref error) = result { // Suppress ENOTSUP errors when preservation is optional. @@ -1724,7 +1724,7 @@ pub(crate) fn copy_attributes( // Ownership must be changed first to avoid interfering with mode change. #[cfg(unix)] - handle_preserve(&attributes.ownership, || -> CopyResult<()> { + handle_preserve(attributes.ownership, || -> CopyResult<()> { use std::os::unix::prelude::MetadataExt; use uucore::perms::Verbosity; use uucore::perms::VerbosityLevel; @@ -1759,7 +1759,7 @@ pub(crate) fn copy_attributes( Ok(()) })?; - handle_preserve(&attributes.mode, || -> CopyResult<()> { + handle_preserve(attributes.mode, || -> CopyResult<()> { // The `chmod()` system call that underlies the // `fs::set_permissions()` call is unable to change the // permissions of a symbolic link. In that case, we just @@ -1778,7 +1778,7 @@ pub(crate) fn copy_attributes( Ok(()) })?; - handle_preserve(&attributes.timestamps, || -> CopyResult<()> { + handle_preserve(attributes.timestamps, || -> CopyResult<()> { let atime = FileTime::from_last_access_time(&source_metadata); let mtime = FileTime::from_last_modification_time(&source_metadata); if dest.is_symlink() { @@ -1791,7 +1791,7 @@ pub(crate) fn copy_attributes( })?; #[cfg(all(feature = "selinux", any(target_os = "linux", target_os = "android")))] - handle_preserve(&attributes.context, || -> CopyResult<()> { + handle_preserve(attributes.context, || -> CopyResult<()> { // Get the source context and apply it to the destination if let Ok(context) = selinux::SecurityContext::of_path(source, false, false) { if let Some(context) = context { @@ -1809,7 +1809,7 @@ pub(crate) fn copy_attributes( Ok(()) })?; - handle_preserve(&attributes.xattr, || -> CopyResult<()> { + handle_preserve(attributes.xattr, || -> CopyResult<()> { #[cfg(all(unix, not(target_os = "android")))] { copy_extended_attrs(source, dest)?; @@ -2767,11 +2767,11 @@ fn copy_link( } /// Generate an error message if `target` is not the correct `target_type` -pub fn verify_target_type(target: &Path, target_type: &TargetType) -> CopyResult<()> { +pub fn verify_target_type(target: &Path, target_type: TargetType) -> CopyResult<()> { match (target_type, target.is_dir()) { - (&TargetType::Directory, false) => Err(translate!("cp-error-target-not-directory", "target" => target.quote()) + (TargetType::Directory, false) => Err(translate!("cp-error-target-not-directory", "target" => target.quote()) .into()), - (&TargetType::File, true) => Err(translate!("cp-error-cannot-overwrite-directory-with-non-directory", "dir" => target.quote()) + (TargetType::File, true) => Err(translate!("cp-error-cannot-overwrite-directory-with-non-directory", "dir" => target.quote()) .into()), _ => Ok(()), } diff --git a/src/uu/dd/src/numbers.rs b/src/uu/dd/src/numbers.rs index 206cd788750..f718052015c 100644 --- a/src/uu/dd/src/numbers.rs +++ b/src/uu/dd/src/numbers.rs @@ -45,7 +45,7 @@ pub(crate) enum SuffixType { } impl SuffixType { - fn base_and_suffix(&self, n: u128) -> (u128, &'static str) { + fn base_and_suffix(self, n: u128) -> (u128, &'static str) { let (bases, suffixes) = match self { Self::Iec => (IEC_BASES, IEC_SUFFIXES), Self::Si => (SI_BASES, SI_SUFFIXES), diff --git a/src/uu/df/src/blocks.rs b/src/uu/df/src/blocks.rs index ded8b591265..328090ffded 100644 --- a/src/uu/df/src/blocks.rs +++ b/src/uu/df/src/blocks.rs @@ -51,7 +51,7 @@ pub(crate) enum SuffixType { impl SuffixType { /// The first ten powers of 1024 and 1000, respectively. - fn bases(&self) -> [u128; 10] { + fn bases(self) -> [u128; 10] { match self { Self::Iec | Self::HumanReadable(HumanReadable::Binary) => IEC_BASES, Self::Si | Self::HumanReadable(HumanReadable::Decimal) => SI_BASES, @@ -59,7 +59,7 @@ impl SuffixType { } /// Suffixes for the first nine multi-byte unit suffixes. - fn suffixes(&self) -> [&'static str; 9] { + fn suffixes(self) -> [&'static str; 9] { match self { // we use "kB" instead of "KB", same as GNU df Self::Si => ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], diff --git a/src/uu/df/src/columns.rs b/src/uu/df/src/columns.rs index 0d2d121a3d1..0fcd20865d5 100644 --- a/src/uu/df/src/columns.rs +++ b/src/uu/df/src/columns.rs @@ -191,16 +191,16 @@ impl Column { } /// Return the alignment of the specified column. - pub(crate) fn alignment(column: &Self) -> Alignment { - match column { + pub(crate) fn alignment(self) -> Alignment { + match self { Self::Source | Self::Target | Self::File | Self::Fstype => Alignment::Left, _ => Alignment::Right, } } /// Return the minimum width of the specified column. - pub(crate) fn min_width(column: &Self) -> usize { - match column { + pub(crate) fn min_width(self) -> usize { + match self { // 14 = length of "Filesystem" plus 4 spaces Self::Source => 14, Self::Used => 5, diff --git a/src/uu/df/src/table.rs b/src/uu/df/src/table.rs index f4d83c3aa03..d4cf1ddfd17 100644 --- a/src/uu/df/src/table.rs +++ b/src/uu/df/src/table.rs @@ -474,7 +474,7 @@ impl Table { .columns .iter() .enumerate() - .map(|(i, col)| Column::min_width(col).max(headers[i].len())) + .map(|(i, col)| col.min_width().max(headers[i].len())) .collect(); let mut rows = vec![headers.iter().map(Cell::from_string).collect()]; @@ -527,7 +527,7 @@ impl Table { let mut alignments = Vec::new(); for column in columns { - alignments.push(Column::alignment(column)); + alignments.push(column.alignment()); } alignments diff --git a/src/uu/env/src/env.rs b/src/uu/env/src/env.rs index c9396a4b899..5e56fbd0413 100644 --- a/src/uu/env/src/env.rs +++ b/src/uu/env/src/env.rs @@ -118,7 +118,7 @@ struct Options<'a> { fn parse_name_value_opt<'a>(opts: &mut Options<'a>, opt: &'a OsStr) -> UResult { // is it a NAME=VALUE like opt ? let wrap = NativeStr::<'a>::new(opt); - let split_o = wrap.split_once(&'='); + let split_o = wrap.split_once('='); if let Some((name, value)) = split_o { // yes, so push name, value pair opts.sets.push((name, value)); @@ -930,8 +930,8 @@ fn apply_unset_env_vars(opts: &Options<'_>) -> Result<(), Box> { for name in &opts.unsets { let native_name = NativeStr::new(name); if name.is_empty() - || native_name.contains(&'\0').unwrap() - || native_name.contains(&'=').unwrap() + || native_name.contains('\0').unwrap() + || native_name.contains('=').unwrap() { return Err(USimpleError::new( 125, diff --git a/src/uu/env/src/native_int_str.rs b/src/uu/env/src/native_int_str.rs index 7e63a663e4e..3e26dad0740 100644 --- a/src/uu/env/src/native_int_str.rs +++ b/src/uu/env/src/native_int_str.rs @@ -173,7 +173,7 @@ pub fn from_native_int_representation_owned(input: NativeIntString) -> OsString } } -pub fn get_single_native_int_value(c: &char) -> Option { +pub fn get_single_native_int_value(c: char) -> Option { #[cfg(target_os = "windows")] { let mut buf = [0u16, 0]; @@ -229,7 +229,7 @@ impl<'a> NativeStr<'a> { self.native } - pub fn contains(&self, x: &char) -> Option { + pub fn contains(&self, x: char) -> Option { let n_c = get_single_native_int_value(x)?; Some(self.native.contains(&n_c)) } @@ -239,7 +239,7 @@ impl<'a> NativeStr<'a> { result.unwrap() } - pub fn split_once(&self, pred: &char) -> Option<(Cow<'a, OsStr>, Cow<'a, OsStr>)> { + pub fn split_once(&self, pred: char) -> Option<(Cow<'a, OsStr>, Cow<'a, OsStr>)> { let n_c = get_single_native_int_value(pred)?; let p = self.native.iter().position(|&x| x == n_c)?; let before = self.slice(0, p); diff --git a/src/uu/env/src/string_parser.rs b/src/uu/env/src/string_parser.rs index 155eb4781be..a0d0ed7bc79 100644 --- a/src/uu/env/src/string_parser.rs +++ b/src/uu/env/src/string_parser.rs @@ -153,7 +153,7 @@ impl<'a> StringParser<'a> { } pub fn skip_until_char_or_end(&mut self, c: char) { - let native_rep = get_single_native_int_value(&c).unwrap(); + let native_rep = get_single_native_int_value(c).unwrap(); let pos = self.remaining.iter().position(|x| *x == native_rep); if let Some(pos) = pos { diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index 3cfd2c83f47..a2a255992b8 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -56,11 +56,7 @@ pub enum StringOp { } impl BinOp { - fn eval( - &self, - left: ExprResult, - right: ExprResult, - ) -> ExprResult { + fn eval(self, left: ExprResult, right: ExprResult) -> ExprResult { match self { Self::Relation(op) => op.eval(left, right), Self::Numeric(op) => op.eval(left, right), @@ -70,7 +66,7 @@ impl BinOp { } impl RelationOp { - fn eval(&self, a: ExprResult, b: ExprResult) -> ExprResult { + fn eval(self, a: ExprResult, b: ExprResult) -> ExprResult { // Make sure that the given comparison validates the relational operator. let check_cmp = |cmp| { use RelationOp::{Eq, Geq, Gt, Leq, Lt, Neq}; @@ -98,11 +94,7 @@ impl RelationOp { } impl NumericOp { - fn eval( - &self, - left: ExprResult, - right: ExprResult, - ) -> ExprResult { + fn eval(self, left: ExprResult, right: ExprResult) -> ExprResult { let a = left?.eval_as_bigint()?; let b = right?.eval_as_bigint()?; Ok(NumOrStr::Num(match self { @@ -124,11 +116,7 @@ impl NumericOp { } impl StringOp { - fn eval( - &self, - left: ExprResult, - right: ExprResult, - ) -> ExprResult { + fn eval(self, left: ExprResult, right: ExprResult) -> ExprResult { match self { Self::Or => { let left = left?; diff --git a/src/uu/groups/src/groups.rs b/src/uu/groups/src/groups.rs index d82d43fb102..aff29ca1e12 100644 --- a/src/uu/groups/src/groups.rs +++ b/src/uu/groups/src/groups.rs @@ -35,12 +35,12 @@ enum GroupsError { impl UError for GroupsError {} -fn infallible_gid2grp(gid: &u32) -> String { - if let Ok(grp) = gid2grp(*gid) { +fn infallible_gid2grp(gid: u32) -> String { + if let Ok(grp) = gid2grp(gid) { grp } else { // The `show!()` macro sets the global exit code for the program. - show!(GroupsError::GroupNotFound(*gid)); + show!(GroupsError::GroupNotFound(gid)); gid.to_string() } } @@ -58,7 +58,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let Ok(gids) = get_groups_gnu(None) else { return Err(GroupsError::GetGroupsFailed.into()); }; - let groups: Vec = gids.iter().map(infallible_gid2grp).collect(); + let groups: Vec = gids.into_iter().map(infallible_gid2grp).collect(); writeln!(stdout(), "{}", groups.join(" "))?; return Ok(()); } @@ -66,7 +66,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { for user in users { match Passwd::locate(user.as_str()) { Ok(p) => { - let groups: Vec = p.belongs_to().iter().map(infallible_gid2grp).collect(); + let groups: Vec = + p.belongs_to().into_iter().map(infallible_gid2grp).collect(); writeln!(stdout(), "{user} : {}", groups.join(" "))?; } Err(_) => { diff --git a/src/uu/ls/src/colors.rs b/src/uu/ls/src/colors.rs index cc9c9c0d235..fa9a8903bb8 100644 --- a/src/uu/ls/src/colors.rs +++ b/src/uu/ls/src/colors.rs @@ -376,7 +376,7 @@ impl<'a> StyleManager<'a> { } else if file_type.is_dir() { self.indicator_for_directory(path) } else { - self.indicator_for_special_file(file_type) + self.indicator_for_special_file(*file_type) } } @@ -478,7 +478,7 @@ impl<'a> StyleManager<'a> { } #[cfg(unix)] - fn indicator_for_special_file(&self, file_type: &fs::FileType) -> Option { + fn indicator_for_special_file(&self, file_type: fs::FileType) -> Option { if file_type.is_fifo() && self.has_indicator_style(Indicator::FIFO) { return Some(Indicator::FIFO); } @@ -495,7 +495,7 @@ impl<'a> StyleManager<'a> { } #[cfg(not(unix))] - fn indicator_for_special_file(&self, _file_type: &fs::FileType) -> Option { + fn indicator_for_special_file(&self, _file_type: fs::FileType) -> Option { None } diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index 3b1f41aa9d5..b6946cdf8c4 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -89,11 +89,11 @@ fn find_numeric_beginning(s: &str) -> Option<&str> { } // finds the valid beginning part of an input string, or None. -fn find_valid_number_with_suffix<'a>(s: &'a str, unit: &Unit) -> Option<&'a str> { +fn find_valid_number_with_suffix(s: &str, unit: Unit) -> Option<&str> { let numeric_part = find_numeric_beginning(s)?; - let accepts_suffix = unit != &Unit::None; - let accepts_i = [Unit::Auto, Unit::Iec(true)].contains(unit); + let accepts_suffix = unit != Unit::None; + let accepts_i = [Unit::Auto, Unit::Iec(true)].contains(&unit); let mut characters = s.chars().skip(numeric_part.len()); let potential_suffix = characters.next(); @@ -117,7 +117,7 @@ fn find_valid_number_with_suffix<'a>(s: &'a str, unit: &Unit) -> Option<&'a str> } } -fn detailed_error_message(s: &str, unit: &Unit) -> Option { +fn detailed_error_message(s: &str, unit: Unit) -> Option { if s.is_empty() { return Some(translate!("numfmt-error-invalid-number-empty")); } @@ -144,13 +144,13 @@ fn detailed_error_message(s: &str, unit: &Unit) -> Option { None } -fn parse_suffix(s: &str, unit: &Unit) -> Result<(f64, Option)> { +fn parse_suffix(s: &str, unit: Unit) -> Result<(f64, Option)> { if s.is_empty() { return Err(translate!("numfmt-error-invalid-number-empty")); } let with_i = s.ends_with('i'); - if with_i && ![Unit::Auto, Unit::Iec(true)].contains(unit) { + if with_i && ![Unit::Auto, Unit::Iec(true)].contains(&unit) { return Err(translate!("numfmt-error-invalid-suffix", "input" => s.quote())); } let mut iter = s.chars(); @@ -200,9 +200,9 @@ fn parse_implicit_precision(s: &str) -> usize { } } -fn remove_suffix(i: f64, s: Option, u: &Unit) -> Result { +fn remove_suffix(i: f64, s: Option, u: Unit) -> Result { match (s, u) { - (Some((raw_suffix, false)), &Unit::Auto | &Unit::Si) => match raw_suffix { + (Some((raw_suffix, false)), Unit::Auto | Unit::Si) => match raw_suffix { RawSuffix::K => Ok(i * 1e3), RawSuffix::M => Ok(i * 1e6), RawSuffix::G => Ok(i * 1e9), @@ -214,8 +214,8 @@ fn remove_suffix(i: f64, s: Option, u: &Unit) -> Result { RawSuffix::R => Ok(i * 1e27), RawSuffix::Q => Ok(i * 1e30), }, - (Some((raw_suffix, false)), &Unit::Iec(false)) - | (Some((raw_suffix, true)), &Unit::Auto | &Unit::Iec(true)) => match raw_suffix { + (Some((raw_suffix, false)), Unit::Iec(false)) + | (Some((raw_suffix, true)), Unit::Auto | Unit::Iec(true)) => match raw_suffix { RawSuffix::K => Ok(i * IEC_BASES[1]), RawSuffix::M => Ok(i * IEC_BASES[2]), RawSuffix::G => Ok(i * IEC_BASES[3]), @@ -227,10 +227,10 @@ fn remove_suffix(i: f64, s: Option, u: &Unit) -> Result { RawSuffix::R => Ok(i * IEC_BASES[9]), RawSuffix::Q => Ok(i * IEC_BASES[10]), }, - (Some((raw_suffix, false)), &Unit::Iec(true)) => Err( + (Some((raw_suffix, false)), Unit::Iec(true)) => Err( translate!("numfmt-error-missing-i-suffix", "number" => i, "suffix" => format!("{raw_suffix:?}")), ), - (Some((raw_suffix, with_i)), &Unit::None) => Err( + (Some((raw_suffix, with_i)), Unit::None) => Err( translate!("numfmt-error-rejecting-suffix", "number" => i, "suffix" => format!("{raw_suffix:?}{}", if with_i { "i" } else { "" })), ), (None, _) => Ok(i), @@ -239,11 +239,11 @@ fn remove_suffix(i: f64, s: Option, u: &Unit) -> Result { } fn transform_from(s: &str, opts: &TransformOptions) -> Result { - let (i, suffix) = parse_suffix(s, &opts.from) - .map_err(|original| detailed_error_message(s, &opts.from).unwrap_or(original))?; + let (i, suffix) = parse_suffix(s, opts.from) + .map_err(|original| detailed_error_message(s, opts.from).unwrap_or(original))?; let i = i * (opts.from_unit as f64); - remove_suffix(i, suffix, &opts.from).map(|n| { + remove_suffix(i, suffix, opts.from).map(|n| { // GNU numfmt doesn't round values if no --from argument is provided by the user if opts.from == Unit::None { if n == -0.0 { 0.0 } else { n } @@ -301,7 +301,7 @@ fn round_with_precision(n: f64, method: RoundMethod, precision: usize) -> f64 { fn consider_suffix( n: f64, - u: &Unit, + u: Unit, round_method: RoundMethod, precision: usize, ) -> Result<(f64, Option)> { @@ -310,7 +310,7 @@ fn consider_suffix( let abs_n = n.abs(); let suffixes = [K, M, G, T, P, E, Z, Y, R, Q]; - let (bases, with_i) = match *u { + let (bases, with_i) = match u { Unit::Si => (&SI_BASES, false), Unit::Iec(with_i) => (&IEC_BASES, with_i), Unit::Auto => return Err(translate!("numfmt-error-unit-auto-not-supported-with-to")), @@ -353,7 +353,7 @@ fn transform_to( precision: usize, unit_separator: &str, ) -> Result { - let (i2, s) = consider_suffix(s, &opts.to, round_method, precision)?; + let (i2, s) = consider_suffix(s, opts.to, round_method, precision)?; let i2 = i2 / (opts.to_unit as f64); Ok(match s { None => { @@ -567,7 +567,7 @@ mod tests { #[test] fn test_parse_suffix_q_r_k() { - let result = parse_suffix("1Q", &Unit::Auto); + let result = parse_suffix("1Q", Unit::Auto); assert!(result.is_ok()); let (number, suffix) = result.unwrap(); assert_eq!(number, 1.0); @@ -576,7 +576,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::Q as i32); assert!(!with_i); - let result = parse_suffix("2R", &Unit::Auto); + let result = parse_suffix("2R", Unit::Auto); assert!(result.is_ok()); let (number, suffix) = result.unwrap(); assert_eq!(number, 2.0); @@ -585,7 +585,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::R as i32); assert!(!with_i); - let result = parse_suffix("3k", &Unit::Auto); + let result = parse_suffix("3k", Unit::Auto); assert!(result.is_ok()); let (number, suffix) = result.unwrap(); assert_eq!(number, 3.0); @@ -594,7 +594,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::K as i32); assert!(!with_i); - let result = parse_suffix("4Qi", &Unit::Auto); + let result = parse_suffix("4Qi", Unit::Auto); assert!(result.is_ok()); let (number, suffix) = result.unwrap(); assert_eq!(number, 4.0); @@ -603,7 +603,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::Q as i32); assert!(with_i); - let result = parse_suffix("5Ri", &Unit::Auto); + let result = parse_suffix("5Ri", Unit::Auto); assert!(result.is_ok()); let (number, suffix) = result.unwrap(); assert_eq!(number, 5.0); @@ -615,13 +615,13 @@ mod tests { #[test] fn test_parse_suffix_error_messages() { - let result = parse_suffix("foo", &Unit::Auto); + let result = parse_suffix("foo", Unit::Auto); assert!(result.is_err()); let error = result.unwrap_err(); assert!(error.contains("numfmt-error-invalid-number") || error.contains("invalid number")); assert!(!error.contains("invalid suffix")); - let result = parse_suffix("World", &Unit::Auto); + let result = parse_suffix("World", Unit::Auto); assert!(result.is_err()); let error = result.unwrap_err(); assert!(error.contains("numfmt-error-invalid-number") || error.contains("invalid number")); @@ -630,12 +630,12 @@ mod tests { #[test] fn test_detailed_error_message() { - let result = detailed_error_message("123i", &Unit::Auto); + let result = detailed_error_message("123i", Unit::Auto); assert!(result.is_some()); let error = result.unwrap(); assert!(error.contains("numfmt-error-invalid-suffix") || error.contains("invalid suffix")); - let result = detailed_error_message("5MF", &Unit::Auto); + let result = detailed_error_message("5MF", Unit::Auto); assert!(result.is_some()); let error = result.unwrap(); assert!( @@ -643,7 +643,7 @@ mod tests { || error.contains("invalid suffix") ); - let result = detailed_error_message("5KM", &Unit::Auto); + let result = detailed_error_message("5KM", Unit::Auto); assert!(result.is_some()); let error = result.unwrap(); assert!( @@ -656,19 +656,19 @@ mod tests { fn test_remove_suffix_q_r() { use crate::units::Unit; - let result = remove_suffix(1.0, Some((RawSuffix::Q, false)), &Unit::Si); + let result = remove_suffix(1.0, Some((RawSuffix::Q, false)), Unit::Si); assert!(result.is_ok()); assert_eq!(result.unwrap(), 1e30); - let result = remove_suffix(1.0, Some((RawSuffix::R, false)), &Unit::Si); + let result = remove_suffix(1.0, Some((RawSuffix::R, false)), Unit::Si); assert!(result.is_ok()); assert_eq!(result.unwrap(), 1e27); - let result = remove_suffix(1.0, Some((RawSuffix::Q, true)), &Unit::Iec(true)); + let result = remove_suffix(1.0, Some((RawSuffix::Q, true)), Unit::Iec(true)); assert!(result.is_ok()); assert_eq!(result.unwrap(), IEC_BASES[10]); - let result = remove_suffix(1.0, Some((RawSuffix::R, true)), &Unit::Iec(true)); + let result = remove_suffix(1.0, Some((RawSuffix::R, true)), Unit::Iec(true)); assert!(result.is_ok()); assert_eq!(result.unwrap(), IEC_BASES[9]); } @@ -676,67 +676,67 @@ mod tests { #[test] fn test_find_valid_part() { assert_eq!( - find_valid_number_with_suffix("12345KL", &Unit::Auto), + find_valid_number_with_suffix("12345KL", Unit::Auto), Some("12345K") ); assert_eq!( - find_valid_number_with_suffix("12345K", &Unit::Auto), + find_valid_number_with_suffix("12345K", Unit::Auto), Some("12345K") ); assert_eq!( - find_valid_number_with_suffix("12345", &Unit::Auto), + find_valid_number_with_suffix("12345", Unit::Auto), Some("12345") ); assert_eq!( - find_valid_number_with_suffix("asd12345KL", &Unit::Auto), + find_valid_number_with_suffix("asd12345KL", Unit::Auto), None ); assert_eq!( - find_valid_number_with_suffix("8asdf", &Unit::Auto), + find_valid_number_with_suffix("8asdf", Unit::Auto), Some("8") ); - assert_eq!(find_valid_number_with_suffix("5i", &Unit::Si), Some("5")); + assert_eq!(find_valid_number_with_suffix("5i", Unit::Si), Some("5")); assert_eq!( - find_valid_number_with_suffix("5i", &Unit::Iec(true)), + find_valid_number_with_suffix("5i", Unit::Iec(true)), Some("5") ); assert_eq!( - find_valid_number_with_suffix("0.1KL", &Unit::Auto), + find_valid_number_with_suffix("0.1KL", Unit::Auto), Some("0.1K") ); assert_eq!( - find_valid_number_with_suffix("0.1", &Unit::Auto), + find_valid_number_with_suffix("0.1", Unit::Auto), Some("0.1") ); assert_eq!( - find_valid_number_with_suffix("-0.1MT", &Unit::Auto), + find_valid_number_with_suffix("-0.1MT", Unit::Auto), Some("-0.1M") ); assert_eq!( - find_valid_number_with_suffix("-0.1PT", &Unit::Auto), + find_valid_number_with_suffix("-0.1PT", Unit::Auto), Some("-0.1P") ); assert_eq!( - find_valid_number_with_suffix("-0.1PT", &Unit::Auto), + find_valid_number_with_suffix("-0.1PT", Unit::Auto), Some("-0.1P") ); assert_eq!( - find_valid_number_with_suffix("123.4.5", &Unit::Auto), + find_valid_number_with_suffix("123.4.5", Unit::Auto), Some("123.4") ); assert_eq!( - find_valid_number_with_suffix("0.55KiJ", &Unit::Iec(true)), + find_valid_number_with_suffix("0.55KiJ", Unit::Iec(true)), Some("0.55Ki") ); assert_eq!( - find_valid_number_with_suffix("0.55KiJ", &Unit::Iec(false)), + find_valid_number_with_suffix("0.55KiJ", Unit::Iec(false)), Some("0.55K") ); assert_eq!( - find_valid_number_with_suffix("123KICK", &Unit::Auto), + find_valid_number_with_suffix("123KICK", Unit::Auto), Some("123K") ); - assert_eq!(find_valid_number_with_suffix("", &Unit::Auto), None); + assert_eq!(find_valid_number_with_suffix("", Unit::Auto), None); } #[test] @@ -744,7 +744,7 @@ mod tests { use crate::options::RoundMethod; use crate::units::Unit; - let result = consider_suffix(1e27, &Unit::Si, RoundMethod::FromZero, 0); + let result = consider_suffix(1e27, Unit::Si, RoundMethod::FromZero, 0); assert!(result.is_ok()); let (value, suffix) = result.unwrap(); assert!(suffix.is_some()); @@ -752,7 +752,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::R as i32); assert_eq!(value, 1.0); - let result = consider_suffix(1e30, &Unit::Si, RoundMethod::FromZero, 0); + let result = consider_suffix(1e30, Unit::Si, RoundMethod::FromZero, 0); assert!(result.is_ok()); let (value, suffix) = result.unwrap(); assert!(suffix.is_some()); @@ -760,7 +760,7 @@ mod tests { assert_eq!(raw_suffix as i32, RawSuffix::Q as i32); assert_eq!(value, 1.0); - let result = consider_suffix(5e30, &Unit::Si, RoundMethod::FromZero, 0); + let result = consider_suffix(5e30, Unit::Si, RoundMethod::FromZero, 0); assert!(result.is_ok()); let (value, suffix) = result.unwrap(); assert!(suffix.is_some()); diff --git a/src/uu/numfmt/src/options.rs b/src/uu/numfmt/src/options.rs index fedcd19c9e3..8d7b639bb84 100644 --- a/src/uu/numfmt/src/options.rs +++ b/src/uu/numfmt/src/options.rs @@ -71,7 +71,7 @@ pub enum RoundMethod { } impl RoundMethod { - pub fn round(&self, f: f64) -> f64 { + pub fn round(self, f: f64) -> f64 { match self { Self::Up => f.ceil(), Self::Down => f.floor(), diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 10bd7671861..de2f0bf7e9a 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -191,6 +191,8 @@ impl UError for SortError { } } +// refs are required because this fn is used by thiserror macro +#[expect(clippy::trivially_copy_pass_by_ref)] fn format_disorder(file: &OsString, line_number: &usize, line: &String, silent: &bool) -> String { if *silent { String::new() @@ -304,7 +306,7 @@ impl Default for NumericLocaleSettings { } impl NumericLocaleSettings { - fn num_info_settings(&self, accept_si_units: bool) -> NumInfoParseSettings { + fn num_info_settings(self, accept_si_units: bool) -> NumInfoParseSettings { NumInfoParseSettings { accept_si_units, thousands_separator: self.thousands_sep, @@ -658,7 +660,7 @@ impl<'a> Line<'a> { for (selector, selection) in settings.selectors.iter().map(|selector| { ( selector, - selector.get_selection(line, token_buffer, &settings.numeric_locale), + selector.get_selection(line, token_buffer, settings.numeric_locale), ) }) { match selection { @@ -1186,7 +1188,7 @@ impl FieldSelector { &self, line: &'a [u8], tokens: &[Field], - numeric_locale: &NumericLocaleSettings, + numeric_locale: NumericLocaleSettings, ) -> Selection<'a> { // `get_range` expects `None` when we don't need tokens and would get confused by an empty vector. let tokens = if self.needs_tokens { diff --git a/src/uu/split/src/filenames.rs b/src/uu/split/src/filenames.rs index 007f817cc44..83b43943bed 100644 --- a/src/uu/split/src/filenames.rs +++ b/src/uu/split/src/filenames.rs @@ -61,7 +61,7 @@ pub enum SuffixType { impl SuffixType { /// The radix to use when representing the suffix string as digits. - pub fn radix(&self) -> u8 { + pub fn radix(self) -> u8 { match self { Self::Alphabetic => 26, Self::Decimal => 10, diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index 295e52e4c28..6e1a8227900 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -106,8 +106,8 @@ fn filter_args( if let Some(slice) = os_slice.to_str() { if should_extract_obs_lines( slice, - preceding_long_opt_req_value, - preceding_short_opt_req_value, + *preceding_long_opt_req_value, + *preceding_short_opt_req_value, ) { // start of the short option string // that can have obsolete lines option value in it @@ -137,8 +137,8 @@ fn filter_args( /// and if so, a short option that can contain obsolete lines value fn should_extract_obs_lines( slice: &str, - preceding_long_opt_req_value: &bool, - preceding_short_opt_req_value: &bool, + preceding_long_opt_req_value: bool, + preceding_short_opt_req_value: bool, ) -> bool { slice.starts_with('-') && !slice.starts_with("--") diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index 1b7f91584f2..8e044ed77ec 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -351,21 +351,21 @@ fn print_it(output: &OutputType, flags: Flags, width: usize, precision: Precisio // A sign (+ or -) should always be placed before a number produced by a signed conversion. // By default, a sign is used only for negative numbers. // A + overrides a space if both are used. - let padding_char = determine_padding_char(&flags); + let padding_char = determine_padding_char(flags); match output { - OutputType::Str(s) => print_str(s, &flags, width, precision), - OutputType::OsStr(s) => print_os_str(s, &flags, width, precision), - OutputType::Integer(num) => print_integer(*num, &flags, width, precision, padding_char), - OutputType::Unsigned(num) => print_unsigned(*num, &flags, width, precision, padding_char), + OutputType::Str(s) => print_str(s, flags, width, precision), + OutputType::OsStr(s) => print_os_str(s, flags, width, precision), + OutputType::Integer(num) => print_integer(*num, flags, width, precision, padding_char), + OutputType::Unsigned(num) => print_unsigned(*num, flags, width, precision, padding_char), OutputType::UnsignedOct(num) => { - print_unsigned_oct(*num, &flags, width, precision, padding_char); + print_unsigned_oct(*num, flags, width, precision, padding_char); } OutputType::UnsignedHex(num) => { - print_unsigned_hex(*num, &flags, width, precision, padding_char); + print_unsigned_hex(*num, flags, width, precision, padding_char); } OutputType::Float(num) => { - print_float(*num, &flags, width, precision, padding_char); + print_float(*num, flags, width, precision, padding_char); } OutputType::Unknown => print!("?"), } @@ -380,7 +380,7 @@ fn print_it(output: &OutputType, flags: Flags, width: usize, precision: Precisio /// # Returns /// /// * Padding - An instance of the Padding enum representing the padding character. -fn determine_padding_char(flags: &Flags) -> Padding { +fn determine_padding_char(flags: Flags) -> Padding { if flags.zero && !flags.left { Padding::Zero } else { @@ -396,7 +396,7 @@ fn determine_padding_char(flags: &Flags) -> Padding { /// * `flags` - A reference to the Flags struct containing formatting flags. /// * `width` - The width of the field for the printed string. /// * `precision` - How many digits of precision, if any. -fn print_str(s: &str, flags: &Flags, width: usize, precision: Precision) { +fn print_str(s: &str, flags: Flags, width: usize, precision: Precision) { let s = match precision { Precision::Number(p) if p < s.len() => &s[..p], _ => s, @@ -415,7 +415,7 @@ fn print_str(s: &str, flags: &Flags, width: usize, precision: Precision) { /// * `flags` - A reference to the Flags struct containing formatting flags. /// * `width` - The width of the field for the printed string. /// * `precision` - How many digits of precision, if any. -fn print_os_str(s: &OsString, flags: &Flags, width: usize, precision: Precision) { +fn print_os_str(s: &OsString, flags: Flags, width: usize, precision: Precision) { #[cfg(unix)] { use std::os::unix::ffi::OsStrExt; @@ -452,7 +452,7 @@ fn quote_file_name(file_name: &str, quoting_style: &QuotingStyle) -> String { fn get_quoted_file_name( display_name: &str, file: &OsString, - file_type: &FileType, + file_type: FileType, from_user: bool, ) -> Result { let quoting_style = env::var("QUOTING_STYLE") @@ -536,7 +536,7 @@ fn process_token_filesystem(t: &Token, meta: &StatFs, display_name: &str) { /// * `padding_char` - The padding character as determined by `determine_padding_char`. fn print_integer( num: i64, - flags: &Flags, + flags: Flags, width: usize, precision: Precision, padding_char: Padding, @@ -601,7 +601,7 @@ fn precision_trunc(num: f64, precision: Precision) -> String { } } -fn print_float(num: f64, flags: &Flags, width: usize, precision: Precision, padding_char: Padding) { +fn print_float(num: f64, flags: Flags, width: usize, precision: Precision, padding_char: Padding) { let prefix = if flags.sign { "+" } else if flags.space { @@ -625,7 +625,7 @@ fn print_float(num: f64, flags: &Flags, width: usize, precision: Precision, padd /// * `padding_char` - The padding character as determined by `determine_padding_char`. fn print_unsigned( num: u64, - flags: &Flags, + flags: Flags, width: usize, precision: Precision, padding_char: Padding, @@ -655,7 +655,7 @@ fn print_unsigned( /// * `padding_char` - The padding character as determined by `determine_padding_char`. fn print_unsigned_oct( num: u32, - flags: &Flags, + flags: Flags, width: usize, precision: Precision, padding_char: Padding, @@ -680,7 +680,7 @@ fn print_unsigned_oct( /// * `padding_char` - The padding character as determined by `determine_padding_char`. fn print_unsigned_hex( num: u64, - flags: &Flags, + flags: Flags, width: usize, precision: Precision, padding_char: Padding, @@ -1015,7 +1015,7 @@ impl Stater { meta: &Metadata, display_name: &str, file: &OsString, - file_type: &FileType, + file_type: FileType, from_user: bool, #[cfg(feature = "selinux")] follow_symbolic_links: bool, #[cfg(not(feature = "selinux"))] _: bool, @@ -1230,7 +1230,7 @@ impl Stater { &meta, &display_name, &file, - &file_type, + file_type, self.from_user, follow_symbolic_links, ) { diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 1984f18b94d..0c62840e044 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -105,8 +105,8 @@ impl Display for BadSequence { ) } Self::BackwardsRange { end, start } => { - fn end_or_start_to_string(ut: &u32) -> String { - match char::from_u32(*ut) { + fn end_or_start_to_string(ut: u32) -> String { + match char::from_u32(ut) { Some(ch @ '\x20'..='\x7E') => ch.escape_default().to_string(), _ => { format!("\\{ut:03o}") @@ -116,7 +116,7 @@ impl Display for BadSequence { write!( f, "{}", - translate!("tr-error-backwards-range", "start" => end_or_start_to_string(start), "end" => end_or_start_to_string(end)) + translate!("tr-error-backwards-range", "start" => end_or_start_to_string(*start), "end" => end_or_start_to_string(*end)) ) } Self::MultipleCharInEquivalence(s) => write!( diff --git a/src/uu/uniq/src/uniq.rs b/src/uu/uniq/src/uniq.rs index a968e6bf04b..3288241e4ef 100644 --- a/src/uu/uniq/src/uniq.rs +++ b/src/uu/uniq/src/uniq.rs @@ -387,16 +387,16 @@ fn filter_args( if let Some(slice) = os_slice.to_str() { if should_extract_obs_skip_fields( slice, - preceding_long_opt_req_value, - preceding_short_opt_req_value, + *preceding_long_opt_req_value, + *preceding_short_opt_req_value, ) { // start of the short option string // that can have obsolete skip fields option value in it filter = handle_extract_obs_skip_fields(slice, skip_fields_old); } else if should_extract_obs_skip_chars( slice, - preceding_long_opt_req_value, - preceding_short_opt_req_value, + *preceding_long_opt_req_value, + *preceding_short_opt_req_value, ) { // the obsolete skip chars option filter = handle_extract_obs_skip_chars(slice, skip_chars_old); @@ -436,8 +436,8 @@ fn filter_args( /// and if so, a short option that can contain obsolete skip fields value fn should_extract_obs_skip_fields( slice: &str, - preceding_long_opt_req_value: &bool, - preceding_short_opt_req_value: &bool, + preceding_long_opt_req_value: bool, + preceding_short_opt_req_value: bool, ) -> bool { slice.starts_with('-') && !slice.starts_with("--") @@ -452,8 +452,8 @@ fn should_extract_obs_skip_fields( /// Checks if the slice is a true obsolete skip chars short option fn should_extract_obs_skip_chars( slice: &str, - preceding_long_opt_req_value: &bool, - preceding_short_opt_req_value: &bool, + preceding_long_opt_req_value: bool, + preceding_short_opt_req_value: bool, ) -> bool { slice.starts_with('+') && posix_version().is_some_and(|v| v <= OBSOLETE) diff --git a/src/uu/wc/src/utf8/mod.rs b/src/uu/wc/src/utf8/mod.rs index d6efb86ebd5..399a9f3646e 100644 --- a/src/uu/wc/src/utf8/mod.rs +++ b/src/uu/wc/src/utf8/mod.rs @@ -33,7 +33,7 @@ impl Incomplete { } } - pub fn is_empty(&self) -> bool { + pub fn is_empty(self) -> bool { self.buffer_len == 0 } diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index 866f213ff86..3c762353ca3 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -335,7 +335,7 @@ impl> From for TotalWhen { } impl TotalWhen { - fn is_total_row_visible(&self, num_inputs: usize) -> bool { + fn is_total_row_visible(self, num_inputs: usize) -> bool { match self { Self::Auto => num_inputs > 1, Self::Always | Self::Only => true, @@ -846,14 +846,14 @@ fn hardware_feature_label(feature: HardwareFeature) -> &'static str { } } -fn is_simd_runtime_feature(feature: &HardwareFeature) -> bool { +fn is_simd_runtime_feature(feature: HardwareFeature) -> bool { matches!( feature, HardwareFeature::Avx2 | HardwareFeature::Sse2 | HardwareFeature::Asimd ) } -fn is_simd_debug_feature(feature: &HardwareFeature) -> bool { +fn is_simd_debug_feature(feature: HardwareFeature) -> bool { matches!( feature, HardwareFeature::Avx512 @@ -872,16 +872,16 @@ struct WcSimdFeatures { fn wc_simd_features(policy: &SimdPolicy) -> WcSimdFeatures { let enabled = policy .iter_features() - .filter(is_simd_runtime_feature) + .filter(|v| is_simd_runtime_feature(*v)) .collect(); let mut disabled = Vec::new(); let mut disabled_runtime = Vec::new(); for feature in policy.disabled_features() { - if is_simd_debug_feature(&feature) { + if is_simd_debug_feature(feature) { disabled.push(feature); } - if is_simd_runtime_feature(&feature) { + if is_simd_runtime_feature(feature) { disabled_runtime.push(feature); } } @@ -895,12 +895,10 @@ fn wc_simd_features(policy: &SimdPolicy) -> WcSimdFeatures { pub(crate) fn wc_simd_allowed(policy: &SimdPolicy) -> bool { let disabled_features = policy.disabled_features(); - if disabled_features.iter().any(is_simd_runtime_feature) { + if disabled_features.into_iter().any(is_simd_runtime_feature) { return false; } - policy - .iter_features() - .any(|feature| is_simd_runtime_feature(&feature)) + policy.iter_features().any(is_simd_runtime_feature) } fn wc(inputs: &Inputs, settings: &Settings) -> UResult<()> { diff --git a/src/uucore/src/lib/features/checksum/compute.rs b/src/uucore/src/lib/features/checksum/compute.rs index c5b0cf6e4b6..2a25f52806f 100644 --- a/src/uucore/src/lib/features/checksum/compute.rs +++ b/src/uucore/src/lib/features/checksum/compute.rs @@ -55,7 +55,7 @@ pub enum ReadingMode { impl ReadingMode { #[inline] - fn as_char(&self) -> char { + fn as_char(self) -> char { match self { Self::Binary => '*', Self::Text => ' ', @@ -72,8 +72,8 @@ pub enum DigestFormat { impl DigestFormat { #[inline] - fn is_base64(&self) -> bool { - *self == Self::Base64 + fn is_base64(self) -> bool { + self == Self::Base64 } } diff --git a/src/uucore/src/lib/features/checksum/validate.rs b/src/uucore/src/lib/features/checksum/validate.rs index 6754f0a36a3..f21e90a27d8 100644 --- a/src/uucore/src/lib/features/checksum/validate.rs +++ b/src/uucore/src/lib/features/checksum/validate.rs @@ -215,7 +215,7 @@ impl FileChecksumResult { /// The cli options might prevent to display on the outcome of the /// comparison on STDOUT. - fn can_display(&self, verbose: ChecksumVerbose) -> bool { + fn can_display(self, verbose: ChecksumVerbose) -> bool { match self { Self::Ok => verbose.over_quiet(), Self::Failed => verbose.over_status(), diff --git a/src/uucore/src/lib/features/format/argument.rs b/src/uucore/src/lib/features/format/argument.rs index 3561bd4a7d6..b4eea031384 100644 --- a/src/uucore/src/lib/features/format/argument.rs +++ b/src/uucore/src/lib/features/format/argument.rs @@ -73,7 +73,7 @@ impl<'a> FormatArguments<'a> { self.next_arg_position = self.current_offset; } - pub fn next_char(&mut self, position: &ArgumentLocation) -> u8 { + pub fn next_char(&mut self, position: ArgumentLocation) -> u8 { match self.next_arg(position) { Some(FormatArgument::Char(c)) => *c as u8, Some(FormatArgument::Unparsed(os)) => match os_str_as_bytes(os) { @@ -84,14 +84,14 @@ impl<'a> FormatArguments<'a> { } } - pub fn next_string(&mut self, position: &ArgumentLocation) -> &'a OsStr { + pub fn next_string(&mut self, position: ArgumentLocation) -> &'a OsStr { match self.next_arg(position) { Some(FormatArgument::Unparsed(os) | FormatArgument::String(os)) => os, _ => "".as_ref(), } } - pub fn next_i64(&mut self, position: &ArgumentLocation) -> i64 { + pub fn next_i64(&mut self, position: ArgumentLocation) -> i64 { match self.next_arg(position) { Some(FormatArgument::SignedInt(n)) => *n, Some(FormatArgument::Unparsed(os)) => Self::get_num::(os), @@ -99,7 +99,7 @@ impl<'a> FormatArguments<'a> { } } - pub fn next_u64(&mut self, position: &ArgumentLocation) -> u64 { + pub fn next_u64(&mut self, position: ArgumentLocation) -> u64 { match self.next_arg(position) { Some(FormatArgument::UnsignedInt(n)) => *n, Some(FormatArgument::Unparsed(os)) => Self::get_num::(os), @@ -107,7 +107,7 @@ impl<'a> FormatArguments<'a> { } } - pub fn next_extended_big_decimal(&mut self, position: &ArgumentLocation) -> ExtendedBigDecimal { + pub fn next_extended_big_decimal(&mut self, position: ArgumentLocation) -> ExtendedBigDecimal { match self.next_arg(position) { Some(FormatArgument::Float(n)) => n.clone(), Some(FormatArgument::Unparsed(os)) => Self::get_num::(os), @@ -188,14 +188,14 @@ impl<'a> FormatArguments<'a> { self.args.get(pos) } - fn next_arg(&mut self, position: &ArgumentLocation) -> Option<&'a FormatArgument> { + fn next_arg(&mut self, position: ArgumentLocation) -> Option<&'a FormatArgument> { match position { ArgumentLocation::NextArgument => { let arg = self.args.get(self.next_arg_position); self.next_arg_position += 1; arg } - ArgumentLocation::Position(pos) => self.get_at_relative_position(*pos), + ArgumentLocation::Position(pos) => self.get_at_relative_position(pos), } } } @@ -257,7 +257,7 @@ mod tests { assert!(!args.is_exhausted()); assert_eq!(Some(&FormatArgument::Char('a')), args.peek_arg()); assert!(!args.is_exhausted()); // Peek shouldn't consume - assert_eq!(b'a', args.next_char(&ArgumentLocation::NextArgument)); + assert_eq!(b'a', args.next_char(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(args.is_exhausted()); // After batch, exhausted with a single arg assert_eq!(None, args.peek_arg()); @@ -278,26 +278,26 @@ mod tests { ]); // First batch - two sequential calls - assert_eq!(b'z', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b'y', args.next_char(&ArgumentLocation::NextArgument)); + assert_eq!(b'z', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b'y', args.next_char(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same pattern - assert_eq!(b'x', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b'w', args.next_char(&ArgumentLocation::NextArgument)); + assert_eq!(b'x', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b'w', args.next_char(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Third batch - same pattern - assert_eq!(b'v', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b'u', args.next_char(&ArgumentLocation::NextArgument)); + assert_eq!(b'v', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b'u', args.next_char(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Fourth batch - same pattern (last batch) - assert_eq!(b't', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b's', args.next_char(&ArgumentLocation::NextArgument)); + assert_eq!(b't', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b's', args.next_char(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(args.is_exhausted()); } @@ -316,20 +316,20 @@ mod tests { let mut args = FormatArguments::new(&args); // First batch - next_char followed by next_string - assert_eq!(b'a', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!("hello", args.next_string(&ArgumentLocation::NextArgument)); + assert_eq!(b'a', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!("hello", args.next_string(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same pattern - assert_eq!(b'1', args.next_char(&ArgumentLocation::NextArgument)); // First byte of 123 - assert_eq!("world", args.next_string(&ArgumentLocation::NextArgument)); + assert_eq!(b'1', args.next_char(ArgumentLocation::NextArgument)); // First byte of 123 + assert_eq!("world", args.next_string(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Third batch - same pattern (last batch) - assert_eq!(b'z', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!("test", args.next_string(&ArgumentLocation::NextArgument)); + assert_eq!(b'z', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!("test", args.next_string(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(args.is_exhausted()); } @@ -354,23 +354,23 @@ mod tests { ]); // First batch - positional access - assert_eq!(b'b', args.next_char(&non_zero_pos(2))); // Position 2 - assert_eq!(b'a', args.next_char(&non_zero_pos(1))); // Position 1 - assert_eq!(b'c', args.next_char(&non_zero_pos(3))); // Position 3 + assert_eq!(b'b', args.next_char(non_zero_pos(2))); // Position 2 + assert_eq!(b'a', args.next_char(non_zero_pos(1))); // Position 1 + assert_eq!(b'c', args.next_char(non_zero_pos(3))); // Position 3 args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same positional pattern - assert_eq!(b'e', args.next_char(&non_zero_pos(2))); // Position 2 - assert_eq!(b'd', args.next_char(&non_zero_pos(1))); // Position 1 - assert_eq!(b'f', args.next_char(&non_zero_pos(3))); // Position 3 + assert_eq!(b'e', args.next_char(non_zero_pos(2))); // Position 2 + assert_eq!(b'd', args.next_char(non_zero_pos(1))); // Position 1 + assert_eq!(b'f', args.next_char(non_zero_pos(3))); // Position 3 args.start_next_batch(); assert!(!args.is_exhausted()); // Third batch - same positional pattern (last batch) - assert_eq!(b'h', args.next_char(&non_zero_pos(2))); // Position 2 - assert_eq!(b'g', args.next_char(&non_zero_pos(1))); // Position 1 - assert_eq!(b'i', args.next_char(&non_zero_pos(3))); // Position 3 + assert_eq!(b'h', args.next_char(non_zero_pos(2))); // Position 2 + assert_eq!(b'g', args.next_char(non_zero_pos(1))); // Position 1 + assert_eq!(b'i', args.next_char(non_zero_pos(3))); // Position 3 args.start_next_batch(); assert!(args.is_exhausted()); } @@ -390,20 +390,20 @@ mod tests { ]); // First batch - mix of sequential and positional - assert_eq!(b'a', args.next_char(&ArgumentLocation::NextArgument)); // Sequential - assert_eq!(b'c', args.next_char(&non_zero_pos(3))); // Positional + assert_eq!(b'a', args.next_char(ArgumentLocation::NextArgument)); // Sequential + assert_eq!(b'c', args.next_char(non_zero_pos(3))); // Positional args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same mixed pattern - assert_eq!(b'd', args.next_char(&ArgumentLocation::NextArgument)); // Sequential - assert_eq!(b'f', args.next_char(&non_zero_pos(3))); // Positional + assert_eq!(b'd', args.next_char(ArgumentLocation::NextArgument)); // Sequential + assert_eq!(b'f', args.next_char(non_zero_pos(3))); // Positional args.start_next_batch(); assert!(!args.is_exhausted()); // Last batch - same mixed pattern - assert_eq!(b'g', args.next_char(&ArgumentLocation::NextArgument)); // Sequential - assert_eq!(b'\0', args.next_char(&non_zero_pos(3))); // Out of bounds + assert_eq!(b'g', args.next_char(ArgumentLocation::NextArgument)); // Sequential + assert_eq!(b'\0', args.next_char(non_zero_pos(3))); // Out of bounds args.start_next_batch(); assert!(args.is_exhausted()); } @@ -422,17 +422,17 @@ mod tests { let mut args = FormatArguments::new(&args); // First batch - i64, u64, decimal - assert_eq!(10, args.next_i64(&ArgumentLocation::NextArgument)); - assert_eq!(20, args.next_u64(&ArgumentLocation::NextArgument)); - let result = args.next_extended_big_decimal(&ArgumentLocation::NextArgument); + assert_eq!(10, args.next_i64(ArgumentLocation::NextArgument)); + assert_eq!(20, args.next_u64(ArgumentLocation::NextArgument)); + let result = args.next_extended_big_decimal(ArgumentLocation::NextArgument); assert_eq!(ExtendedBigDecimal::zero(), result); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same pattern - assert_eq!(30, args.next_i64(&ArgumentLocation::NextArgument)); - assert_eq!(40, args.next_u64(&ArgumentLocation::NextArgument)); - let result = args.next_extended_big_decimal(&ArgumentLocation::NextArgument); + assert_eq!(30, args.next_i64(ArgumentLocation::NextArgument)); + assert_eq!(40, args.next_u64(ArgumentLocation::NextArgument)); + let result = args.next_extended_big_decimal(ArgumentLocation::NextArgument); assert_eq!(ExtendedBigDecimal::zero(), result); args.start_next_batch(); assert!(args.is_exhausted()); @@ -450,14 +450,14 @@ mod tests { let mut args = FormatArguments::new(&args); // First batch - string, number - assert_eq!("hello", args.next_string(&ArgumentLocation::NextArgument)); - assert_eq!(123, args.next_i64(&ArgumentLocation::NextArgument)); + assert_eq!("hello", args.next_string(ArgumentLocation::NextArgument)); + assert_eq!(123, args.next_i64(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same pattern - assert_eq!("hello", args.next_string(&ArgumentLocation::NextArgument)); - assert_eq!(456, args.next_i64(&ArgumentLocation::NextArgument)); + assert_eq!("hello", args.next_string(ArgumentLocation::NextArgument)); + assert_eq!(456, args.next_i64(ArgumentLocation::NextArgument)); args.start_next_batch(); assert!(args.is_exhausted()); } @@ -476,16 +476,16 @@ mod tests { let mut args = FormatArguments::new(&args); // First batch - positional access of different types - assert_eq!(b'a', args.next_char(&non_zero_pos(1))); - assert_eq!("test", args.next_string(&non_zero_pos(2))); - assert_eq!(42, args.next_u64(&non_zero_pos(3))); + assert_eq!(b'a', args.next_char(non_zero_pos(1))); + assert_eq!("test", args.next_string(non_zero_pos(2))); + assert_eq!(42, args.next_u64(non_zero_pos(3))); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch - same pattern - assert_eq!(b'b', args.next_char(&non_zero_pos(1))); - assert_eq!("more", args.next_string(&non_zero_pos(2))); - assert_eq!(99, args.next_u64(&non_zero_pos(3))); + assert_eq!(b'b', args.next_char(non_zero_pos(1))); + assert_eq!("more", args.next_string(non_zero_pos(2))); + assert_eq!(99, args.next_u64(non_zero_pos(3))); args.start_next_batch(); assert!(args.is_exhausted()); } @@ -502,14 +502,14 @@ mod tests { ]); // First batch - assert_eq!(b'a', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b'c', args.next_char(&non_zero_pos(3))); + assert_eq!(b'a', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b'c', args.next_char(non_zero_pos(3))); args.start_next_batch(); assert!(!args.is_exhausted()); // Second batch (partial) - assert_eq!(b'd', args.next_char(&ArgumentLocation::NextArgument)); - assert_eq!(b'\0', args.next_char(&non_zero_pos(3))); // Out of bounds + assert_eq!(b'd', args.next_char(ArgumentLocation::NextArgument)); + assert_eq!(b'\0', args.next_char(non_zero_pos(3))); // Out of bounds args.start_next_batch(); assert!(args.is_exhausted()); } diff --git a/src/uucore/src/lib/features/format/escape.rs b/src/uucore/src/lib/features/format/escape.rs index cba03a8a603..2c6a0283a6e 100644 --- a/src/uucore/src/lib/features/format/escape.rs +++ b/src/uucore/src/lib/features/format/escape.rs @@ -33,21 +33,21 @@ enum Base { } impl Base { - fn as_base(&self) -> u8 { + fn as_base(self) -> u8 { match self { Self::Oct(_) => 8, Self::Hex => 16, } } - fn max_digits(&self) -> u8 { + fn max_digits(self) -> u8 { match self { - Self::Oct(parsing) => *parsing as u8, + Self::Oct(parsing) => parsing as u8, Self::Hex => 2, } } - fn convert_digit(&self, c: u8) -> Option { + fn convert_digit(self, c: u8) -> Option { match self { Self::Oct(_) => { if matches!(c, b'0'..=b'7') { diff --git a/src/uucore/src/lib/features/format/spec.rs b/src/uucore/src/lib/features/format/spec.rs index 3bef0fbb1a7..3587816b771 100644 --- a/src/uucore/src/lib/features/format/spec.rs +++ b/src/uucore/src/lib/features/format/spec.rs @@ -357,7 +357,7 @@ impl Spec { let (width, neg_width) = resolve_asterisk_width(*width, args).unwrap_or_default(); write_padded( writer, - &[args.next_char(position)], + &[args.next_char(*position)], width, *align_left || neg_width, ) @@ -377,7 +377,7 @@ impl Spec { // TODO: We need to not use Rust's formatting for aligning the output, // so that we can just write bytes to stdout without panicking. let precision = resolve_asterisk_precision(*precision, args); - let os_str = args.next_string(position); + let os_str = args.next_string(*position); let bytes = os_str_as_bytes(os_str)?; let truncated = match precision { @@ -387,7 +387,7 @@ impl Spec { write_padded(writer, truncated, width, *align_left || neg_width) } Self::EscapedString { position } => { - let os_str = args.next_string(position); + let os_str = args.next_string(*position); let bytes = os_str_as_bytes(os_str)?; let mut parsed = Vec::::new(); @@ -404,7 +404,7 @@ impl Spec { } Self::QuotedString { position } => { let s = locale_aware_escape_name( - args.next_string(position), + args.next_string(*position), QuotingStyle::SHELL_ESCAPE, ); let bytes = os_str_as_bytes(&s)?; @@ -419,7 +419,7 @@ impl Spec { } => { let (width, neg_width) = resolve_asterisk_width(*width, args).unwrap_or((0, false)); let precision = resolve_asterisk_precision(*precision, args).unwrap_or_default(); - let i = args.next_i64(position); + let i = args.next_i64(*position); if precision as u64 > i32::MAX as u64 { return Err(FormatError::InvalidPrecision(precision.to_string())); @@ -447,7 +447,7 @@ impl Spec { } => { let (width, neg_width) = resolve_asterisk_width(*width, args).unwrap_or((0, false)); let precision = resolve_asterisk_precision(*precision, args).unwrap_or_default(); - let i = args.next_u64(position); + let i = args.next_u64(*position); if precision as u64 > i32::MAX as u64 { return Err(FormatError::InvalidPrecision(precision.to_string())); @@ -478,7 +478,7 @@ impl Spec { } => { let (width, neg_width) = resolve_asterisk_width(*width, args).unwrap_or((0, false)); let precision = resolve_asterisk_precision(*precision, args); - let f: ExtendedBigDecimal = args.next_extended_big_decimal(position); + let f: ExtendedBigDecimal = args.next_extended_big_decimal(*position); if precision.is_some_and(|p| p as u64 > i32::MAX as u64) { return Err(FormatError::InvalidPrecision( @@ -515,7 +515,7 @@ fn resolve_asterisk_width( match option { None => None, Some(CanAsterisk::Asterisk(loc)) => { - let nb = args.next_i64(&loc); + let nb = args.next_i64(loc); if nb < 0 { Some((usize::try_from(-(nb as isize)).ok().unwrap_or(0), true)) } else { @@ -534,7 +534,7 @@ fn resolve_asterisk_precision( ) -> Option { match option { None => None, - Some(CanAsterisk::Asterisk(loc)) => match args.next_i64(&loc) { + Some(CanAsterisk::Asterisk(loc)) => match args.next_i64(loc) { v if v >= 0 => usize::try_from(v).ok(), v if v < 0 => Some(0usize), _ => None, diff --git a/src/uucore/src/lib/features/parser/num_parser.rs b/src/uucore/src/lib/features/parser/num_parser.rs index b23f51fb52e..c52cddd6ad0 100644 --- a/src/uucore/src/lib/features/parser/num_parser.rs +++ b/src/uucore/src/lib/features/parser/num_parser.rs @@ -35,7 +35,7 @@ enum Base { impl Base { /// Return the digit value of a character in the given base - fn digit(&self, c: char) -> Option { + fn digit(self, c: char) -> Option { fn from_decimal(c: char) -> u64 { u64::from(c) - u64::from('0') } @@ -53,7 +53,7 @@ impl Base { /// Greedily parse as many digits as possible from the string /// Returns parsed digits (if any), and the rest of the string. - fn parse_digits<'a>(&self, str: &'a str) -> (Option, &'a str) { + fn parse_digits(self, str: &str) -> (Option, &str) { let (digits, _, rest) = self.parse_digits_count(str, None); (digits, rest) } @@ -61,11 +61,11 @@ impl Base { /// Greedily parse as many digits as possible from the string, adding to already parsed digits. /// This is meant to be used (directly) for the part after a decimal point. /// Returns parsed digits (if any), the number of parsed digits, and the rest of the string. - fn parse_digits_count<'a>( - &self, - str: &'a str, + fn parse_digits_count( + self, + str: &str, digits: Option, - ) -> (Option, i64, &'a str) { + ) -> (Option, i64, &str) { let mut digits: Option = digits; let mut count: i64 = 0; let mut rest = str; @@ -77,9 +77,9 @@ impl Base { let mut mul_tmp: u64 = 1; while let Some(d) = rest.chars().next().and_then(|c| self.digit(c)) { (digits_tmp, count_tmp, mul_tmp) = ( - digits_tmp * *self as u64 + d, + digits_tmp * self as u64 + d, count_tmp + 1, - mul_tmp * *self as u64, + mul_tmp * self as u64, ); rest = &rest[1..]; // In base 16, we parse 4 bits at a time, so we can parse 16 digits at most in a u64. diff --git a/src/uucore/src/lib/features/safe_traversal.rs b/src/uucore/src/lib/features/safe_traversal.rs index 42ab0a12429..05c456ad4ce 100644 --- a/src/uucore/src/lib/features/safe_traversal.rs +++ b/src/uucore/src/lib/features/safe_traversal.rs @@ -345,15 +345,15 @@ impl FileType { } } - pub fn is_directory(&self) -> bool { + pub fn is_directory(self) -> bool { matches!(self, Self::Directory) } - pub fn is_regular_file(&self) -> bool { + pub fn is_regular_file(self) -> bool { matches!(self, Self::RegularFile) } - pub fn is_symlink(&self) -> bool { + pub fn is_symlink(self) -> bool { matches!(self, Self::Symlink) } }