From ba45fe312abffe58241d1bb031e024c602a1dd6e Mon Sep 17 00:00:00 2001 From: Daniel Eades Date: Sun, 30 Jan 2022 14:59:31 +0100 Subject: [PATCH] use 'Self' and derive 'Default' where possible --- src/uu/base32/src/base_common.rs | 4 +- src/uu/cp/src/cp.rs | 54 +++---- src/uu/csplit/src/csplit.rs | 8 +- src/uu/csplit/src/csplit_error.rs | 2 +- src/uu/csplit/src/patterns.rs | 8 +- src/uu/csplit/src/split_name.rs | 4 +- src/uu/date/src/date.rs | 16 +- src/uu/dd/src/dd.rs | 8 +- src/uu/dd/src/parseargs.rs | 6 +- src/uu/df/src/df.rs | 18 +-- src/uu/du/src/du.rs | 12 +- src/uu/expand/src/expand.rs | 4 +- src/uu/expr/src/syntax_tree.rs | 12 +- src/uu/expr/src/tokens.rs | 8 +- src/uu/factor/sieve.rs | 28 ++-- src/uu/factor/src/factor.rs | 16 +- src/uu/factor/src/miller_rabin.rs | 2 +- src/uu/factor/src/numeric/montgomery.rs | 2 +- src/uu/factor/src/numeric/traits.rs | 2 +- src/uu/hashsum/src/digest.rs | 6 +- src/uu/head/src/head.rs | 4 +- src/uu/head/src/take.rs | 4 +- src/uu/join/src/join.rs | 18 +-- src/uu/ls/src/ls.rs | 4 +- src/uu/ls/src/quoting_style.rs | 4 +- src/uu/od/src/formatteriteminfo.rs | 2 +- src/uu/od/src/inputoffset.rs | 4 +- src/uu/od/src/mockstream.rs | 4 +- src/uu/od/src/od.rs | 4 +- src/uu/od/src/output_info.rs | 8 +- src/uu/od/src/parse_formats.rs | 7 +- src/uu/od/src/partialreader.rs | 2 +- src/uu/od/src/peekreader.rs | 2 +- src/uu/pr/src/pr.rs | 10 +- src/uu/ptx/src/ptx.rs | 8 +- src/uu/runcon/src/errors.rs | 8 +- src/uu/seq/src/extendedbigdecimal.rs | 12 +- src/uu/seq/src/extendedbigint.rs | 22 +-- src/uu/seq/src/number.rs | 12 +- src/uu/shred/src/shred.rs | 4 +- src/uu/shuf/src/rand_read_adapter.rs | 4 +- src/uu/sort/src/chunks.rs | 2 +- src/uu/sort/src/merge.rs | 4 +- src/uu/sort/src/numeric_str_cmp.rs | 8 +- src/uu/sort/src/sort.rs | 15 +- src/uu/split/src/platform/unix.rs | 8 +- src/uu/split/src/split.rs | 20 +-- src/uu/stat/src/stat.rs | 10 +- src/uu/stdbuf/src/stdbuf.rs | 2 +- src/uu/tail/src/platform/unix.rs | 4 +- src/uu/tail/src/tail.rs | 4 +- src/uu/test/src/parser.rs | 52 +++---- src/uu/timeout/src/timeout.rs | 4 +- src/uu/tr/src/operation.rs | 139 ++++++++---------- src/uu/tsort/src/tsort.rs | 9 +- src/uu/unexpand/src/unexpand.rs | 4 +- src/uu/wc/src/wc.rs | 6 +- src/uu/yes/src/splice.rs | 2 +- src/uucore/src/lib/features/encoding.rs | 2 +- src/uucore/src/lib/features/entries.rs | 4 +- src/uucore/src/lib/features/fsext.rs | 12 +- src/uucore/src/lib/features/memo.rs | 6 +- src/uucore/src/lib/features/process.rs | 4 +- src/uucore/src/lib/features/ringbuffer.rs | 8 +- .../formatters/cninetyninehexfloatf.rs | 5 +- .../tokenize/num_format/formatters/decf.rs | 4 +- .../num_format/formatters/float_common.rs | 4 +- .../tokenize/num_format/formatters/floatf.rs | 5 +- .../tokenize/num_format/formatters/intf.rs | 15 +- .../tokenize/num_format/formatters/scif.rs | 5 +- src/uucore/src/lib/features/tokenize/sub.rs | 26 ++-- .../lib/features/tokenize/unescaped_text.rs | 17 ++- src/uucore/src/lib/features/utmpx.rs | 2 +- src/uucore/src/lib/mods/error.rs | 10 +- src/uucore/src/lib/mods/ranges.rs | 14 +- src/uucore/src/lib/parser/parse_size.rs | 8 +- tests/by-util/test_kill.rs | 4 +- tests/by-util/test_split.rs | 10 +- tests/common/util.rs | 94 ++++++------ 79 files changed, 445 insertions(+), 474 deletions(-) diff --git a/src/uu/base32/src/base_common.rs b/src/uu/base32/src/base_common.rs index 35295a295..39a46e315 100644 --- a/src/uu/base32/src/base_common.rs +++ b/src/uu/base32/src/base_common.rs @@ -38,7 +38,7 @@ pub mod options { } impl Config { - pub fn from(options: &clap::ArgMatches) -> UResult { + pub fn from(options: &clap::ArgMatches) -> UResult { let file: Option = match options.values_of(options::FILE) { Some(mut values) => { let name = values.next().unwrap(); @@ -76,7 +76,7 @@ impl Config { }) .transpose()?; - Ok(Config { + Ok(Self { decode: options.is_present(options::DECODE), ignore_garbage: options.is_present(options::IGNORE_GARBAGE), wrap_cols: cols, diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 871017f26..374ab2f81 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -495,43 +495,43 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } impl ClobberMode { - fn from_matches(matches: &ArgMatches) -> ClobberMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::FORCE) { - ClobberMode::Force + Self::Force } else if matches.is_present(options::REMOVE_DESTINATION) { - ClobberMode::RemoveDestination + Self::RemoveDestination } else { - ClobberMode::Standard + Self::Standard } } } impl OverwriteMode { - fn from_matches(matches: &ArgMatches) -> OverwriteMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::INTERACTIVE) { - OverwriteMode::Interactive(ClobberMode::from_matches(matches)) + Self::Interactive(ClobberMode::from_matches(matches)) } else if matches.is_present(options::NO_CLOBBER) { - OverwriteMode::NoClobber + Self::NoClobber } else { - OverwriteMode::Clobber(ClobberMode::from_matches(matches)) + Self::Clobber(ClobberMode::from_matches(matches)) } } } impl CopyMode { - fn from_matches(matches: &ArgMatches) -> CopyMode { + fn from_matches(matches: &ArgMatches) -> Self { if matches.is_present(options::LINK) { - CopyMode::Link + Self::Link } else if matches.is_present(options::SYMBOLIC_LINK) { - CopyMode::SymLink + Self::SymLink } else if matches.is_present(options::SPARSE) { - CopyMode::Sparse + Self::Sparse } else if matches.is_present(options::UPDATE) { - CopyMode::Update + Self::Update } else if matches.is_present(options::ATTRIBUTES_ONLY) { - CopyMode::AttrOnly + Self::AttrOnly } else { - CopyMode::Copy + Self::Copy } } } @@ -539,16 +539,16 @@ impl CopyMode { impl FromStr for Attribute { type Err = Error; - fn from_str(value: &str) -> CopyResult { + fn from_str(value: &str) -> CopyResult { Ok(match &*value.to_lowercase() { - "mode" => Attribute::Mode, + "mode" => Self::Mode, #[cfg(unix)] - "ownership" => Attribute::Ownership, - "timestamps" => Attribute::Timestamps, + "ownership" => Self::Ownership, + "timestamps" => Self::Timestamps, #[cfg(feature = "feat_selinux")] - "context" => Attribute::Context, - "links" => Attribute::Links, - "xattr" => Attribute::Xattr, + "context" => Self::Context, + "links" => Self::Links, + "xattr" => Self::Xattr, _ => { return Err(Error::InvalidArgument(format!( "invalid attribute {}", @@ -577,7 +577,7 @@ fn add_all_attributes() -> Vec { } impl Options { - fn from_matches(matches: &ArgMatches) -> CopyResult { + fn from_matches(matches: &ArgMatches) -> CopyResult { let not_implemented_opts = vec![ options::COPY_CONTENTS, options::SPARSE, @@ -646,7 +646,7 @@ impl Options { // if not executed first. preserve_attributes.sort_unstable(); - let options = Options { + let options = Self { attributes_only: matches.is_present(options::ATTRIBUTES_ONLY), copy_contents: matches.is_present(options::COPY_CONTENTS), copy_mode: CopyMode::from_matches(matches), @@ -703,11 +703,11 @@ impl TargetType { /// /// Treat target as a dir if we have multiple sources or the target /// exists and already is a directory - fn determine(sources: &[Source], target: &TargetSlice) -> TargetType { + fn determine(sources: &[Source], target: &TargetSlice) -> Self { if sources.len() > 1 || target.is_dir() { - TargetType::Directory + Self::Directory } else { - TargetType::File + Self::File } } } diff --git a/src/uu/csplit/src/csplit.rs b/src/uu/csplit/src/csplit.rs index 6f79b69f2..da0d24727 100644 --- a/src/uu/csplit/src/csplit.rs +++ b/src/uu/csplit/src/csplit.rs @@ -57,13 +57,13 @@ pub struct CsplitOptions { } impl CsplitOptions { - fn new(matches: &ArgMatches) -> CsplitOptions { + fn new(matches: &ArgMatches) -> Self { let keep_files = matches.is_present(options::KEEP_FILES); let quiet = matches.is_present(options::QUIET); let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES); let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED); - CsplitOptions { + Self { split_name: crash_if_err!( 1, SplitName::new( @@ -477,8 +477,8 @@ impl InputSplitter where I: Iterator)>, { - fn new(iter: I) -> InputSplitter { - InputSplitter { + fn new(iter: I) -> Self { + Self { iter, buffer: Vec::new(), rewind: false, diff --git a/src/uu/csplit/src/csplit_error.rs b/src/uu/csplit/src/csplit_error.rs index 53d48a026..b81a331a2 100644 --- a/src/uu/csplit/src/csplit_error.rs +++ b/src/uu/csplit/src/csplit_error.rs @@ -35,7 +35,7 @@ pub enum CsplitError { impl From for CsplitError { fn from(error: io::Error) -> Self { - CsplitError::IoError(error) + Self::IoError(error) } } diff --git a/src/uu/csplit/src/patterns.rs b/src/uu/csplit/src/patterns.rs index 6689b79de..0346ed381 100644 --- a/src/uu/csplit/src/patterns.rs +++ b/src/uu/csplit/src/patterns.rs @@ -44,8 +44,8 @@ pub enum ExecutePattern { impl ExecutePattern { pub fn iter(&self) -> ExecutePatternIter { match self { - ExecutePattern::Times(n) => ExecutePatternIter::new(Some(*n)), - ExecutePattern::Always => ExecutePatternIter::new(None), + Self::Times(n) => ExecutePatternIter::new(Some(*n)), + Self::Always => ExecutePatternIter::new(None), } } } @@ -56,8 +56,8 @@ pub struct ExecutePatternIter { } impl ExecutePatternIter { - fn new(max: Option) -> ExecutePatternIter { - ExecutePatternIter { max, cur: 0 } + fn new(max: Option) -> Self { + Self { max, cur: 0 } } } diff --git a/src/uu/csplit/src/split_name.rs b/src/uu/csplit/src/split_name.rs index 44ea2a5af..b1f4f1505 100644 --- a/src/uu/csplit/src/split_name.rs +++ b/src/uu/csplit/src/split_name.rs @@ -29,7 +29,7 @@ impl SplitName { prefix_opt: Option, format_opt: Option, n_digits_opt: Option, - ) -> Result { + ) -> Result { // get the prefix let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); // the width for the split offset @@ -231,7 +231,7 @@ impl SplitName { } }; - Ok(SplitName { fn_split_name }) + Ok(Self { fn_split_name }) } /// Returns the filename of the i-th split. diff --git a/src/uu/date/src/date.rs b/src/uu/date/src/date.rs index 49090f0ff..5a88225bb 100644 --- a/src/uu/date/src/date.rs +++ b/src/uu/date/src/date.rs @@ -111,11 +111,11 @@ enum Iso8601Format { impl<'a> From<&'a str> for Iso8601Format { fn from(s: &str) -> Self { match s { - HOURS | HOUR => Iso8601Format::Hours, - MINUTES | MINUTE => Iso8601Format::Minutes, - SECONDS | SECOND => Iso8601Format::Seconds, - NS => Iso8601Format::Ns, - DATE => Iso8601Format::Date, + HOURS | HOUR => Self::Hours, + MINUTES | MINUTE => Self::Minutes, + SECONDS | SECOND => Self::Seconds, + NS => Self::Ns, + DATE => Self::Date, // Should be caught by clap _ => panic!("Invalid format: {}", s), } @@ -131,9 +131,9 @@ enum Rfc3339Format { impl<'a> From<&'a str> for Rfc3339Format { fn from(s: &str) -> Self { match s { - DATE => Rfc3339Format::Date, - SECONDS | SECOND => Rfc3339Format::Seconds, - NS => Rfc3339Format::Ns, + DATE => Self::Date, + SECONDS | SECOND => Self::Seconds, + NS => Self::Ns, // Should be caught by clap _ => panic!("Invalid format: {}", s), } diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index 7640cadaf..54e3190ce 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -69,7 +69,7 @@ impl Input { let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?; let count = parseargs::parse_count(&iflags, matches)?; - let mut i = Input { + let mut i = Self { src: io::stdin(), non_ascii, ibs, @@ -157,7 +157,7 @@ impl Input { .map_err_context(|| "failed to seek in input file".to_string())?; } - let i = Input { + let i = Self { src, non_ascii, ibs, @@ -306,7 +306,7 @@ impl OutputTrait for Output { .map_err_context(|| String::from("write error"))?; } - Ok(Output { dst, obs, cflags }) + Ok(Self { dst, obs, cflags }) } fn fsync(&mut self) -> io::Result<()> { @@ -497,7 +497,7 @@ impl OutputTrait for Output { .map_err_context(|| "failed to seek in output file".to_string())?; } - Ok(Output { dst, obs, cflags }) + Ok(Self { dst, obs, cflags }) } else { // The following error should only occur if someone // mistakenly calls Output::::new() without checking diff --git a/src/uu/dd/src/parseargs.rs b/src/uu/dd/src/parseargs.rs index c790de41f..d85a7fcc7 100644 --- a/src/uu/dd/src/parseargs.rs +++ b/src/uu/dd/src/parseargs.rs @@ -296,9 +296,9 @@ impl std::str::FromStr for StatusLevel { fn from_str(s: &str) -> Result { match s { - "none" => Ok(StatusLevel::None), - "noxfer" => Ok(StatusLevel::Noxfer), - "progress" => Ok(StatusLevel::Progress), + "none" => Ok(Self::None), + "noxfer" => Ok(Self::Noxfer), + "progress" => Ok(Self::Progress), _ => Err(ParseError::StatusLevelNotRecognized(s.to_string())), } } diff --git a/src/uu/df/src/df.rs b/src/uu/df/src/df.rs index b9512f6d8..77deeb6df 100644 --- a/src/uu/df/src/df.rs +++ b/src/uu/df/src/df.rs @@ -52,6 +52,7 @@ static OPT_EXCLUDE_TYPE: &str = "exclude-type"; /// Store names of file systems as a selector. /// Note: `exclude` takes priority over `include`. +#[derive(Default)] struct FsSelector { include: HashSet, exclude: HashSet, @@ -79,11 +80,8 @@ fn usage() -> String { } impl FsSelector { - fn new() -> FsSelector { - FsSelector { - include: HashSet::new(), - exclude: HashSet::new(), - } + fn new() -> Self { + Self::default() } #[inline(always)] @@ -105,8 +103,8 @@ impl FsSelector { } impl Options { - fn new() -> Options { - Options { + fn new() -> Self { + Self { show_local_fs: false, show_all_fs: false, show_listed_fs: false, @@ -124,7 +122,7 @@ impl Options { impl Filesystem { // TODO: resolve uuid in `mount_info.dev_name` if exists - fn new(mount_info: MountInfo) -> Option { + fn new(mount_info: MountInfo) -> Option { let _stat_path = if !mount_info.mount_dir.is_empty() { mount_info.mount_dir.clone() } else { @@ -145,14 +143,14 @@ impl Filesystem { if statfs_fn(path.as_ptr(), &mut statvfs) < 0 { None } else { - Some(Filesystem { + Some(Self { mount_info, usage: FsUsage::new(statvfs), }) } } #[cfg(windows)] - Some(Filesystem { + Some(Self { mount_info, usage: FsUsage::new(Path::new(&_stat_path)), }) diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index 72a5f771f..16e1d166f 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -114,7 +114,7 @@ struct Stat { } impl Stat { - fn new(path: PathBuf, options: &Options) -> Result { + fn new(path: PathBuf, options: &Options) -> Result { let metadata = if options.dereference { fs::metadata(&path)? } else { @@ -127,7 +127,7 @@ impl Stat { dev_id: metadata.dev(), }; #[cfg(not(windows))] - return Ok(Stat { + return Ok(Self { path, is_dir: metadata.is_dir(), size: metadata.len(), @@ -815,9 +815,9 @@ impl FromStr for Threshold { let size = u64::try_from(parse_size(&s[offset..])?).unwrap(); if s.starts_with('-') { - Ok(Threshold::Upper(size)) + Ok(Self::Upper(size)) } else { - Ok(Threshold::Lower(size)) + Ok(Self::Lower(size)) } } } @@ -825,8 +825,8 @@ impl FromStr for Threshold { impl Threshold { fn should_exclude(&self, size: u64) -> bool { match *self { - Threshold::Upper(threshold) => size > threshold, - Threshold::Lower(threshold) => size < threshold, + Self::Upper(threshold) => size > threshold, + Self::Lower(threshold) => size < threshold, } } } diff --git a/src/uu/expand/src/expand.rs b/src/uu/expand/src/expand.rs index 8e4bf43b8..fd7876ad1 100644 --- a/src/uu/expand/src/expand.rs +++ b/src/uu/expand/src/expand.rs @@ -133,7 +133,7 @@ struct Options { } impl Options { - fn new(matches: &ArgMatches) -> Options { + fn new(matches: &ArgMatches) -> Self { let (remaining_mode, tabstops) = match matches.value_of(options::TABS) { Some(s) => tabstops_parse(s), None => (RemainingMode::None, vec![DEFAULT_TABSTOP]), @@ -160,7 +160,7 @@ impl Options { None => vec!["-".to_owned()], }; - Options { + Self { files, tabstops, tspaces, diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index 3c78358dc..8894f87fb 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -66,23 +66,23 @@ impl AstNode { } } - fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { - Box::new(AstNode::Node { + fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { + Box::new(Self::Node { token_idx, op_type: op_type.into(), operands, }) } - fn new_leaf(token_idx: usize, value: &str) -> Box { - Box::new(AstNode::Leaf { + fn new_leaf(token_idx: usize, value: &str) -> Box { + Box::new(Self::Leaf { token_idx, value: value.into(), }) } pub fn evaluate(&self) -> Result { match self { - AstNode::Leaf { value, .. } => Ok(value.clone()), - AstNode::Node { op_type, .. } => match self.operand_values() { + Self::Leaf { value, .. } => Ok(value.clone()), + Self::Node { op_type, .. } => match self.operand_values() { Err(reason) => Err(reason), Ok(operand_values) => match op_type.as_ref() { "+" => { diff --git a/src/uu/expr/src/tokens.rs b/src/uu/expr/src/tokens.rs index a80ad4a60..27912d006 100644 --- a/src/uu/expr/src/tokens.rs +++ b/src/uu/expr/src/tokens.rs @@ -42,25 +42,25 @@ pub enum Token { } impl Token { fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self { - Token::InfixOp { + Self::InfixOp { left_assoc, precedence, value: v.into(), } } fn new_value(v: &str) -> Self { - Token::Value { value: v.into() } + Self::Value { value: v.into() } } fn is_infix_plus(&self) -> bool { match self { - Token::InfixOp { value, .. } => value == "+", + Self::InfixOp { value, .. } => value == "+", _ => false, } } fn is_a_number(&self) -> bool { match self { - Token::Value { value, .. } => value.parse::().is_ok(), + Self::Value { value, .. } => value.parse::().is_ok(), _ => false, } } diff --git a/src/uu/factor/sieve.rs b/src/uu/factor/sieve.rs index f783c2d98..e7d499151 100644 --- a/src/uu/factor/sieve.rs +++ b/src/uu/factor/sieve.rs @@ -15,6 +15,7 @@ use std::slice::Iter; /// This is a reasonably efficient implementation based on /// O'Neill, M. E. "[The Genuine Sieve of Eratosthenes.](http://dx.doi.org/10.1017%2FS0956796808007004)" /// Journal of Functional Programming, Volume 19, Issue 1, 2009, pp. 95--106. +#[derive(Default)] pub struct Sieve { inner: Wheel, filts: PrimeHeap, @@ -58,23 +59,20 @@ impl Iterator for Sieve { } impl Sieve { - fn new() -> Sieve { - Sieve { - inner: Wheel::new(), - filts: PrimeHeap::new(), - } + fn new() -> Self { + Self::default() } #[allow(dead_code)] #[inline] pub fn primes() -> PrimeSieve { - INIT_PRIMES.iter().copied().chain(Sieve::new()) + INIT_PRIMES.iter().copied().chain(Self::new()) } #[allow(dead_code)] #[inline] pub fn odd_primes() -> PrimeSieve { - INIT_PRIMES[1..].iter().copied().chain(Sieve::new()) + INIT_PRIMES[1..].iter().copied().chain(Self::new()) } } @@ -106,14 +104,20 @@ impl Iterator for Wheel { impl Wheel { #[inline] - fn new() -> Wheel { - Wheel { + fn new() -> Self { + Self { next: 11u64, increment: WHEEL_INCS.iter().cycle(), } } } +impl Default for Wheel { + fn default() -> Self { + Self::new() + } +} + /// The increments of a wheel of circumference 210 /// (i.e., a wheel that skips all multiples of 2, 3, 5, 7) const WHEEL_INCS: &[u64] = &[ @@ -124,16 +128,12 @@ const INIT_PRIMES: &[u64] = &[2, 3, 5, 7]; /// A min-heap of "infinite lists" of prime multiples, where a list is /// represented as (head, increment). -#[derive(Debug)] +#[derive(Debug, Default)] struct PrimeHeap { data: Vec<(u64, u64)>, } impl PrimeHeap { - fn new() -> PrimeHeap { - PrimeHeap { data: Vec::new() } - } - fn peek(&self) -> Option<(u64, u64)> { if let Some(&(x, y)) = self.data.get(0) { Some((x, y)) diff --git a/src/uu/factor/src/factor.rs b/src/uu/factor/src/factor.rs index 151aa74a9..c776f95ea 100644 --- a/src/uu/factor/src/factor.rs +++ b/src/uu/factor/src/factor.rs @@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table}; type Exponent = u8; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); // spell-checker:ignore (names) Erdős–Kac * Erdős Kac @@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); const NUM_FACTORS_INLINE: usize = 5; impl Decomposition { - fn one() -> Decomposition { - Decomposition(SmallVec::new()) + fn one() -> Self { + Self::default() } fn add(&mut self, factor: u64, exp: Exponent) { @@ -51,7 +51,7 @@ impl Decomposition { } impl PartialEq for Decomposition { - fn eq(&self, other: &Decomposition) -> bool { + fn eq(&self, other: &Self) -> bool { for p in &self.0 { if other.get(p.0) != Some(p) { return false; @@ -73,8 +73,8 @@ impl Eq for Decomposition {} pub struct Factors(RefCell); impl Factors { - pub fn one() -> Factors { - Factors(RefCell::new(Decomposition::one())) + pub fn one() -> Self { + Self(RefCell::new(Decomposition::one())) } pub fn add(&mut self, prime: u64, exp: Exponent) { @@ -286,9 +286,9 @@ impl quickcheck::Arbitrary for Factors { impl std::ops::BitXor for Factors { type Output = Self; - fn bitxor(self, rhs: Exponent) -> Factors { + fn bitxor(self, rhs: Exponent) -> Self { debug_assert_ne!(rhs, 0); - let mut r = Factors::one(); + let mut r = Self::one(); for (p, e) in self.0.borrow().0.iter() { r.add(*p, rhs * e); } diff --git a/src/uu/factor/src/miller_rabin.rs b/src/uu/factor/src/miller_rabin.rs index d336188a5..b5a01735a 100644 --- a/src/uu/factor/src/miller_rabin.rs +++ b/src/uu/factor/src/miller_rabin.rs @@ -42,7 +42,7 @@ pub(crate) enum Result { impl Result { pub(crate) fn is_prime(&self) -> bool { - *self == Result::Prime + *self == Self::Prime } } diff --git a/src/uu/factor/src/numeric/montgomery.rs b/src/uu/factor/src/numeric/montgomery.rs index 485025d87..504e6a09b 100644 --- a/src/uu/factor/src/numeric/montgomery.rs +++ b/src/uu/factor/src/numeric/montgomery.rs @@ -106,7 +106,7 @@ impl Arithmetic for Montgomery { let n = T::from_u64(n); let a = modular_inverse(n).wrapping_neg(); debug_assert_eq!(n.wrapping_mul(&a), T::one().wrapping_neg()); - Montgomery { a, n } + Self { a, n } } fn modulus(&self) -> u64 { diff --git a/src/uu/factor/src/numeric/traits.rs b/src/uu/factor/src/numeric/traits.rs index 2e9167e0b..1dc681976 100644 --- a/src/uu/factor/src/numeric/traits.rs +++ b/src/uu/factor/src/numeric/traits.rs @@ -61,7 +61,7 @@ macro_rules! double_int { fn as_double_width(self) -> $y { self as _ } - fn from_double_width(n: $y) -> $x { + fn from_double_width(n: $y) -> Self { n as _ } } diff --git a/src/uu/hashsum/src/digest.rs b/src/uu/hashsum/src/digest.rs index 4b6b5f6d2..3176f34b5 100644 --- a/src/uu/hashsum/src/digest.rs +++ b/src/uu/hashsum/src/digest.rs @@ -40,7 +40,7 @@ pub trait Digest { impl Digest for md5::Context { fn new() -> Self { - md5::Context::new() + Self::new() } fn input(&mut self, input: &[u8]) { @@ -52,7 +52,7 @@ impl Digest for md5::Context { } fn reset(&mut self) { - *self = md5::Context::new(); + *self = Self::new(); } fn output_bits(&self) -> usize { @@ -85,7 +85,7 @@ impl Digest for blake2b_simd::State { impl Digest for sha1::Sha1 { fn new() -> Self { - sha1::Sha1::new() + Self::new() } fn input(&mut self, input: &[u8]) { diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 69c1ed100..eded419df 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -112,7 +112,7 @@ enum Modes { impl Default for Modes { fn default() -> Self { - Modes::Lines(10) + Self::Lines(10) } } @@ -167,7 +167,7 @@ impl HeadOptions { pub fn get_from(args: impl uucore::Args) -> Result { let matches = uu_app().get_matches_from(arg_iterate(args)?); - let mut options: HeadOptions = Default::default(); + let mut options = Self::default(); options.quiet = matches.is_present(options::QUIET_NAME); options.verbose = matches.is_present(options::VERBOSE_NAME); diff --git a/src/uu/head/src/take.rs b/src/uu/head/src/take.rs index fded202a5..a003f9328 100644 --- a/src/uu/head/src/take.rs +++ b/src/uu/head/src/take.rs @@ -28,7 +28,7 @@ pub struct TakeAllBut { } impl TakeAllBut { - pub fn new(mut iter: I, n: usize) -> TakeAllBut { + pub fn new(mut iter: I, n: usize) -> Self { // Create a new ring buffer and fill it up. // // If there are fewer than `n` elements in `iter`, then we @@ -44,7 +44,7 @@ impl TakeAllBut { }; buf.push_back(value); } - TakeAllBut { iter, buf } + Self { iter, buf } } } diff --git a/src/uu/join/src/join.rs b/src/uu/join/src/join.rs index be664be82..559d957d1 100644 --- a/src/uu/join/src/join.rs +++ b/src/uu/join/src/join.rs @@ -63,8 +63,8 @@ struct Settings { } impl Default for Settings { - fn default() -> Settings { - Settings { + fn default() -> Self { + Self { key1: 0, key2: 0, print_unpaired1: false, @@ -163,8 +163,8 @@ struct Input { } impl Input { - fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Input { - Input { + fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Self { + Self { separator, ignore_case, check_order, @@ -198,14 +198,14 @@ enum Spec { } impl Spec { - fn parse(format: &str) -> UResult { + fn parse(format: &str) -> UResult { let mut chars = format.chars(); let file_num = match chars.next() { Some('0') => { // Must be all alone without a field specifier. if chars.next().is_none() { - return Ok(Spec::Key); + return Ok(Self::Key); } return Err(USimpleError::new( 1, @@ -223,7 +223,7 @@ impl Spec { }; if let Some('.') = chars.next() { - return Ok(Spec::Field(file_num, parse_field_number(chars.as_str())?)); + return Ok(Self::Field(file_num, parse_field_number(chars.as_str())?)); } Err(USimpleError::new( @@ -239,7 +239,7 @@ struct Line { } impl Line { - fn new(string: Vec, separator: Sep) -> Line { + fn new(string: Vec, separator: Sep) -> Self { let fields = match separator { Sep::Whitespaces => string // GNU join uses Bourne shell field splitters by default @@ -251,7 +251,7 @@ impl Line { Sep::Line => vec![string.clone()], }; - Line { fields, string } + Self { fields, string } } /// Get field at index. diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index 0b5bcbb23..ed858e62a 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -339,7 +339,7 @@ struct PaddingCollection { impl Config { #[allow(clippy::cognitive_complexity)] - fn from(options: &clap::ArgMatches) -> UResult { + fn from(options: &clap::ArgMatches) -> UResult { let context = options.is_present(options::CONTEXT); let (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) { ( @@ -661,7 +661,7 @@ impl Config { Dereference::DirArgs }; - Ok(Config { + Ok(Self { format, files, sort, diff --git a/src/uu/ls/src/quoting_style.rs b/src/uu/ls/src/quoting_style.rs index c7c64cc6c..4900dc566 100644 --- a/src/uu/ls/src/quoting_style.rs +++ b/src/uu/ls/src/quoting_style.rs @@ -79,8 +79,8 @@ impl Iterator for EscapeOctal { } impl EscapeOctal { - fn from(c: char) -> EscapeOctal { - EscapeOctal { + fn from(c: char) -> Self { + Self { c, idx: 2, state: EscapeOctalState::Backslash, diff --git a/src/uu/od/src/formatteriteminfo.rs b/src/uu/od/src/formatteriteminfo.rs index 13cf62246..9778b68f4 100644 --- a/src/uu/od/src/formatteriteminfo.rs +++ b/src/uu/od/src/formatteriteminfo.rs @@ -18,7 +18,7 @@ impl Clone for FormatWriter { } impl PartialEq for FormatWriter { - fn eq(&self, other: &FormatWriter) -> bool { + fn eq(&self, other: &Self) -> bool { use crate::formatteriteminfo::FormatWriter::*; match (self, other) { diff --git a/src/uu/od/src/inputoffset.rs b/src/uu/od/src/inputoffset.rs index 2bdf03ca4..bc12098f8 100644 --- a/src/uu/od/src/inputoffset.rs +++ b/src/uu/od/src/inputoffset.rs @@ -19,8 +19,8 @@ pub struct InputOffset { impl InputOffset { /// creates a new `InputOffset` using the provided values. - pub fn new(radix: Radix, byte_pos: usize, label: Option) -> InputOffset { - InputOffset { + pub fn new(radix: Radix, byte_pos: usize, label: Option) -> Self { + Self { radix, byte_pos, label, diff --git a/src/uu/od/src/mockstream.rs b/src/uu/od/src/mockstream.rs index 5beecbf9c..a1ce0dd68 100644 --- a/src/uu/od/src/mockstream.rs +++ b/src/uu/od/src/mockstream.rs @@ -54,8 +54,8 @@ impl FailingMockStream { /// /// When `read` or `write` is called, it will return an error `repeat_count` times. /// `kind` and `message` can be specified to define the exact error. - pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream { - FailingMockStream { + pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> Self { + Self { kind, message, repeat_count, diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index d1be3dfc7..16abb20fc 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -121,7 +121,7 @@ struct OdOptions { } impl OdOptions { - fn new(matches: &ArgMatches, args: &[String]) -> UResult { + fn new(matches: &ArgMatches, args: &[String]) -> UResult { let byte_order = match matches.value_of(options::ENDIAN) { None => ByteOrder::Native, Some("little") => ByteOrder::Little, @@ -232,7 +232,7 @@ impl OdOptions { } }; - Ok(OdOptions { + Ok(Self { byte_order, skip_bytes, read_bytes, diff --git a/src/uu/od/src/output_info.rs b/src/uu/od/src/output_info.rs index cf050475a..60cbaf5ab 100644 --- a/src/uu/od/src/output_info.rs +++ b/src/uu/od/src/output_info.rs @@ -54,7 +54,7 @@ impl OutputInfo { line_bytes: usize, formats: &[ParsedFormatterItemInfo], output_duplicates: bool, - ) -> OutputInfo { + ) -> Self { let byte_size_block = formats.iter().fold(1, |max, next| { cmp::max(max, next.formatter_item_info.byte_size) }); @@ -68,9 +68,9 @@ impl OutputInfo { let print_width_line = print_width_block * (line_bytes / byte_size_block); let spaced_formatters = - OutputInfo::create_spaced_formatter_info(formats, byte_size_block, print_width_block); + Self::create_spaced_formatter_info(formats, byte_size_block, print_width_block); - OutputInfo { + Self { byte_size_line: line_bytes, print_width_line, byte_size_block, @@ -90,7 +90,7 @@ impl OutputInfo { .map(|f| SpacedFormatterItemInfo { formatter_item_info: f.formatter_item_info, add_ascii_dump: f.add_ascii_dump, - spacing: OutputInfo::calculate_alignment(f, byte_size_block, print_width_block), + spacing: Self::calculate_alignment(f, byte_size_block, print_width_block), }) .collect() } diff --git a/src/uu/od/src/parse_formats.rs b/src/uu/od/src/parse_formats.rs index 01dd65e1c..21971445d 100644 --- a/src/uu/od/src/parse_formats.rs +++ b/src/uu/od/src/parse_formats.rs @@ -14,11 +14,8 @@ pub struct ParsedFormatterItemInfo { } impl ParsedFormatterItemInfo { - pub fn new( - formatter_item_info: FormatterItemInfo, - add_ascii_dump: bool, - ) -> ParsedFormatterItemInfo { - ParsedFormatterItemInfo { + pub fn new(formatter_item_info: FormatterItemInfo, add_ascii_dump: bool) -> Self { + Self { formatter_item_info, add_ascii_dump, } diff --git a/src/uu/od/src/partialreader.rs b/src/uu/od/src/partialreader.rs index f155a7bd2..68e3f30a1 100644 --- a/src/uu/od/src/partialreader.rs +++ b/src/uu/od/src/partialreader.rs @@ -24,7 +24,7 @@ impl PartialReader { /// `skip` bytes, and limits the output to `limit` bytes. Set `limit` /// to `None` if there should be no limit. pub fn new(inner: R, skip: usize, limit: Option) -> Self { - PartialReader { inner, skip, limit } + Self { inner, skip, limit } } } diff --git a/src/uu/od/src/peekreader.rs b/src/uu/od/src/peekreader.rs index 73a94d2e2..45cd554d0 100644 --- a/src/uu/od/src/peekreader.rs +++ b/src/uu/od/src/peekreader.rs @@ -43,7 +43,7 @@ pub struct PeekReader { impl PeekReader { /// Create a new `PeekReader` wrapping `inner` pub fn new(inner: R) -> Self { - PeekReader { + Self { inner, temp_buffer: Vec::new(), } diff --git a/src/uu/pr/src/pr.rs b/src/uu/pr/src/pr.rs index 6e0cc76e0..6282be454 100644 --- a/src/uu/pr/src/pr.rs +++ b/src/uu/pr/src/pr.rs @@ -112,8 +112,8 @@ struct NumberingMode { } impl Default for NumberingMode { - fn default() -> NumberingMode { - NumberingMode { + fn default() -> Self { + Self { width: 5, separator: TAB.to_string(), first_number: 1, @@ -122,8 +122,8 @@ impl Default for NumberingMode { } impl Default for FileLine { - fn default() -> FileLine { - FileLine { + fn default() -> Self { + Self { file_id: 0, line_number: 0, page_number: 0, @@ -136,7 +136,7 @@ impl Default for FileLine { impl From for PrError { fn from(err: IOError) -> Self { - PrError::EncounteredErrors(err.to_string()) + Self::EncounteredErrors(err.to_string()) } } diff --git a/src/uu/ptx/src/ptx.rs b/src/uu/ptx/src/ptx.rs index e389b89ac..fff70373f 100644 --- a/src/uu/ptx/src/ptx.rs +++ b/src/uu/ptx/src/ptx.rs @@ -52,8 +52,8 @@ struct Config { } impl Default for Config { - fn default() -> Config { - Config { + fn default() -> Self { + Self { format: OutFormat::Dumb, gnu_ext: true, auto_ref: false, @@ -96,7 +96,7 @@ struct WordFilter { } impl WordFilter { - fn new(matches: &clap::ArgMatches, config: &Config) -> UResult { + fn new(matches: &clap::ArgMatches, config: &Config) -> UResult { let (o, oset): (bool, HashSet) = if matches.is_present(options::ONLY_FILE) { let words = read_word_filter_file(matches, options::ONLY_FILE).map_err_context(String::new)?; @@ -139,7 +139,7 @@ impl WordFilter { } } }; - Ok(WordFilter { + Ok(Self { only_specified: o, ignore_specified: i, only_set: oset, diff --git a/src/uu/runcon/src/errors.rs b/src/uu/runcon/src/errors.rs index 082b55055..18f06deb9 100644 --- a/src/uu/runcon/src/errors.rs +++ b/src/uu/runcon/src/errors.rs @@ -94,12 +94,12 @@ pub(crate) struct RunconError { } impl RunconError { - pub(crate) fn new(e: Error) -> RunconError { - RunconError::with_code(error_exit_status::ANOTHER_ERROR, e) + pub(crate) fn new(e: Error) -> Self { + Self::with_code(error_exit_status::ANOTHER_ERROR, e) } - pub(crate) fn with_code(code: i32, e: Error) -> RunconError { - RunconError { inner: e, code } + pub(crate) fn with_code(code: i32, e: Error) -> Self { + Self { inner: e, code } } } diff --git a/src/uu/seq/src/extendedbigdecimal.rs b/src/uu/seq/src/extendedbigdecimal.rs index 6cad83dad..3c7e3df53 100644 --- a/src/uu/seq/src/extendedbigdecimal.rs +++ b/src/uu/seq/src/extendedbigdecimal.rs @@ -110,10 +110,10 @@ impl From for ExtendedBigDecimal { fn from(big_int: ExtendedBigInt) -> Self { match big_int { ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)), - ExtendedBigInt::Infinity => ExtendedBigDecimal::Infinity, - ExtendedBigInt::MinusInfinity => ExtendedBigDecimal::MinusInfinity, - ExtendedBigInt::MinusZero => ExtendedBigDecimal::MinusZero, - ExtendedBigInt::Nan => ExtendedBigDecimal::Nan, + ExtendedBigInt::Infinity => Self::Infinity, + ExtendedBigInt::MinusInfinity => Self::MinusInfinity, + ExtendedBigInt::MinusZero => Self::MinusZero, + ExtendedBigInt::Nan => Self::Nan, } } } @@ -124,7 +124,7 @@ impl Display for ExtendedBigDecimal { ExtendedBigDecimal::BigDecimal(x) => { let (n, p) = x.as_bigint_and_exponent(); match p { - 0 => ExtendedBigDecimal::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f), + 0 => Self::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f), _ => x.fmt(f), } } @@ -145,7 +145,7 @@ impl Display for ExtendedBigDecimal { impl Zero for ExtendedBigDecimal { fn zero() -> Self { - ExtendedBigDecimal::BigDecimal(BigDecimal::zero()) + Self::BigDecimal(BigDecimal::zero()) } fn is_zero(&self) -> bool { match self { diff --git a/src/uu/seq/src/extendedbigint.rs b/src/uu/seq/src/extendedbigint.rs index 4a33fa617..bbe64300a 100644 --- a/src/uu/seq/src/extendedbigint.rs +++ b/src/uu/seq/src/extendedbigint.rs @@ -42,7 +42,7 @@ impl ExtendedBigInt { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - ExtendedBigInt::BigInt(BigInt::one()) + Self::BigInt(BigInt::one()) } } @@ -51,10 +51,10 @@ impl From for ExtendedBigInt { match big_decimal { // TODO When can this fail? ExtendedBigDecimal::BigDecimal(x) => Self::BigInt(x.to_bigint().unwrap()), - ExtendedBigDecimal::Infinity => ExtendedBigInt::Infinity, - ExtendedBigDecimal::MinusInfinity => ExtendedBigInt::MinusInfinity, - ExtendedBigDecimal::MinusZero => ExtendedBigInt::MinusZero, - ExtendedBigDecimal::Nan => ExtendedBigInt::Nan, + ExtendedBigDecimal::Infinity => Self::Infinity, + ExtendedBigDecimal::MinusInfinity => Self::MinusInfinity, + ExtendedBigDecimal::MinusZero => Self::MinusZero, + ExtendedBigDecimal::Nan => Self::Nan, } } } @@ -62,22 +62,22 @@ impl From for ExtendedBigInt { impl Display for ExtendedBigInt { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ExtendedBigInt::BigInt(n) => n.fmt(f), - ExtendedBigInt::Infinity => f32::INFINITY.fmt(f), - ExtendedBigInt::MinusInfinity => f32::NEG_INFINITY.fmt(f), - ExtendedBigInt::MinusZero => { + Self::BigInt(n) => n.fmt(f), + Self::Infinity => f32::INFINITY.fmt(f), + Self::MinusInfinity => f32::NEG_INFINITY.fmt(f), + Self::MinusZero => { // FIXME Come up with a way of formatting this with a // "-" prefix. 0.fmt(f) } - ExtendedBigInt::Nan => "nan".fmt(f), + Self::Nan => "nan".fmt(f), } } } impl Zero for ExtendedBigInt { fn zero() -> Self { - ExtendedBigInt::BigInt(BigInt::zero()) + Self::BigInt(BigInt::zero()) } fn is_zero(&self) -> bool { match self { diff --git a/src/uu/seq/src/number.rs b/src/uu/seq/src/number.rs index cec96c0ba..1b46f8f55 100644 --- a/src/uu/seq/src/number.rs +++ b/src/uu/seq/src/number.rs @@ -42,7 +42,7 @@ impl Number { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - Number::Int(ExtendedBigInt::one()) + Self::Int(ExtendedBigInt::one()) } /// Round this number towards the given other number. @@ -89,12 +89,8 @@ pub struct PreciseNumber { } impl PreciseNumber { - pub fn new( - number: Number, - num_integral_digits: usize, - num_fractional_digits: usize, - ) -> PreciseNumber { - PreciseNumber { + pub fn new(number: Number, num_integral_digits: usize, num_fractional_digits: usize) -> Self { + Self { number, num_integral_digits, num_fractional_digits, @@ -106,7 +102,7 @@ impl PreciseNumber { // We would like to implement `num_traits::One`, but it requires // a multiplication implementation, and we don't want to // implement that here. - PreciseNumber::new(Number::one(), 1, 0) + Self::new(Number::one(), 1, 0) } /// Decide whether this number is zero (either positive or negative). diff --git a/src/uu/shred/src/shred.rs b/src/uu/shred/src/shred.rs index cb3cee2da..2ad91afd1 100644 --- a/src/uu/shred/src/shred.rs +++ b/src/uu/shred/src/shred.rs @@ -68,9 +68,9 @@ struct FilenameGenerator { } impl FilenameGenerator { - fn new(name_len: usize) -> FilenameGenerator { + fn new(name_len: usize) -> Self { let indices: Vec = vec![0; name_len]; - FilenameGenerator { + Self { name_len, name_charset_indices: RefCell::new(indices), exhausted: Cell::new(false), diff --git a/src/uu/shuf/src/rand_read_adapter.rs b/src/uu/shuf/src/rand_read_adapter.rs index ebe9bd01c..fd8998c10 100644 --- a/src/uu/shuf/src/rand_read_adapter.rs +++ b/src/uu/shuf/src/rand_read_adapter.rs @@ -38,8 +38,8 @@ pub struct ReadRng { impl ReadRng { /// Create a new `ReadRng` from a `Read`. - pub fn new(r: R) -> ReadRng { - ReadRng { reader: r } + pub fn new(r: R) -> Self { + Self { reader: r } } } diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index bfe6aa73b..d7e795efa 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -100,7 +100,7 @@ pub struct RecycledChunk { impl RecycledChunk { pub fn new(capacity: usize) -> Self { - RecycledChunk { + Self { lines: Vec::new(), selections: Vec::new(), num_infos: Vec::new(), diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 96d5128f6..a7b4417e3 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -415,7 +415,7 @@ impl WriteableTmpFile for WriteablePlainTmpFile { type InnerWrite = BufWriter; fn create((file, path): (File, PathBuf), _: Option<&str>) -> UResult { - Ok(WriteablePlainTmpFile { + Ok(Self { file: BufWriter::new(file), path, }) @@ -484,7 +484,7 @@ impl WriteableTmpFile for WriteableCompressedTmpFile { code: err.raw_os_error().unwrap(), })?; let child_stdin = child.stdin.take().unwrap(); - Ok(WriteableCompressedTmpFile { + Ok(Self { path, compress_prog: compress_prog.to_owned(), child, diff --git a/src/uu/sort/src/numeric_str_cmp.rs b/src/uu/sort/src/numeric_str_cmp.rs index d60159775..d6855b267 100644 --- a/src/uu/sort/src/numeric_str_cmp.rs +++ b/src/uu/sort/src/numeric_str_cmp.rs @@ -85,12 +85,12 @@ impl NumInfo { let has_si_unit = parse_settings.accept_si_units && matches!(char, 'K' | 'k' | 'M' | 'G' | 'T' | 'P' | 'E' | 'Z' | 'Y'); ( - NumInfo { exponent, sign }, + Self { exponent, sign }, start..if has_si_unit { idx + 1 } else { idx }, ) } else { ( - NumInfo { + Self { sign: Sign::Positive, exponent: 0, }, @@ -127,10 +127,10 @@ impl NumInfo { } } if let Some(start) = start { - (NumInfo { exponent, sign }, start..num.len()) + (Self { exponent, sign }, start..num.len()) } else { ( - NumInfo { + Self { sign: Sign::Positive, exponent: 0, }, diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index e9177654e..31aa2b0a2 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -323,7 +323,7 @@ pub struct GlobalSettings { /// Data needed for sorting. Should be computed once before starting to sort /// by calling `GlobalSettings::init_precomputed`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] struct Precomputed { needs_tokens: bool, num_infos_per_line: usize, @@ -378,8 +378,8 @@ impl GlobalSettings { } impl Default for GlobalSettings { - fn default() -> GlobalSettings { - GlobalSettings { + fn default() -> Self { + Self { mode: SortMode::Default, debug: false, ignore_leading_blanks: false, @@ -400,12 +400,7 @@ impl Default for GlobalSettings { buffer_size: DEFAULT_BUF_SIZE, compress_prog: None, merge_batch_size: 32, - precomputed: Precomputed { - num_infos_per_line: 0, - floats_per_line: 0, - selections_per_line: 0, - needs_tokens: false, - }, + precomputed: Precomputed::default(), } } } @@ -784,7 +779,7 @@ impl KeyPosition { impl Default for KeyPosition { fn default() -> Self { - KeyPosition { + Self { field: 1, char: 1, ignore_blanks: false, diff --git a/src/uu/split/src/platform/unix.rs b/src/uu/split/src/platform/unix.rs index c05593861..f6bac702b 100644 --- a/src/uu/split/src/platform/unix.rs +++ b/src/uu/split/src/platform/unix.rs @@ -39,10 +39,10 @@ struct WithEnvVarSet { } impl WithEnvVarSet { /// Save previous value assigned to key, set key=value - fn new(key: &str, value: &str) -> WithEnvVarSet { + fn new(key: &str, value: &str) -> Self { let previous_env_value = env::var(key); env::set_var(key, value); - WithEnvVarSet { + Self { _previous_var_key: String::from(key), _previous_var_value: previous_env_value, } @@ -66,7 +66,7 @@ impl FilterWriter { /// /// * `command` - The shell command to execute /// * `filepath` - Path of the output file (forwarded to command as $FILE) - fn new(command: &str, filepath: &str) -> FilterWriter { + fn new(command: &str, filepath: &str) -> Self { // set $FILE, save previous value (if there was one) let _with_env_var_set = WithEnvVarSet::new("FILE", filepath); @@ -78,7 +78,7 @@ impl FilterWriter { .spawn() .expect("Couldn't spawn filter command"); - FilterWriter { shell_process } + Self { shell_process } } } diff --git a/src/uu/split/src/split.rs b/src/uu/split/src/split.rs index d83408ce6..239df62fb 100644 --- a/src/uu/split/src/split.rs +++ b/src/uu/split/src/split.rs @@ -182,31 +182,31 @@ impl Strategy { matches.occurrences_of(OPT_LINE_BYTES), matches.occurrences_of(OPT_NUMBER), ) { - (0, 0, 0, 0) => Ok(Strategy::Lines(1000)), + (0, 0, 0, 0) => Ok(Self::Lines(1000)), (1, 0, 0, 0) => { let s = matches.value_of(OPT_LINES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of lines: {}", e)))?; - Ok(Strategy::Lines(n)) + Ok(Self::Lines(n)) } (0, 1, 0, 0) => { let s = matches.value_of(OPT_BYTES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; - Ok(Strategy::Bytes(n)) + Ok(Self::Bytes(n)) } (0, 0, 1, 0) => { let s = matches.value_of(OPT_LINE_BYTES).unwrap(); let n = parse_size(s) .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; - Ok(Strategy::LineBytes(n)) + Ok(Self::LineBytes(n)) } (0, 0, 0, 1) => { let s = matches.value_of(OPT_NUMBER).unwrap(); let n = s.parse::().map_err(|e| { USimpleError::new(1, format!("invalid number of chunks: {}", e)) })?; - Ok(Strategy::Number(n)) + Ok(Self::Number(n)) } _ => Err(UUsageError::new(1, "cannot split in more than one way")), } @@ -232,7 +232,7 @@ struct Settings { impl Settings { /// Parse a strategy from the command-line arguments. fn from(matches: ArgMatches) -> UResult { - let result = Settings { + let result = Self { suffix_length: matches .value_of(OPT_SUFFIX_LENGTH) .unwrap() @@ -275,8 +275,8 @@ struct LineSplitter { } impl LineSplitter { - fn new(chunk_size: usize) -> LineSplitter { - LineSplitter { + fn new(chunk_size: usize) -> Self { + Self { lines_per_split: chunk_size, } } @@ -314,8 +314,8 @@ struct ByteSplitter { } impl ByteSplitter { - fn new(chunk_size: usize) -> ByteSplitter { - ByteSplitter { + fn new(chunk_size: usize) -> Self { + Self { bytes_per_split: u128::try_from(chunk_size).unwrap(), } } diff --git a/src/uu/stat/src/stat.rs b/src/uu/stat/src/stat.rs index fd8578faa..e2a0f57ef 100644 --- a/src/uu/stat/src/stat.rs +++ b/src/uu/stat/src/stat.rs @@ -461,7 +461,7 @@ impl Stater { Ok(tokens) } - fn new(matches: &ArgMatches) -> UResult { + fn new(matches: &ArgMatches) -> UResult { let files: Vec = matches .values_of(ARG_FILES) .map(|v| v.map(ToString::to_string).collect()) @@ -480,12 +480,12 @@ impl Stater { let show_fs = matches.is_present(options::FILE_SYSTEM); let default_tokens = if format_str.is_empty() { - Stater::generate_tokens(&Stater::default_format(show_fs, terse, false), use_printf)? + Self::generate_tokens(&Self::default_format(show_fs, terse, false), use_printf)? } else { - Stater::generate_tokens(format_str, use_printf)? + Self::generate_tokens(format_str, use_printf)? }; let default_dev_tokens = - Stater::generate_tokens(&Stater::default_format(show_fs, terse, true), use_printf)?; + Self::generate_tokens(&Self::default_format(show_fs, terse, true), use_printf)?; let mount_list = if show_fs { // mount points aren't displayed when showing filesystem information @@ -501,7 +501,7 @@ impl Stater { Some(mount_list) }; - Ok(Stater { + Ok(Self { follow: matches.is_present(options::DEREFERENCE), show_fs, from_user: !format_str.is_empty(), diff --git a/src/uu/stdbuf/src/stdbuf.rs b/src/uu/stdbuf/src/stdbuf.rs index b0581b3f6..c62873fb3 100644 --- a/src/uu/stdbuf/src/stdbuf.rs +++ b/src/uu/stdbuf/src/stdbuf.rs @@ -70,7 +70,7 @@ impl<'a> TryFrom<&ArgMatches> for ProgramOptions { type Error = ProgramOptionsError; fn try_from(matches: &ArgMatches) -> Result { - Ok(ProgramOptions { + Ok(Self { stdin: check_option(matches, options::INPUT)?, stdout: check_option(matches, options::OUTPUT)?, stderr: check_option(matches, options::ERROR)?, diff --git a/src/uu/tail/src/platform/unix.rs b/src/uu/tail/src/platform/unix.rs index 580a40135..e7f75c31e 100644 --- a/src/uu/tail/src/platform/unix.rs +++ b/src/uu/tail/src/platform/unix.rs @@ -25,8 +25,8 @@ pub struct ProcessChecker { } impl ProcessChecker { - pub fn new(process_id: self::Pid) -> ProcessChecker { - ProcessChecker { pid: process_id } + pub fn new(process_id: self::Pid) -> Self { + Self { pid: process_id } } // Borrowing mutably to be aligned with Windows implementation diff --git a/src/uu/tail/src/tail.rs b/src/uu/tail/src/tail.rs index 54808ed34..951399866 100644 --- a/src/uu/tail/src/tail.rs +++ b/src/uu/tail/src/tail.rs @@ -72,7 +72,7 @@ enum FilterMode { impl Default for FilterMode { fn default() -> Self { - FilterMode::Lines(10, b'\n') + Self::Lines(10, b'\n') } } @@ -92,7 +92,7 @@ impl Settings { pub fn get_from(args: impl uucore::Args) -> Result { let matches = uu_app().get_matches_from(arg_iterate(args)?); - let mut settings: Settings = Settings { + let mut settings: Self = Self { sleep_msec: 1000, follow: matches.is_present(options::FOLLOW), ..Default::default() diff --git a/src/uu/test/src/parser.rs b/src/uu/test/src/parser.rs index ce4c0dec0..d8d7ce802 100644 --- a/src/uu/test/src/parser.rs +++ b/src/uu/test/src/parser.rs @@ -44,26 +44,26 @@ impl Symbol { /// Create a new Symbol from an OsString. /// /// Returns Symbol::None in place of None - fn new(token: Option) -> Symbol { + fn new(token: Option) -> Self { match token { Some(s) => match s.to_str() { Some(t) => match t { - "(" => Symbol::LParen, - "!" => Symbol::Bang, - "-a" | "-o" => Symbol::BoolOp(s), - "=" | "==" | "!=" => Symbol::Op(Operator::String(s)), - "-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Symbol::Op(Operator::Int(s)), - "-ef" | "-nt" | "-ot" => Symbol::Op(Operator::File(s)), - "-n" | "-z" => Symbol::UnaryOp(UnaryOperator::StrlenOp(s)), + "(" => Self::LParen, + "!" => Self::Bang, + "-a" | "-o" => Self::BoolOp(s), + "=" | "==" | "!=" => Self::Op(Operator::String(s)), + "-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Self::Op(Operator::Int(s)), + "-ef" | "-nt" | "-ot" => Self::Op(Operator::File(s)), + "-n" | "-z" => Self::UnaryOp(UnaryOperator::StrlenOp(s)), "-b" | "-c" | "-d" | "-e" | "-f" | "-g" | "-G" | "-h" | "-k" | "-L" | "-O" | "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => { - Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) + Self::UnaryOp(UnaryOperator::FiletestOp(s)) } - _ => Symbol::Literal(s), + _ => Self::Literal(s), }, - None => Symbol::Literal(s), + None => Self::Literal(s), }, - None => Symbol::None, + None => Self::None, } } @@ -74,18 +74,18 @@ impl Symbol { /// # Panics /// /// Panics if `self` is Symbol::None - fn into_literal(self) -> Symbol { - Symbol::Literal(match self { - Symbol::LParen => OsString::from("("), - Symbol::Bang => OsString::from("!"), - Symbol::BoolOp(s) - | Symbol::Literal(s) - | Symbol::Op(Operator::String(s)) - | Symbol::Op(Operator::Int(s)) - | Symbol::Op(Operator::File(s)) - | Symbol::UnaryOp(UnaryOperator::StrlenOp(s)) - | Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) => s, - Symbol::None => panic!(), + fn into_literal(self) -> Self { + Self::Literal(match self { + Self::LParen => OsString::from("("), + Self::Bang => OsString::from("!"), + Self::BoolOp(s) + | Self::Literal(s) + | Self::Op(Operator::String(s)) + | Self::Op(Operator::Int(s)) + | Self::Op(Operator::File(s)) + | Self::UnaryOp(UnaryOperator::StrlenOp(s)) + | Self::UnaryOp(UnaryOperator::FiletestOp(s)) => s, + Self::None => panic!(), }) } } @@ -120,8 +120,8 @@ struct Parser { impl Parser { /// Construct a new Parser from a `Vec` of tokens. - fn new(tokens: Vec) -> Parser { - Parser { + fn new(tokens: Vec) -> Self { + Self { tokens: tokens.into_iter().peekable(), stack: vec![], } diff --git a/src/uu/timeout/src/timeout.rs b/src/uu/timeout/src/timeout.rs index 9a8222dee..2e686f811 100644 --- a/src/uu/timeout/src/timeout.rs +++ b/src/uu/timeout/src/timeout.rs @@ -57,7 +57,7 @@ struct Config { } impl Config { - fn from(options: &clap::ArgMatches) -> Config { + fn from(options: &clap::ArgMatches) -> Self { let signal = match options.value_of(options::SIGNAL) { Some(signal_) => { let signal_result = signal_by_name_or_value(signal_); @@ -88,7 +88,7 @@ impl Config { .map(String::from) .collect::>(); - Config { + Self { foreground, kill_after, signal, diff --git a/src/uu/tr/src/operation.rs b/src/uu/tr/src/operation.rs index 373dec0c2..4d00a0af1 100644 --- a/src/uu/tr/src/operation.rs +++ b/src/uu/tr/src/operation.rs @@ -140,10 +140,10 @@ impl Sequence { set2_str: &str, truncate_set1_flag: bool, ) -> Result<(Vec, Vec), BadSequence> { - let set1 = Sequence::from_str(set1_str)?; - let set2 = Sequence::from_str(set2_str)?; + let set1 = Self::from_str(set1_str)?; + let set2 = Self::from_str(set2_str)?; - let is_char_star = |s: &&Sequence| -> bool { matches!(s, Sequence::CharStar(_)) }; + let is_char_star = |s: &&Self| -> bool { matches!(s, Sequence::CharStar(_)) }; let set1_star_count = set1.iter().filter(is_char_star).count(); if set1_star_count == 0 { let set2_star_count = set2.iter().filter(is_char_star).count(); @@ -152,17 +152,15 @@ impl Sequence { Sequence::CharStar(c) => Some(c), _ => None, }); - let mut partition = set2 - .as_slice() - .split(|s| matches!(s, Sequence::CharStar(_))); - let set1_len = set1.iter().flat_map(Sequence::flatten).count(); + let mut partition = set2.as_slice().split(|s| matches!(s, Self::CharStar(_))); + let set1_len = set1.iter().flat_map(Self::flatten).count(); let set2_len = set2 .iter() .filter_map(|s| match s { Sequence::CharStar(_) => None, r => Some(r), }) - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .count(); let star_compensate_len = set1_len.saturating_sub(set2_len); let (left, right) = (partition.next(), partition.next()); @@ -175,35 +173,35 @@ impl Sequence { if let Some(c) = char_star { std::iter::repeat(*c) .take(star_compensate_len) - .chain(set2_b.iter().flat_map(Sequence::flatten)) + .chain(set2_b.iter().flat_map(Self::flatten)) .collect() } else { - set2_b.iter().flat_map(Sequence::flatten).collect() + set2_b.iter().flat_map(Self::flatten).collect() } } (Some(set2_a), None) => match char_star { Some(c) => set2_a .iter() - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .chain(std::iter::repeat(*c).take(star_compensate_len)) .collect(), - None => set2_a.iter().flat_map(Sequence::flatten).collect(), + None => set2_a.iter().flat_map(Self::flatten).collect(), }, (Some(set2_a), Some(set2_b)) => match char_star { Some(c) => set2_a .iter() - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .chain(std::iter::repeat(*c).take(star_compensate_len)) - .chain(set2_b.iter().flat_map(Sequence::flatten)) + .chain(set2_b.iter().flat_map(Self::flatten)) .collect(), None => set2_a .iter() .chain(set2_b.iter()) - .flat_map(Sequence::flatten) + .flat_map(Self::flatten) .collect(), }, }; - let mut set1_solved: Vec = set1.iter().flat_map(Sequence::flatten).collect(); + let mut set1_solved: Vec = set1.iter().flat_map(Self::flatten).collect(); if truncate_set1_flag { set1_solved.truncate(set2_solved.len()); } @@ -218,15 +216,15 @@ impl Sequence { } impl Sequence { - pub fn from_str(input: &str) -> Result, BadSequence> { + pub fn from_str(input: &str) -> Result, BadSequence> { many0(alt(( - Sequence::parse_char_range, - Sequence::parse_char_star, - Sequence::parse_char_repeat, - Sequence::parse_class, - Sequence::parse_char_equal, + Self::parse_char_range, + Self::parse_char_star, + Self::parse_char_repeat, + Self::parse_class, + Self::parse_char_equal, // NOTE: This must be the last one - map(Sequence::parse_backslash_or_char, |s| Ok(Sequence::Char(s))), + map(Self::parse_backslash_or_char, |s| Ok(Self::Char(s))), )))(input) .map(|(_, r)| r) .unwrap() @@ -251,64 +249,64 @@ impl Sequence { } fn parse_backslash_or_char(input: &str) -> IResult<&str, char> { - alt((Sequence::parse_backslash, anychar))(input) + alt((Self::parse_backslash, anychar))(input) } - fn parse_char_range(input: &str) -> IResult<&str, Result> { + fn parse_char_range(input: &str) -> IResult<&str, Result> { separated_pair( - Sequence::parse_backslash_or_char, + Self::parse_backslash_or_char, tag("-"), - Sequence::parse_backslash_or_char, + Self::parse_backslash_or_char, )(input) .map(|(l, (a, b))| { (l, { let (start, end) = (u32::from(a), u32::from(b)); - Ok(Sequence::CharRange(start, end)) + Ok(Self::CharRange(start, end)) }) }) } - fn parse_char_star(input: &str) -> IResult<&str, Result> { - delimited(tag("["), Sequence::parse_backslash_or_char, tag("*]"))(input) - .map(|(l, a)| (l, Ok(Sequence::CharStar(a)))) + fn parse_char_star(input: &str) -> IResult<&str, Result> { + delimited(tag("["), Self::parse_backslash_or_char, tag("*]"))(input) + .map(|(l, a)| (l, Ok(Self::CharStar(a)))) } - fn parse_char_repeat(input: &str) -> IResult<&str, Result> { + fn parse_char_repeat(input: &str) -> IResult<&str, Result> { delimited( tag("["), - separated_pair(Sequence::parse_backslash_or_char, tag("*"), digit1), + separated_pair(Self::parse_backslash_or_char, tag("*"), digit1), tag("]"), )(input) .map(|(l, (c, str))| { ( l, match usize::from_str_radix(str, 8) { - Ok(0) => Ok(Sequence::CharStar(c)), - Ok(count) => Ok(Sequence::CharRepeat(c, count)), + Ok(0) => Ok(Self::CharStar(c)), + Ok(count) => Ok(Self::CharRepeat(c, count)), Err(_) => Err(BadSequence::InvalidRepeatCount(str.to_string())), }, ) }) } - fn parse_class(input: &str) -> IResult<&str, Result> { + fn parse_class(input: &str) -> IResult<&str, Result> { delimited( tag("[:"), alt(( map( alt(( - value(Sequence::Alnum, tag("alnum")), - value(Sequence::Alpha, tag("alpha")), - value(Sequence::Blank, tag("blank")), - value(Sequence::Control, tag("cntrl")), - value(Sequence::Digit, tag("digit")), - value(Sequence::Graph, tag("graph")), - value(Sequence::Lower, tag("lower")), - value(Sequence::Print, tag("print")), - value(Sequence::Punct, tag("punct")), - value(Sequence::Space, tag("space")), - value(Sequence::Upper, tag("upper")), - value(Sequence::Xdigit, tag("xdigit")), + value(Self::Alnum, tag("alnum")), + value(Self::Alpha, tag("alpha")), + value(Self::Blank, tag("blank")), + value(Self::Control, tag("cntrl")), + value(Self::Digit, tag("digit")), + value(Self::Graph, tag("graph")), + value(Self::Lower, tag("lower")), + value(Self::Print, tag("print")), + value(Self::Punct, tag("punct")), + value(Self::Space, tag("space")), + value(Self::Upper, tag("upper")), + value(Self::Xdigit, tag("xdigit")), )), Ok, ), @@ -318,7 +316,7 @@ impl Sequence { )(input) } - fn parse_char_equal(input: &str) -> IResult<&str, Result> { + fn parse_char_equal(input: &str) -> IResult<&str, Result> { delimited( tag("[="), alt(( @@ -326,7 +324,7 @@ impl Sequence { Err(BadSequence::MissingEquivalentClassChar), peek(tag("=]")), ), - map(Sequence::parse_backslash_or_char, |c| Ok(Sequence::Char(c))), + map(Self::parse_backslash_or_char, |c| Ok(Self::Char(c))), )), tag("=]"), )(input) @@ -344,8 +342,8 @@ pub struct DeleteOperation { } impl DeleteOperation { - pub fn new(set: Vec, complement_flag: bool) -> DeleteOperation { - DeleteOperation { + pub fn new(set: Vec, complement_flag: bool) -> Self { + Self { set, complement_flag, } @@ -372,8 +370,8 @@ pub struct TranslateOperationComplement { } impl TranslateOperationComplement { - fn new(set1: Vec, set2: Vec) -> TranslateOperationComplement { - TranslateOperationComplement { + fn new(set1: Vec, set2: Vec) -> Self { + Self { iter: 0, set2_iter: 0, set1, @@ -389,16 +387,16 @@ pub struct TranslateOperationStandard { } impl TranslateOperationStandard { - fn new(set1: Vec, set2: Vec) -> Result { + fn new(set1: Vec, set2: Vec) -> Result { if let Some(fallback) = set2.last().copied() { - Ok(TranslateOperationStandard { + Ok(Self { translation_map: set1 .into_iter() .zip(set2.into_iter().chain(std::iter::repeat(fallback))) .collect::>(), }) } else if set1.is_empty() && set2.is_empty() { - Ok(TranslateOperationStandard { + Ok(Self { translation_map: HashMap::new(), }) } else { @@ -424,19 +422,13 @@ impl TranslateOperation { } impl TranslateOperation { - pub fn new( - set1: Vec, - set2: Vec, - complement: bool, - ) -> Result { + pub fn new(set1: Vec, set2: Vec, complement: bool) -> Result { if complement { - Ok(TranslateOperation::Complement( - TranslateOperationComplement::new(set1, set2), - )) + Ok(Self::Complement(TranslateOperationComplement::new( + set1, set2, + ))) } else { - Ok(TranslateOperation::Standard( - TranslateOperationStandard::new(set1, set2)?, - )) + Ok(Self::Standard(TranslateOperationStandard::new(set1, set2)?)) } } } @@ -444,13 +436,13 @@ impl TranslateOperation { impl SymbolTranslator for TranslateOperation { fn translate(&mut self, current: char) -> Option { match self { - TranslateOperation::Standard(TranslateOperationStandard { translation_map }) => Some( + Self::Standard(TranslateOperationStandard { translation_map }) => Some( translation_map .iter() .find_map(|(l, r)| if l.eq(¤t) { Some(*r) } else { None }) .unwrap_or(current), ), - TranslateOperation::Complement(TranslateOperationComplement { + Self::Complement(TranslateOperationComplement { iter, set2_iter, set1, @@ -467,8 +459,7 @@ impl SymbolTranslator for TranslateOperation { } else { while translation_map.get(¤t).is_none() { if let Some(value) = set2.get(*set2_iter) { - let (next_iter, next_key) = - TranslateOperation::next_complement_char(*iter, &*set1); + let (next_iter, next_key) = Self::next_complement_char(*iter, &*set1); *iter = next_iter; *set2_iter = set2_iter.saturating_add(1); translation_map.insert(next_key, *value); @@ -491,8 +482,8 @@ pub struct SqueezeOperation { } impl SqueezeOperation { - pub fn new(set1: Vec, complement: bool) -> SqueezeOperation { - SqueezeOperation { + pub fn new(set1: Vec, complement: bool) -> Self { + Self { set1: set1.into_iter().collect(), complement, previous: None, diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index c50b695ac..069d6dc4f 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -104,6 +104,7 @@ pub fn uu_app<'a>() -> App<'a> { // We use String as a representation of node here // but using integer may improve performance. +#[derive(Default)] struct Graph { in_edges: HashMap>, out_edges: HashMap>, @@ -111,12 +112,8 @@ struct Graph { } impl Graph { - fn new() -> Graph { - Graph { - in_edges: HashMap::new(), - out_edges: HashMap::new(), - result: vec![], - } + fn new() -> Self { + Self::default() } fn has_node(&self, n: &str) -> bool { diff --git a/src/uu/unexpand/src/unexpand.rs b/src/uu/unexpand/src/unexpand.rs index 3b419d854..dc1d0c800 100644 --- a/src/uu/unexpand/src/unexpand.rs +++ b/src/uu/unexpand/src/unexpand.rs @@ -67,7 +67,7 @@ struct Options { } impl Options { - fn new(matches: &clap::ArgMatches) -> Options { + fn new(matches: &clap::ArgMatches) -> Self { let tabstops = match matches.value_of(options::TABS) { None => vec![DEFAULT_TABSTOP], Some(s) => tabstops_parse(s), @@ -82,7 +82,7 @@ impl Options { None => vec!["-".to_owned()], }; - Options { + Self { files, tabstops, aflag, diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index d8782e62d..6a96d425b 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -39,8 +39,8 @@ struct Settings { } impl Settings { - fn new(matches: &ArgMatches) -> Settings { - let settings = Settings { + fn new(matches: &ArgMatches) -> Self { + let settings = Self { show_bytes: matches.is_present(options::BYTES), show_chars: matches.is_present(options::CHAR), show_lines: matches.is_present(options::LINES), @@ -57,7 +57,7 @@ impl Settings { return settings; } - Settings { + Self { show_bytes: true, show_chars: false, show_lines: true, diff --git a/src/uu/yes/src/splice.rs b/src/uu/yes/src/splice.rs index 84bd1cc24..f77a09ed6 100644 --- a/src/uu/yes/src/splice.rs +++ b/src/uu/yes/src/splice.rs @@ -55,7 +55,7 @@ type Result = std::result::Result; impl From for Error { fn from(error: nix::Error) -> Self { - Error::Io(io::Error::from_raw_os_error(error as i32)) + Self::Io(io::Error::from_raw_os_error(error as i32)) } } diff --git a/src/uucore/src/lib/features/encoding.rs b/src/uucore/src/lib/features/encoding.rs index b36e6a6a0..e99017070 100644 --- a/src/uucore/src/lib/features/encoding.rs +++ b/src/uucore/src/lib/features/encoding.rs @@ -107,7 +107,7 @@ pub struct Data { impl Data { pub fn new(input: R, format: Format) -> Self { - Data { + Self { line_wrap: 76, ignore_garbage: false, input, diff --git a/src/uucore/src/lib/features/entries.rs b/src/uucore/src/lib/features/entries.rs index 60fa6a3da..90f3134ab 100644 --- a/src/uucore/src/lib/features/entries.rs +++ b/src/uucore/src/lib/features/entries.rs @@ -175,7 +175,7 @@ impl Passwd { /// SAFETY: All the pointed-to strings must be valid and not change while /// the function runs. That means PW_LOCK must be held. unsafe fn from_raw(raw: passwd) -> Self { - Passwd { + Self { name: cstr2string(raw.pw_name), uid: raw.pw_uid, gid: raw.pw_gid, @@ -243,7 +243,7 @@ impl Group { /// SAFETY: gr_name must be valid and not change while /// the function runs. That means PW_LOCK must be held. unsafe fn from_raw(raw: group) -> Self { - Group { + Self { name: cstr2string(raw.gr_name), gid: raw.gr_gid, } diff --git a/src/uucore/src/lib/features/fsext.rs b/src/uucore/src/lib/features/fsext.rs index 8ba7f8fc0..d1e623757 100644 --- a/src/uucore/src/lib/features/fsext.rs +++ b/src/uucore/src/lib/features/fsext.rs @@ -197,7 +197,7 @@ impl MountInfo { } #[cfg(target_os = "linux")] - fn new(file_name: &str, raw: &[&str]) -> Option { + fn new(file_name: &str, raw: &[&str]) -> Option { match file_name { // spell-checker:ignore (word) noatime // Format: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue @@ -207,7 +207,7 @@ impl MountInfo { let after_fields = raw[FIELDS_OFFSET..].iter().position(|c| *c == "-").unwrap() + FIELDS_OFFSET + 1; - let mut m = MountInfo { + let mut m = Self { dev_id: "".to_string(), dev_name: raw[after_fields + 1].to_string(), fs_type: raw[after_fields].to_string(), @@ -221,7 +221,7 @@ impl MountInfo { Some(m) } LINUX_MTAB => { - let mut m = MountInfo { + let mut m = Self { dev_id: "".to_string(), dev_name: raw[0].to_string(), fs_type: raw[2].to_string(), @@ -496,9 +496,9 @@ pub struct FsUsage { impl FsUsage { #[cfg(unix)] - pub fn new(statvfs: StatFs) -> FsUsage { + pub fn new(statvfs: StatFs) -> Self { { - FsUsage { + Self { blocksize: statvfs.f_bsize as u64, // or `statvfs.f_frsize` ? blocks: statvfs.f_blocks as u64, bfree: statvfs.f_bfree as u64, @@ -510,7 +510,7 @@ impl FsUsage { } } #[cfg(not(unix))] - pub fn new(path: &Path) -> FsUsage { + pub fn new(path: &Path) -> Self { let mut root_path = [0u16; MAX_PATH]; let success = unsafe { GetVolumePathNamesForVolumeNameW( diff --git a/src/uucore/src/lib/features/memo.rs b/src/uucore/src/lib/features/memo.rs index f2d1a33d9..fd57c33b5 100644 --- a/src/uucore/src/lib/features/memo.rs +++ b/src/uucore/src/lib/features/memo.rs @@ -26,8 +26,8 @@ fn warn_excess_args(first_arg: &str) { } impl Memo { - pub fn new(pf_string: &str, pf_args_it: &mut Peekable>) -> Memo { - let mut pm = Memo { tokens: Vec::new() }; + pub fn new(pf_string: &str, pf_args_it: &mut Peekable>) -> Self { + let mut pm = Self { tokens: Vec::new() }; let mut tmp_token: Option>; let mut it = put_back_n(pf_string.chars()); let mut has_sub = false; @@ -73,7 +73,7 @@ impl Memo { } pub fn run_all(pf_string: &str, pf_args: &[String]) { let mut arg_it = pf_args.iter().peekable(); - let pm = Memo::new(pf_string, &mut arg_it); + let pm = Self::new(pf_string, &mut arg_it); loop { if arg_it.peek().is_none() { break; diff --git a/src/uucore/src/lib/features/process.rs b/src/uucore/src/lib/features/process.rs index d0f530a5a..b573fdfcc 100644 --- a/src/uucore/src/lib/features/process.rs +++ b/src/uucore/src/lib/features/process.rs @@ -56,12 +56,12 @@ impl ExitStatus { use std::os::unix::process::ExitStatusExt; if let Some(signal) = status.signal() { - return ExitStatus::Signal(signal); + return Self::Signal(signal); } } // NOTE: this should never fail as we check if the program exited through a signal above - ExitStatus::Code(status.code().unwrap()) + Self::Code(status.code().unwrap()) } pub fn success(&self) -> bool { diff --git a/src/uucore/src/lib/features/ringbuffer.rs b/src/uucore/src/lib/features/ringbuffer.rs index 772336ef1..08073fae0 100644 --- a/src/uucore/src/lib/features/ringbuffer.rs +++ b/src/uucore/src/lib/features/ringbuffer.rs @@ -42,15 +42,15 @@ pub struct RingBuffer { } impl RingBuffer { - pub fn new(size: usize) -> RingBuffer { - RingBuffer { + pub fn new(size: usize) -> Self { + Self { data: VecDeque::new(), size, } } - pub fn from_iter(iter: impl Iterator, size: usize) -> RingBuffer { - let mut ring_buffer = RingBuffer::new(size); + pub fn from_iter(iter: impl Iterator, size: usize) -> Self { + let mut ring_buffer = Self::new(size); for value in iter { ring_buffer.push_back(value); } diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs index 68b35c3c1..85396a2aa 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/cninetyninehexfloatf.rs @@ -8,13 +8,14 @@ use super::base_conv; use super::base_conv::RadixDef; use super::float_common::{primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct CninetyNineHexFloatf { #[allow(dead_code)] as_num: f64, } impl CninetyNineHexFloatf { - pub fn new() -> CninetyNineHexFloatf { - CninetyNineHexFloatf { as_num: 0.0 } + pub fn new() -> Self { + Self::default() } } diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs index 3376345e0..52b8515c9 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/decf.rs @@ -25,8 +25,8 @@ fn get_len_fmt_primitive(fmt: &FormatPrimitive) -> usize { pub struct Decf; impl Decf { - pub fn new() -> Decf { - Decf + pub fn new() -> Self { + Self } } impl Formatter for Decf { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs index 95b0e34e6..e62245534 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/float_common.rs @@ -46,12 +46,12 @@ impl FloatAnalysis { max_sd_opt: Option, max_after_dec_opt: Option, hex_output: bool, - ) -> FloatAnalysis { + ) -> Self { // this fn assumes // the input string // has no leading spaces or 0s let str_it = get_it_at(initial_prefix.offset, str_in); - let mut ret = FloatAnalysis { + let mut ret = Self { len_important: 0, decimal_pos: None, follow: None, diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs index afb2bcf08..e13629af5 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/floatf.rs @@ -6,10 +6,11 @@ use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct Floatf; impl Floatf { - pub fn new() -> Floatf { - Floatf + pub fn new() -> Self { + Self::default() } } impl Formatter for Floatf { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs index b6c18d436..0b93d134c 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/intf.rs @@ -11,6 +11,7 @@ use super::super::formatter::{ use std::i64; use std::u64; +#[derive(Default)] pub struct Intf { _a: u32, } @@ -24,8 +25,8 @@ struct IntAnalysis { } impl Intf { - pub fn new() -> Intf { - Intf { _a: 0 } + pub fn new() -> Self { + Self::default() } // take a ref to argument string, and basic information // about prefix (offset, radix, sign), and analyze string @@ -166,7 +167,7 @@ impl Intf { fmt_prim.pre_decimal = Some(format!("{}", i)); fmt_prim } - Err(_) => Intf::get_max(field_char, sign), + Err(_) => Self::get_max(field_char, sign), }, _ => match u64::from_str_radix(segment, radix_in as u32) { Ok(u) => { @@ -180,7 +181,7 @@ impl Intf { }); fmt_prim } - Err(_) => Intf::get_max(field_char, sign), + Err(_) => Self::get_max(field_char, sign), }, } } @@ -196,7 +197,7 @@ impl Formatter for Intf { // get information about the string. see Intf::Analyze // def above. - let convert_hints = Intf::analyze( + let convert_hints = Self::analyze( str_in, *field.field_char == 'i' || *field.field_char == 'd', initial_prefix, @@ -226,7 +227,7 @@ impl Formatter for Intf { if convert_hints.check_past_max || decrease_from_max || radix_mismatch { // radix of in and out is the same. let segment = String::from(&str_in[begin..end]); - Intf::conv_from_segment( + Self::conv_from_segment( &segment, initial_prefix.radix_in.clone(), *field.field_char, @@ -246,7 +247,7 @@ impl Formatter for Intf { fmt_prim } } else { - Intf::get_max(*field.field_char, initial_prefix.sign) + Self::get_max(*field.field_char, initial_prefix.sign) }) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { diff --git a/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs b/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs index c46c7d423..c5b88b5a7 100644 --- a/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs +++ b/src/uucore/src/lib/features/tokenize/num_format/formatters/scif.rs @@ -5,11 +5,12 @@ use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; +#[derive(Default)] pub struct Scif; impl Scif { - pub fn new() -> Scif { - Scif + pub fn new() -> Self { + Self::default() } } impl Formatter for Scif { diff --git a/src/uucore/src/lib/features/tokenize/sub.rs b/src/uucore/src/lib/features/tokenize/sub.rs index 0c3a68c3c..6f9196d93 100644 --- a/src/uucore/src/lib/features/tokenize/sub.rs +++ b/src/uucore/src/lib/features/tokenize/sub.rs @@ -67,7 +67,7 @@ impl Sub { second_field: CanAsterisk>, field_char: char, orig: String, - ) -> Sub { + ) -> Self { // for more dry printing, field characters are grouped // in initialization of token. let field_type = match field_char { @@ -84,7 +84,7 @@ impl Sub { exit(EXIT_ERR); } }; - Sub { + Self { min_width, second_field, field_char, @@ -94,6 +94,7 @@ impl Sub { } } +#[derive(Default)] struct SubParser { min_width_tmp: Option, min_width_is_asterisk: bool, @@ -106,32 +107,23 @@ struct SubParser { } impl SubParser { - fn new() -> SubParser { - SubParser { - min_width_tmp: None, - min_width_is_asterisk: false, - past_decimal: false, - second_field_tmp: None, - second_field_is_asterisk: false, - specifiers_found: false, - field_char: None, - text_so_far: String::new(), - } + fn new() -> Self { + Self::default() } fn from_it( it: &mut PutBackN, args: &mut Peekable>, ) -> Option> { - let mut parser = SubParser::new(); + let mut parser = Self::new(); if parser.sub_vals_retrieved(it) { - let t: Box = SubParser::build_token(parser); + let t: Box = Self::build_token(parser); t.print(args); Some(t) } else { None } } - fn build_token(parser: SubParser) -> Box { + fn build_token(parser: Self) -> Box { // not a self method so as to allow move of sub-parser vals. // return new Sub struct as token let t: Box = Box::new(Sub::new( @@ -151,7 +143,7 @@ impl SubParser { t } fn sub_vals_retrieved(&mut self, it: &mut PutBackN) -> bool { - if !SubParser::successfully_eat_prefix(it, &mut self.text_so_far) { + if !Self::successfully_eat_prefix(it, &mut self.text_so_far) { return false; } // this fn in particular is much longer than it needs to be diff --git a/src/uucore/src/lib/features/tokenize/unescaped_text.rs b/src/uucore/src/lib/features/tokenize/unescaped_text.rs index a192c757b..0ec721b48 100644 --- a/src/uucore/src/lib/features/tokenize/unescaped_text.rs +++ b/src/uucore/src/lib/features/tokenize/unescaped_text.rs @@ -35,10 +35,11 @@ fn flush_bytes(bslice: &[u8]) { let _ = stdout().flush(); } +#[derive(Default)] pub struct UnescapedText(Vec); impl UnescapedText { - fn new() -> UnescapedText { - UnescapedText(Vec::new()) + fn new() -> Self { + Self::default() } // take an iterator to the format string // consume between min and max chars @@ -133,7 +134,7 @@ impl UnescapedText { _ => {} } if !ignore { - let val = (UnescapedText::base_to_u32(min_len, max_len, base, it) % 256) as u8; + let val = (Self::base_to_u32(min_len, max_len, base, it) % 256) as u8; byte_vec.push(val); let bvec = [val]; flush_bytes(&bvec); @@ -170,8 +171,8 @@ impl UnescapedText { 'u' => 4, /* 'U' | */ _ => 8, }; - let val = UnescapedText::base_to_u32(len, len, 16, it); - UnescapedText::validate_iec(val, false); + let val = Self::base_to_u32(len, len, 16, it); + Self::validate_iec(val, false); if let Some(c) = from_u32(val) { c } else { @@ -199,7 +200,7 @@ impl UnescapedText { subs_mode: bool, ) -> Option> { let mut addchar = false; - let mut new_text = UnescapedText::new(); + let mut new_text = Self::new(); let mut tmp_str = String::new(); { let new_vec: &mut Vec = &mut (new_text.0); @@ -227,7 +228,7 @@ impl UnescapedText { new_vec.extend(tmp_str.bytes()); tmp_str = String::new(); } - UnescapedText::handle_escaped(new_vec, it, subs_mode); + Self::handle_escaped(new_vec, it, subs_mode); } x if x == '%' && !subs_mode => { if let Some(follow) = it.next() { @@ -266,7 +267,7 @@ impl token::Tokenizer for UnescapedText { it: &mut PutBackN, _: &mut Peekable>, ) -> Option> { - UnescapedText::from_it_core(it, false) + Self::from_it_core(it, false) } } impl token::Token for UnescapedText { diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index a3078b818..c82fd35ef 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -322,7 +322,7 @@ impl UtmpxIter { fn new() -> Self { // PoisonErrors can safely be ignored let guard = LOCK.lock().unwrap_or_else(|err| err.into_inner()); - UtmpxIter { + Self { guard, phantom: PhantomData, } diff --git a/src/uucore/src/lib/mods/error.rs b/src/uucore/src/lib/mods/error.rs index 24de6434b..ba7722f1c 100644 --- a/src/uucore/src/lib/mods/error.rs +++ b/src/uucore/src/lib/mods/error.rs @@ -265,7 +265,7 @@ impl From for Box where T: UError + 'static, { - fn from(t: T) -> Box { + fn from(t: T) -> Self { Box::new(t) } } @@ -490,8 +490,8 @@ impl FromIo> for std::io::ErrorKind { } impl From for UIoError { - fn from(f: std::io::Error) -> UIoError { - UIoError { + fn from(f: std::io::Error) -> Self { + Self { context: None, inner: f, } @@ -499,9 +499,9 @@ impl From for UIoError { } impl From for Box { - fn from(f: std::io::Error) -> Box { + fn from(f: std::io::Error) -> Self { let u_error: UIoError = f.into(); - Box::new(u_error) as Box + Box::new(u_error) as Self } } diff --git a/src/uucore/src/lib/mods/ranges.rs b/src/uucore/src/lib/mods/ranges.rs index f142e14fb..822c09e02 100644 --- a/src/uucore/src/lib/mods/ranges.rs +++ b/src/uucore/src/lib/mods/ranges.rs @@ -20,7 +20,7 @@ pub struct Range { impl FromStr for Range { type Err = &'static str; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { use std::usize::MAX; let mut parts = s.splitn(2, '-'); @@ -33,7 +33,7 @@ impl FromStr for Range { (Some(nm), None) => { if let Ok(nm) = nm.parse::() { if nm > 0 { - Ok(Range { low: nm, high: nm }) + Ok(Self { low: nm, high: nm }) } else { Err(field) } @@ -44,7 +44,7 @@ impl FromStr for Range { (Some(n), Some(m)) if m.is_empty() => { if let Ok(low) = n.parse::() { if low > 0 { - Ok(Range { low, high: MAX - 1 }) + Ok(Self { low, high: MAX - 1 }) } else { Err(field) } @@ -55,7 +55,7 @@ impl FromStr for Range { (Some(n), Some(m)) if n.is_empty() => { if let Ok(high) = m.parse::() { if high > 0 { - Ok(Range { low: 1, high }) + Ok(Self { low: 1, high }) } else { Err(field) } @@ -66,7 +66,7 @@ impl FromStr for Range { (Some(n), Some(m)) => match (n.parse::(), m.parse::()) { (Ok(low), Ok(high)) => { if low > 0 && low <= high { - Ok(Range { low, high }) + Ok(Self { low, high }) } else if low == 0 { Err(field) } else { @@ -81,10 +81,10 @@ impl FromStr for Range { } impl Range { - pub fn from_list(list: &str) -> Result, String> { + pub fn from_list(list: &str) -> Result, String> { use std::cmp::max; - let mut ranges: Vec = vec![]; + let mut ranges: Vec = vec![]; for item in list.split(',') { let range_item = FromStr::from_str(item) diff --git a/src/uucore/src/lib/parser/parse_size.rs b/src/uucore/src/lib/parser/parse_size.rs index c05c0d3f1..797daebbb 100644 --- a/src/uucore/src/lib/parser/parse_size.rs +++ b/src/uucore/src/lib/parser/parse_size.rs @@ -113,7 +113,7 @@ impl fmt::Display for ParseSizeError { // but there's a lot of downstream code that constructs these errors manually // that would be affected impl ParseSizeError { - fn parse_failure(s: &str) -> ParseSizeError { + fn parse_failure(s: &str) -> Self { // stderr on linux (GNU coreutils 8.32) (LC_ALL=C) // has to be handled in the respective uutils because strings differ, e.g.: // @@ -145,10 +145,10 @@ impl ParseSizeError { // --width // --strings // etc. - ParseSizeError::ParseFailure(format!("{}", s.quote())) + Self::ParseFailure(format!("{}", s.quote())) } - fn size_too_big(s: &str) -> ParseSizeError { + fn size_too_big(s: &str) -> Self { // stderr on linux (GNU coreutils 8.32) (LC_ALL=C) // has to be handled in the respective uutils because strings differ, e.g.: // @@ -165,7 +165,7 @@ impl ParseSizeError { // stderr on macos (brew - GNU coreutils 8.32) also differs for the same version, e.g.: // ghead: invalid number of bytes: '1Y': Value too large to be stored in data type // gtail: invalid number of bytes: '1Y': Value too large to be stored in data type - ParseSizeError::SizeTooBig(format!( + Self::SizeTooBig(format!( "{}: Value too large for defined data type", s.quote() )) diff --git a/tests/by-util/test_kill.rs b/tests/by-util/test_kill.rs index 40b9cec67..7581086a0 100644 --- a/tests/by-util/test_kill.rs +++ b/tests/by-util/test_kill.rs @@ -13,8 +13,8 @@ impl Target { // Creates a target that will naturally die after some time if not killed // fast enough. // This timeout avoids hanging failing tests. - fn new() -> Target { - Target { + fn new() -> Self { + Self { child: Command::new("sleep") .arg("30") .spawn() diff --git a/tests/by-util/test_split.rs b/tests/by-util/test_split.rs index 2005c0235..8e61c5153 100644 --- a/tests/by-util/test_split.rs +++ b/tests/by-util/test_split.rs @@ -32,8 +32,8 @@ struct Glob { } impl Glob { - fn new(at: &AtPath, directory: &str, regex: &str) -> Glob { - Glob { + fn new(at: &AtPath, directory: &str, regex: &str) -> Self { + Self { directory: AtPath::new(Path::new(&at.plus_as_string(directory))), regex: Regex::new(regex).unwrap(), } @@ -83,8 +83,8 @@ impl RandomFile { const LINESIZE: usize = 32; /// `create()` file handle located at `at` / `name` - fn new(at: &AtPath, name: &str) -> RandomFile { - RandomFile { + fn new(at: &AtPath, name: &str) -> Self { + Self { inner: File::create(&at.plus(name)).unwrap(), } } @@ -113,7 +113,7 @@ impl RandomFile { fn add_lines(&mut self, lines: usize) { let mut n = lines; while n > 0 { - writeln!(self.inner, "{}", random_chars(RandomFile::LINESIZE)).unwrap(); + writeln!(self.inner, "{}", random_chars(Self::LINESIZE)).unwrap(); n -= 1; } } diff --git a/tests/common/util.rs b/tests/common/util.rs index 5b293c216..d21aea968 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -88,8 +88,8 @@ impl CmdResult { success: bool, stdout: &[u8], stderr: &[u8], - ) -> CmdResult { - CmdResult { + ) -> Self { + Self { bin_path, util_name, tmpd, @@ -150,7 +150,7 @@ impl CmdResult { self.code.expect("Program must be run first") } - pub fn code_is(&self, expected_code: i32) -> &CmdResult { + pub fn code_is(&self, expected_code: i32) -> &Self { assert_eq!(self.code(), expected_code); self } @@ -170,7 +170,7 @@ impl CmdResult { } /// asserts that the command resulted in a success (zero) status code - pub fn success(&self) -> &CmdResult { + pub fn success(&self) -> &Self { assert!( self.success, "Command was expected to succeed.\nstdout = {}\n stderr = {}", @@ -181,7 +181,7 @@ impl CmdResult { } /// asserts that the command resulted in a failure (non-zero) status code - pub fn failure(&self) -> &CmdResult { + pub fn failure(&self) -> &Self { assert!( !self.success, "Command was expected to fail.\nstdout = {}\n stderr = {}", @@ -192,7 +192,7 @@ impl CmdResult { } /// asserts that the command's exit code is the same as the given one - pub fn status_code(&self, code: i32) -> &CmdResult { + pub fn status_code(&self, code: i32) -> &Self { assert_eq!(self.code, Some(code)); self } @@ -202,7 +202,7 @@ impl CmdResult { /// but you might find yourself using this function if /// 1. you can not know exactly what stdout will be or /// 2. you know that stdout will also be empty - pub fn no_stderr(&self) -> &CmdResult { + pub fn no_stderr(&self) -> &Self { assert!( self.stderr.is_empty(), "Expected stderr to be empty, but it's:\n{}", @@ -217,7 +217,7 @@ impl CmdResult { /// but you might find yourself using this function if /// 1. you can not know exactly what stderr will be or /// 2. you know that stderr will also be empty - pub fn no_stdout(&self) -> &CmdResult { + pub fn no_stdout(&self) -> &Self { assert!( self.stdout.is_empty(), "Expected stdout to be empty, but it's:\n{}", @@ -229,13 +229,13 @@ impl CmdResult { /// asserts that the command resulted in stdout stream output that equals the /// passed in value, trailing whitespace are kept to force strict comparison (#1235) /// stdout_only is a better choice unless stderr may or will be non-empty - pub fn stdout_is>(&self, msg: T) -> &CmdResult { + pub fn stdout_is>(&self, msg: T) -> &Self { assert_eq!(self.stdout_str(), String::from(msg.as_ref())); self } /// like `stdout_is`, but succeeds if any elements of `expected` matches stdout. - pub fn stdout_is_any + std::fmt::Debug>(&self, expected: &[T]) -> &CmdResult { + pub fn stdout_is_any + std::fmt::Debug>(&self, expected: &[T]) -> &Self { if !expected.iter().any(|msg| self.stdout_str() == msg.as_ref()) { panic!( "stdout was {}\nExpected any of {:#?}", @@ -247,7 +247,7 @@ impl CmdResult { } /// Like `stdout_is` but newlines are normalized to `\n`. - pub fn normalized_newlines_stdout_is>(&self, msg: T) -> &CmdResult { + pub fn normalized_newlines_stdout_is>(&self, msg: T) -> &Self { let msg = msg.as_ref().replace("\r\n", "\n"); assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg); self @@ -255,13 +255,13 @@ impl CmdResult { /// asserts that the command resulted in stdout stream output, /// whose bytes equal those of the passed in slice - pub fn stdout_is_bytes>(&self, msg: T) -> &CmdResult { + pub fn stdout_is_bytes>(&self, msg: T) -> &Self { assert_eq!(self.stdout, msg.as_ref()); self } /// like stdout_is(...), but expects the contents of the file at the provided relative path - pub fn stdout_is_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stdout_is_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_is(String::from_utf8(contents).unwrap()) } @@ -271,7 +271,7 @@ impl CmdResult { &self, file_rel_path: T, template_vars: &[(&str, &str)], - ) -> &CmdResult { + ) -> &Self { let mut contents = String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap(); for kv in template_vars { @@ -300,7 +300,7 @@ impl CmdResult { /// asserts that the command resulted in stderr stream output that equals the /// passed in value, when both are trimmed of trailing whitespace /// stderr_only is a better choice unless stdout may or will be non-empty - pub fn stderr_is>(&self, msg: T) -> &CmdResult { + pub fn stderr_is>(&self, msg: T) -> &Self { assert_eq!( self.stderr_str().trim_end(), String::from(msg.as_ref()).trim_end() @@ -310,13 +310,13 @@ impl CmdResult { /// asserts that the command resulted in stderr stream output, /// whose bytes equal those of the passed in slice - pub fn stderr_is_bytes>(&self, msg: T) -> &CmdResult { + pub fn stderr_is_bytes>(&self, msg: T) -> &Self { assert_eq!(self.stderr, msg.as_ref()); self } /// Like stdout_is_fixture, but for stderr - pub fn stderr_is_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stderr_is_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stderr_is(String::from_utf8(contents).unwrap()) } @@ -325,7 +325,7 @@ impl CmdResult { /// 1. the command resulted in stdout stream output that equals the /// passed in value /// 2. the command resulted in empty (zero-length) stderr stream output - pub fn stdout_only>(&self, msg: T) -> &CmdResult { + pub fn stdout_only>(&self, msg: T) -> &Self { self.no_stderr().stdout_is(msg) } @@ -333,12 +333,12 @@ impl CmdResult { /// 1. the command resulted in a stdout stream whose bytes /// equal those of the passed in value /// 2. the command resulted in an empty stderr stream - pub fn stdout_only_bytes>(&self, msg: T) -> &CmdResult { + pub fn stdout_only_bytes>(&self, msg: T) -> &Self { self.no_stderr().stdout_is_bytes(msg) } /// like stdout_only(...), but expects the contents of the file at the provided relative path - pub fn stdout_only_fixture>(&self, file_rel_path: T) -> &CmdResult { + pub fn stdout_only_fixture>(&self, file_rel_path: T) -> &Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_only_bytes(contents) } @@ -347,7 +347,7 @@ impl CmdResult { /// 1. the command resulted in stderr stream output that equals the /// passed in value, when both are trimmed of trailing whitespace /// 2. the command resulted in empty (zero-length) stdout stream output - pub fn stderr_only>(&self, msg: T) -> &CmdResult { + pub fn stderr_only>(&self, msg: T) -> &Self { self.no_stdout().stderr_is(msg) } @@ -355,11 +355,11 @@ impl CmdResult { /// 1. the command resulted in a stderr stream whose bytes equal the ones /// of the passed value /// 2. the command resulted in an empty stdout stream - pub fn stderr_only_bytes>(&self, msg: T) -> &CmdResult { + pub fn stderr_only_bytes>(&self, msg: T) -> &Self { self.no_stderr().stderr_is_bytes(msg) } - pub fn fails_silently(&self) -> &CmdResult { + pub fn fails_silently(&self) -> &Self { assert!(!self.success); assert!(self.stderr.is_empty()); self @@ -373,7 +373,7 @@ impl CmdResult { /// `msg` should be the same as the one provided to UUsageError::new or show_error! /// /// 2. the command resulted in empty (zero-length) stdout stream output - pub fn usage_error>(&self, msg: T) -> &CmdResult { + pub fn usage_error>(&self, msg: T) -> &Self { self.stderr_only(format!( "{0}: {2}\nTry '{1} {0} --help' for more information.", self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command @@ -382,7 +382,7 @@ impl CmdResult { )) } - pub fn stdout_contains>(&self, cmp: T) -> &CmdResult { + pub fn stdout_contains>(&self, cmp: T) -> &Self { assert!( self.stdout_str().contains(cmp.as_ref()), "'{}' does not contain '{}'", @@ -392,7 +392,7 @@ impl CmdResult { self } - pub fn stderr_contains>(&self, cmp: T) -> &CmdResult { + pub fn stderr_contains>(&self, cmp: T) -> &Self { assert!( self.stderr_str().contains(cmp.as_ref()), "'{}' does not contain '{}'", @@ -402,7 +402,7 @@ impl CmdResult { self } - pub fn stdout_does_not_contain>(&self, cmp: T) -> &CmdResult { + pub fn stdout_does_not_contain>(&self, cmp: T) -> &Self { assert!( !self.stdout_str().contains(cmp.as_ref()), "'{}' contains '{}' but should not", @@ -412,19 +412,19 @@ impl CmdResult { self } - pub fn stderr_does_not_contain>(&self, cmp: T) -> &CmdResult { + pub fn stderr_does_not_contain>(&self, cmp: T) -> &Self { assert!(!self.stderr_str().contains(cmp.as_ref())); self } - pub fn stdout_matches(&self, regex: ®ex::Regex) -> &CmdResult { + pub fn stdout_matches(&self, regex: ®ex::Regex) -> &Self { if !regex.is_match(self.stdout_str().trim()) { panic!("Stdout does not match regex:\n{}", self.stdout_str()); } self } - pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &CmdResult { + pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &Self { if regex.is_match(self.stdout_str().trim()) { panic!("Stdout matches regex:\n{}", self.stdout_str()); } @@ -469,8 +469,8 @@ pub struct AtPath { } impl AtPath { - pub fn new(subdir: &Path) -> AtPath { - AtPath { + pub fn new(subdir: &Path) -> Self { + Self { subdir: PathBuf::from(subdir), } } @@ -776,9 +776,9 @@ pub struct TestScenario { } impl TestScenario { - pub fn new(util_name: &str) -> TestScenario { + pub fn new(util_name: &str) -> Self { let tmpd = Rc::new(TempDir::new().unwrap()); - let ts = TestScenario { + let ts = Self { bin_path: { // Instead of hard coding the path relative to the current // directory, use Cargo's OUT_DIR to find path to executable. @@ -875,11 +875,11 @@ impl UCommand { util_name: &Option, curdir: U, env_clear: bool, - ) -> UCommand { + ) -> Self { let bin_path = bin_path.as_ref(); let util_name = util_name.as_ref().map(|un| un.as_ref()); - let mut ucmd = UCommand { + let mut ucmd = Self { tmpd: None, has_run: false, raw: { @@ -927,31 +927,31 @@ impl UCommand { util_name: &Option, tmpd: Rc, env_clear: bool, - ) -> UCommand { + ) -> Self { let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap())); - let mut ucmd: UCommand = UCommand::new(bin_path, util_name, tmpd_path_buf, env_clear); + let mut ucmd: Self = Self::new(bin_path, util_name, tmpd_path_buf, env_clear); ucmd.tmpd = Some(tmpd); ucmd } - pub fn set_stdin>(&mut self, stdin: T) -> &mut UCommand { + pub fn set_stdin>(&mut self, stdin: T) -> &mut Self { self.stdin = Some(stdin.into()); self } - pub fn set_stdout>(&mut self, stdout: T) -> &mut UCommand { + pub fn set_stdout>(&mut self, stdout: T) -> &mut Self { self.stdout = Some(stdout.into()); self } - pub fn set_stderr>(&mut self, stderr: T) -> &mut UCommand { + pub fn set_stderr>(&mut self, stderr: T) -> &mut Self { self.stderr = Some(stderr.into()); self } /// Add a parameter to the invocation. Path arguments are treated relative /// to the test environment directory. - pub fn arg>(&mut self, arg: S) -> &mut UCommand { + pub fn arg>(&mut self, arg: S) -> &mut Self { assert!(!self.has_run, "{}", ALREADY_RUN); self.comm_string.push(' '); self.comm_string @@ -962,7 +962,7 @@ impl UCommand { /// Add multiple parameters to the invocation. Path arguments are treated relative /// to the test environment directory. - pub fn args>(&mut self, args: &[S]) -> &mut UCommand { + pub fn args>(&mut self, args: &[S]) -> &mut Self { assert!(!self.has_run, "{}", MULTIPLE_STDIN_MEANINGLESS); let strings = args .iter() @@ -980,7 +980,7 @@ impl UCommand { } /// provides standard input to feed in to the command when spawned - pub fn pipe_in>>(&mut self, input: T) -> &mut UCommand { + pub fn pipe_in>>(&mut self, input: T) -> &mut Self { assert!( self.bytes_into_stdin.is_none(), "{}", @@ -991,7 +991,7 @@ impl UCommand { } /// like pipe_in(...), but uses the contents of the file at the provided relative path as the piped in data - pub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> &mut UCommand { + pub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> &mut Self { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.pipe_in(contents) } @@ -999,13 +999,13 @@ impl UCommand { /// Ignores error caused by feeding stdin to the command. /// This is typically useful to test non-standard workflows /// like feeding something to a command that does not read it - pub fn ignore_stdin_write_error(&mut self) -> &mut UCommand { + pub fn ignore_stdin_write_error(&mut self) -> &mut Self { assert!(self.bytes_into_stdin.is_some(), "{}", NO_STDIN_MEANINGLESS); self.ignore_stdin_write_error = true; self } - pub fn env(&mut self, key: K, val: V) -> &mut UCommand + pub fn env(&mut self, key: K, val: V) -> &mut Self where K: AsRef, V: AsRef,