1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-27 11:07:44 +00:00

use 'Self' and derive 'Default' where possible

This commit is contained in:
Daniel Eades 2022-01-30 14:59:31 +01:00
parent 2f85610cc3
commit ba45fe312a
79 changed files with 445 additions and 474 deletions

View file

@ -38,7 +38,7 @@ pub mod options {
} }
impl Config { impl Config {
pub fn from(options: &clap::ArgMatches) -> UResult<Config> { pub fn from(options: &clap::ArgMatches) -> UResult<Self> {
let file: Option<String> = match options.values_of(options::FILE) { let file: Option<String> = match options.values_of(options::FILE) {
Some(mut values) => { Some(mut values) => {
let name = values.next().unwrap(); let name = values.next().unwrap();
@ -76,7 +76,7 @@ impl Config {
}) })
.transpose()?; .transpose()?;
Ok(Config { Ok(Self {
decode: options.is_present(options::DECODE), decode: options.is_present(options::DECODE),
ignore_garbage: options.is_present(options::IGNORE_GARBAGE), ignore_garbage: options.is_present(options::IGNORE_GARBAGE),
wrap_cols: cols, wrap_cols: cols,

View file

@ -495,43 +495,43 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
} }
impl ClobberMode { impl ClobberMode {
fn from_matches(matches: &ArgMatches) -> ClobberMode { fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::FORCE) { if matches.is_present(options::FORCE) {
ClobberMode::Force Self::Force
} else if matches.is_present(options::REMOVE_DESTINATION) { } else if matches.is_present(options::REMOVE_DESTINATION) {
ClobberMode::RemoveDestination Self::RemoveDestination
} else { } else {
ClobberMode::Standard Self::Standard
} }
} }
} }
impl OverwriteMode { impl OverwriteMode {
fn from_matches(matches: &ArgMatches) -> OverwriteMode { fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::INTERACTIVE) { 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) { } else if matches.is_present(options::NO_CLOBBER) {
OverwriteMode::NoClobber Self::NoClobber
} else { } else {
OverwriteMode::Clobber(ClobberMode::from_matches(matches)) Self::Clobber(ClobberMode::from_matches(matches))
} }
} }
} }
impl CopyMode { impl CopyMode {
fn from_matches(matches: &ArgMatches) -> CopyMode { fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::LINK) { if matches.is_present(options::LINK) {
CopyMode::Link Self::Link
} else if matches.is_present(options::SYMBOLIC_LINK) { } else if matches.is_present(options::SYMBOLIC_LINK) {
CopyMode::SymLink Self::SymLink
} else if matches.is_present(options::SPARSE) { } else if matches.is_present(options::SPARSE) {
CopyMode::Sparse Self::Sparse
} else if matches.is_present(options::UPDATE) { } else if matches.is_present(options::UPDATE) {
CopyMode::Update Self::Update
} else if matches.is_present(options::ATTRIBUTES_ONLY) { } else if matches.is_present(options::ATTRIBUTES_ONLY) {
CopyMode::AttrOnly Self::AttrOnly
} else { } else {
CopyMode::Copy Self::Copy
} }
} }
} }
@ -539,16 +539,16 @@ impl CopyMode {
impl FromStr for Attribute { impl FromStr for Attribute {
type Err = Error; type Err = Error;
fn from_str(value: &str) -> CopyResult<Attribute> { fn from_str(value: &str) -> CopyResult<Self> {
Ok(match &*value.to_lowercase() { Ok(match &*value.to_lowercase() {
"mode" => Attribute::Mode, "mode" => Self::Mode,
#[cfg(unix)] #[cfg(unix)]
"ownership" => Attribute::Ownership, "ownership" => Self::Ownership,
"timestamps" => Attribute::Timestamps, "timestamps" => Self::Timestamps,
#[cfg(feature = "feat_selinux")] #[cfg(feature = "feat_selinux")]
"context" => Attribute::Context, "context" => Self::Context,
"links" => Attribute::Links, "links" => Self::Links,
"xattr" => Attribute::Xattr, "xattr" => Self::Xattr,
_ => { _ => {
return Err(Error::InvalidArgument(format!( return Err(Error::InvalidArgument(format!(
"invalid attribute {}", "invalid attribute {}",
@ -577,7 +577,7 @@ fn add_all_attributes() -> Vec<Attribute> {
} }
impl Options { impl Options {
fn from_matches(matches: &ArgMatches) -> CopyResult<Options> { fn from_matches(matches: &ArgMatches) -> CopyResult<Self> {
let not_implemented_opts = vec![ let not_implemented_opts = vec![
options::COPY_CONTENTS, options::COPY_CONTENTS,
options::SPARSE, options::SPARSE,
@ -646,7 +646,7 @@ impl Options {
// if not executed first. // if not executed first.
preserve_attributes.sort_unstable(); preserve_attributes.sort_unstable();
let options = Options { let options = Self {
attributes_only: matches.is_present(options::ATTRIBUTES_ONLY), attributes_only: matches.is_present(options::ATTRIBUTES_ONLY),
copy_contents: matches.is_present(options::COPY_CONTENTS), copy_contents: matches.is_present(options::COPY_CONTENTS),
copy_mode: CopyMode::from_matches(matches), 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 /// Treat target as a dir if we have multiple sources or the target
/// exists and already is a directory /// 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() { if sources.len() > 1 || target.is_dir() {
TargetType::Directory Self::Directory
} else { } else {
TargetType::File Self::File
} }
} }
} }

View file

@ -57,13 +57,13 @@ pub struct CsplitOptions {
} }
impl CsplitOptions { impl CsplitOptions {
fn new(matches: &ArgMatches) -> CsplitOptions { fn new(matches: &ArgMatches) -> Self {
let keep_files = matches.is_present(options::KEEP_FILES); let keep_files = matches.is_present(options::KEEP_FILES);
let quiet = matches.is_present(options::QUIET); let quiet = matches.is_present(options::QUIET);
let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES); let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES);
let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED); let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED);
CsplitOptions { Self {
split_name: crash_if_err!( split_name: crash_if_err!(
1, 1,
SplitName::new( SplitName::new(
@ -477,8 +477,8 @@ impl<I> InputSplitter<I>
where where
I: Iterator<Item = (usize, io::Result<String>)>, I: Iterator<Item = (usize, io::Result<String>)>,
{ {
fn new(iter: I) -> InputSplitter<I> { fn new(iter: I) -> Self {
InputSplitter { Self {
iter, iter,
buffer: Vec::new(), buffer: Vec::new(),
rewind: false, rewind: false,

View file

@ -35,7 +35,7 @@ pub enum CsplitError {
impl From<io::Error> for CsplitError { impl From<io::Error> for CsplitError {
fn from(error: io::Error) -> Self { fn from(error: io::Error) -> Self {
CsplitError::IoError(error) Self::IoError(error)
} }
} }

View file

@ -44,8 +44,8 @@ pub enum ExecutePattern {
impl ExecutePattern { impl ExecutePattern {
pub fn iter(&self) -> ExecutePatternIter { pub fn iter(&self) -> ExecutePatternIter {
match self { match self {
ExecutePattern::Times(n) => ExecutePatternIter::new(Some(*n)), Self::Times(n) => ExecutePatternIter::new(Some(*n)),
ExecutePattern::Always => ExecutePatternIter::new(None), Self::Always => ExecutePatternIter::new(None),
} }
} }
} }
@ -56,8 +56,8 @@ pub struct ExecutePatternIter {
} }
impl ExecutePatternIter { impl ExecutePatternIter {
fn new(max: Option<usize>) -> ExecutePatternIter { fn new(max: Option<usize>) -> Self {
ExecutePatternIter { max, cur: 0 } Self { max, cur: 0 }
} }
} }

View file

@ -29,7 +29,7 @@ impl SplitName {
prefix_opt: Option<String>, prefix_opt: Option<String>,
format_opt: Option<String>, format_opt: Option<String>,
n_digits_opt: Option<String>, n_digits_opt: Option<String>,
) -> Result<SplitName, CsplitError> { ) -> Result<Self, CsplitError> {
// get the prefix // get the prefix
let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string()); let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string());
// the width for the split offset // 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. /// Returns the filename of the i-th split.

View file

@ -111,11 +111,11 @@ enum Iso8601Format {
impl<'a> From<&'a str> for Iso8601Format { impl<'a> From<&'a str> for Iso8601Format {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
match s { match s {
HOURS | HOUR => Iso8601Format::Hours, HOURS | HOUR => Self::Hours,
MINUTES | MINUTE => Iso8601Format::Minutes, MINUTES | MINUTE => Self::Minutes,
SECONDS | SECOND => Iso8601Format::Seconds, SECONDS | SECOND => Self::Seconds,
NS => Iso8601Format::Ns, NS => Self::Ns,
DATE => Iso8601Format::Date, DATE => Self::Date,
// Should be caught by clap // Should be caught by clap
_ => panic!("Invalid format: {}", s), _ => panic!("Invalid format: {}", s),
} }
@ -131,9 +131,9 @@ enum Rfc3339Format {
impl<'a> From<&'a str> for Rfc3339Format { impl<'a> From<&'a str> for Rfc3339Format {
fn from(s: &str) -> Self { fn from(s: &str) -> Self {
match s { match s {
DATE => Rfc3339Format::Date, DATE => Self::Date,
SECONDS | SECOND => Rfc3339Format::Seconds, SECONDS | SECOND => Self::Seconds,
NS => Rfc3339Format::Ns, NS => Self::Ns,
// Should be caught by clap // Should be caught by clap
_ => panic!("Invalid format: {}", s), _ => panic!("Invalid format: {}", s),
} }

View file

@ -69,7 +69,7 @@ impl Input<io::Stdin> {
let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?; let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?;
let count = parseargs::parse_count(&iflags, matches)?; let count = parseargs::parse_count(&iflags, matches)?;
let mut i = Input { let mut i = Self {
src: io::stdin(), src: io::stdin(),
non_ascii, non_ascii,
ibs, ibs,
@ -157,7 +157,7 @@ impl Input<File> {
.map_err_context(|| "failed to seek in input file".to_string())?; .map_err_context(|| "failed to seek in input file".to_string())?;
} }
let i = Input { let i = Self {
src, src,
non_ascii, non_ascii,
ibs, ibs,
@ -306,7 +306,7 @@ impl OutputTrait for Output<io::Stdout> {
.map_err_context(|| String::from("write error"))?; .map_err_context(|| String::from("write error"))?;
} }
Ok(Output { dst, obs, cflags }) Ok(Self { dst, obs, cflags })
} }
fn fsync(&mut self) -> io::Result<()> { fn fsync(&mut self) -> io::Result<()> {
@ -497,7 +497,7 @@ impl OutputTrait for Output<File> {
.map_err_context(|| "failed to seek in output file".to_string())?; .map_err_context(|| "failed to seek in output file".to_string())?;
} }
Ok(Output { dst, obs, cflags }) Ok(Self { dst, obs, cflags })
} else { } else {
// The following error should only occur if someone // The following error should only occur if someone
// mistakenly calls Output::<File>::new() without checking // mistakenly calls Output::<File>::new() without checking

View file

@ -296,9 +296,9 @@ impl std::str::FromStr for StatusLevel {
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
match s { match s {
"none" => Ok(StatusLevel::None), "none" => Ok(Self::None),
"noxfer" => Ok(StatusLevel::Noxfer), "noxfer" => Ok(Self::Noxfer),
"progress" => Ok(StatusLevel::Progress), "progress" => Ok(Self::Progress),
_ => Err(ParseError::StatusLevelNotRecognized(s.to_string())), _ => Err(ParseError::StatusLevelNotRecognized(s.to_string())),
} }
} }

View file

@ -52,6 +52,7 @@ static OPT_EXCLUDE_TYPE: &str = "exclude-type";
/// Store names of file systems as a selector. /// Store names of file systems as a selector.
/// Note: `exclude` takes priority over `include`. /// Note: `exclude` takes priority over `include`.
#[derive(Default)]
struct FsSelector { struct FsSelector {
include: HashSet<String>, include: HashSet<String>,
exclude: HashSet<String>, exclude: HashSet<String>,
@ -79,11 +80,8 @@ fn usage() -> String {
} }
impl FsSelector { impl FsSelector {
fn new() -> FsSelector { fn new() -> Self {
FsSelector { Self::default()
include: HashSet::new(),
exclude: HashSet::new(),
}
} }
#[inline(always)] #[inline(always)]
@ -105,8 +103,8 @@ impl FsSelector {
} }
impl Options { impl Options {
fn new() -> Options { fn new() -> Self {
Options { Self {
show_local_fs: false, show_local_fs: false,
show_all_fs: false, show_all_fs: false,
show_listed_fs: false, show_listed_fs: false,
@ -124,7 +122,7 @@ impl Options {
impl Filesystem { impl Filesystem {
// TODO: resolve uuid in `mount_info.dev_name` if exists // TODO: resolve uuid in `mount_info.dev_name` if exists
fn new(mount_info: MountInfo) -> Option<Filesystem> { fn new(mount_info: MountInfo) -> Option<Self> {
let _stat_path = if !mount_info.mount_dir.is_empty() { let _stat_path = if !mount_info.mount_dir.is_empty() {
mount_info.mount_dir.clone() mount_info.mount_dir.clone()
} else { } else {
@ -145,14 +143,14 @@ impl Filesystem {
if statfs_fn(path.as_ptr(), &mut statvfs) < 0 { if statfs_fn(path.as_ptr(), &mut statvfs) < 0 {
None None
} else { } else {
Some(Filesystem { Some(Self {
mount_info, mount_info,
usage: FsUsage::new(statvfs), usage: FsUsage::new(statvfs),
}) })
} }
} }
#[cfg(windows)] #[cfg(windows)]
Some(Filesystem { Some(Self {
mount_info, mount_info,
usage: FsUsage::new(Path::new(&_stat_path)), usage: FsUsage::new(Path::new(&_stat_path)),
}) })

View file

@ -114,7 +114,7 @@ struct Stat {
} }
impl Stat { impl Stat {
fn new(path: PathBuf, options: &Options) -> Result<Stat> { fn new(path: PathBuf, options: &Options) -> Result<Self> {
let metadata = if options.dereference { let metadata = if options.dereference {
fs::metadata(&path)? fs::metadata(&path)?
} else { } else {
@ -127,7 +127,7 @@ impl Stat {
dev_id: metadata.dev(), dev_id: metadata.dev(),
}; };
#[cfg(not(windows))] #[cfg(not(windows))]
return Ok(Stat { return Ok(Self {
path, path,
is_dir: metadata.is_dir(), is_dir: metadata.is_dir(),
size: metadata.len(), size: metadata.len(),
@ -815,9 +815,9 @@ impl FromStr for Threshold {
let size = u64::try_from(parse_size(&s[offset..])?).unwrap(); let size = u64::try_from(parse_size(&s[offset..])?).unwrap();
if s.starts_with('-') { if s.starts_with('-') {
Ok(Threshold::Upper(size)) Ok(Self::Upper(size))
} else { } else {
Ok(Threshold::Lower(size)) Ok(Self::Lower(size))
} }
} }
} }
@ -825,8 +825,8 @@ impl FromStr for Threshold {
impl Threshold { impl Threshold {
fn should_exclude(&self, size: u64) -> bool { fn should_exclude(&self, size: u64) -> bool {
match *self { match *self {
Threshold::Upper(threshold) => size > threshold, Self::Upper(threshold) => size > threshold,
Threshold::Lower(threshold) => size < threshold, Self::Lower(threshold) => size < threshold,
} }
} }
} }

View file

@ -133,7 +133,7 @@ struct Options {
} }
impl Options { impl Options {
fn new(matches: &ArgMatches) -> Options { fn new(matches: &ArgMatches) -> Self {
let (remaining_mode, tabstops) = match matches.value_of(options::TABS) { let (remaining_mode, tabstops) = match matches.value_of(options::TABS) {
Some(s) => tabstops_parse(s), Some(s) => tabstops_parse(s),
None => (RemainingMode::None, vec![DEFAULT_TABSTOP]), None => (RemainingMode::None, vec![DEFAULT_TABSTOP]),
@ -160,7 +160,7 @@ impl Options {
None => vec!["-".to_owned()], None => vec!["-".to_owned()],
}; };
Options { Self {
files, files,
tabstops, tabstops,
tspaces, tspaces,

View file

@ -66,23 +66,23 @@ impl AstNode {
} }
} }
fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<AstNode> { fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<Self> {
Box::new(AstNode::Node { Box::new(Self::Node {
token_idx, token_idx,
op_type: op_type.into(), op_type: op_type.into(),
operands, operands,
}) })
} }
fn new_leaf(token_idx: usize, value: &str) -> Box<AstNode> { fn new_leaf(token_idx: usize, value: &str) -> Box<Self> {
Box::new(AstNode::Leaf { Box::new(Self::Leaf {
token_idx, token_idx,
value: value.into(), value: value.into(),
}) })
} }
pub fn evaluate(&self) -> Result<String, String> { pub fn evaluate(&self) -> Result<String, String> {
match self { match self {
AstNode::Leaf { value, .. } => Ok(value.clone()), Self::Leaf { value, .. } => Ok(value.clone()),
AstNode::Node { op_type, .. } => match self.operand_values() { Self::Node { op_type, .. } => match self.operand_values() {
Err(reason) => Err(reason), Err(reason) => Err(reason),
Ok(operand_values) => match op_type.as_ref() { Ok(operand_values) => match op_type.as_ref() {
"+" => { "+" => {

View file

@ -42,25 +42,25 @@ pub enum Token {
} }
impl Token { impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self { fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Token::InfixOp { Self::InfixOp {
left_assoc, left_assoc,
precedence, precedence,
value: v.into(), value: v.into(),
} }
} }
fn new_value(v: &str) -> Self { fn new_value(v: &str) -> Self {
Token::Value { value: v.into() } Self::Value { value: v.into() }
} }
fn is_infix_plus(&self) -> bool { fn is_infix_plus(&self) -> bool {
match self { match self {
Token::InfixOp { value, .. } => value == "+", Self::InfixOp { value, .. } => value == "+",
_ => false, _ => false,
} }
} }
fn is_a_number(&self) -> bool { fn is_a_number(&self) -> bool {
match self { match self {
Token::Value { value, .. } => value.parse::<BigInt>().is_ok(), Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false, _ => false,
} }
} }

View file

@ -15,6 +15,7 @@ use std::slice::Iter;
/// This is a reasonably efficient implementation based on /// This is a reasonably efficient implementation based on
/// O'Neill, M. E. "[The Genuine Sieve of Eratosthenes.](http://dx.doi.org/10.1017%2FS0956796808007004)" /// 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. /// Journal of Functional Programming, Volume 19, Issue 1, 2009, pp. 95--106.
#[derive(Default)]
pub struct Sieve { pub struct Sieve {
inner: Wheel, inner: Wheel,
filts: PrimeHeap, filts: PrimeHeap,
@ -58,23 +59,20 @@ impl Iterator for Sieve {
} }
impl Sieve { impl Sieve {
fn new() -> Sieve { fn new() -> Self {
Sieve { Self::default()
inner: Wheel::new(),
filts: PrimeHeap::new(),
}
} }
#[allow(dead_code)] #[allow(dead_code)]
#[inline] #[inline]
pub fn primes() -> PrimeSieve { pub fn primes() -> PrimeSieve {
INIT_PRIMES.iter().copied().chain(Sieve::new()) INIT_PRIMES.iter().copied().chain(Self::new())
} }
#[allow(dead_code)] #[allow(dead_code)]
#[inline] #[inline]
pub fn odd_primes() -> PrimeSieve { 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 { impl Wheel {
#[inline] #[inline]
fn new() -> Wheel { fn new() -> Self {
Wheel { Self {
next: 11u64, next: 11u64,
increment: WHEEL_INCS.iter().cycle(), increment: WHEEL_INCS.iter().cycle(),
} }
} }
} }
impl Default for Wheel {
fn default() -> Self {
Self::new()
}
}
/// The increments of a wheel of circumference 210 /// The increments of a wheel of circumference 210
/// (i.e., a wheel that skips all multiples of 2, 3, 5, 7) /// (i.e., a wheel that skips all multiples of 2, 3, 5, 7)
const WHEEL_INCS: &[u64] = &[ 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 /// A min-heap of "infinite lists" of prime multiples, where a list is
/// represented as (head, increment). /// represented as (head, increment).
#[derive(Debug)] #[derive(Debug, Default)]
struct PrimeHeap { struct PrimeHeap {
data: Vec<(u64, u64)>, data: Vec<(u64, u64)>,
} }
impl PrimeHeap { impl PrimeHeap {
fn new() -> PrimeHeap {
PrimeHeap { data: Vec::new() }
}
fn peek(&self) -> Option<(u64, u64)> { fn peek(&self) -> Option<(u64, u64)> {
if let Some(&(x, y)) = self.data.get(0) { if let Some(&(x, y)) = self.data.get(0) {
Some((x, y)) Some((x, y))

View file

@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table};
type Exponent = u8; type Exponent = u8;
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>); struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
// spell-checker:ignore (names) ErdősKac * Erdős Kac // spell-checker:ignore (names) ErdősKac * Erdős Kac
@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
const NUM_FACTORS_INLINE: usize = 5; const NUM_FACTORS_INLINE: usize = 5;
impl Decomposition { impl Decomposition {
fn one() -> Decomposition { fn one() -> Self {
Decomposition(SmallVec::new()) Self::default()
} }
fn add(&mut self, factor: u64, exp: Exponent) { fn add(&mut self, factor: u64, exp: Exponent) {
@ -51,7 +51,7 @@ impl Decomposition {
} }
impl PartialEq for Decomposition { impl PartialEq for Decomposition {
fn eq(&self, other: &Decomposition) -> bool { fn eq(&self, other: &Self) -> bool {
for p in &self.0 { for p in &self.0 {
if other.get(p.0) != Some(p) { if other.get(p.0) != Some(p) {
return false; return false;
@ -73,8 +73,8 @@ impl Eq for Decomposition {}
pub struct Factors(RefCell<Decomposition>); pub struct Factors(RefCell<Decomposition>);
impl Factors { impl Factors {
pub fn one() -> Factors { pub fn one() -> Self {
Factors(RefCell::new(Decomposition::one())) Self(RefCell::new(Decomposition::one()))
} }
pub fn add(&mut self, prime: u64, exp: Exponent) { pub fn add(&mut self, prime: u64, exp: Exponent) {
@ -286,9 +286,9 @@ impl quickcheck::Arbitrary for Factors {
impl std::ops::BitXor<Exponent> for Factors { impl std::ops::BitXor<Exponent> for Factors {
type Output = Self; type Output = Self;
fn bitxor(self, rhs: Exponent) -> Factors { fn bitxor(self, rhs: Exponent) -> Self {
debug_assert_ne!(rhs, 0); debug_assert_ne!(rhs, 0);
let mut r = Factors::one(); let mut r = Self::one();
for (p, e) in self.0.borrow().0.iter() { for (p, e) in self.0.borrow().0.iter() {
r.add(*p, rhs * e); r.add(*p, rhs * e);
} }

View file

@ -42,7 +42,7 @@ pub(crate) enum Result {
impl Result { impl Result {
pub(crate) fn is_prime(&self) -> bool { pub(crate) fn is_prime(&self) -> bool {
*self == Result::Prime *self == Self::Prime
} }
} }

View file

@ -106,7 +106,7 @@ impl<T: DoubleInt> Arithmetic for Montgomery<T> {
let n = T::from_u64(n); let n = T::from_u64(n);
let a = modular_inverse(n).wrapping_neg(); let a = modular_inverse(n).wrapping_neg();
debug_assert_eq!(n.wrapping_mul(&a), T::one().wrapping_neg()); debug_assert_eq!(n.wrapping_mul(&a), T::one().wrapping_neg());
Montgomery { a, n } Self { a, n }
} }
fn modulus(&self) -> u64 { fn modulus(&self) -> u64 {

View file

@ -61,7 +61,7 @@ macro_rules! double_int {
fn as_double_width(self) -> $y { fn as_double_width(self) -> $y {
self as _ self as _
} }
fn from_double_width(n: $y) -> $x { fn from_double_width(n: $y) -> Self {
n as _ n as _
} }
} }

View file

@ -40,7 +40,7 @@ pub trait Digest {
impl Digest for md5::Context { impl Digest for md5::Context {
fn new() -> Self { fn new() -> Self {
md5::Context::new() Self::new()
} }
fn input(&mut self, input: &[u8]) { fn input(&mut self, input: &[u8]) {
@ -52,7 +52,7 @@ impl Digest for md5::Context {
} }
fn reset(&mut self) { fn reset(&mut self) {
*self = md5::Context::new(); *self = Self::new();
} }
fn output_bits(&self) -> usize { fn output_bits(&self) -> usize {
@ -85,7 +85,7 @@ impl Digest for blake2b_simd::State {
impl Digest for sha1::Sha1 { impl Digest for sha1::Sha1 {
fn new() -> Self { fn new() -> Self {
sha1::Sha1::new() Self::new()
} }
fn input(&mut self, input: &[u8]) { fn input(&mut self, input: &[u8]) {

View file

@ -112,7 +112,7 @@ enum Modes {
impl Default for Modes { impl Default for Modes {
fn default() -> Self { fn default() -> Self {
Modes::Lines(10) Self::Lines(10)
} }
} }
@ -167,7 +167,7 @@ impl HeadOptions {
pub fn get_from(args: impl uucore::Args) -> Result<Self, String> { pub fn get_from(args: impl uucore::Args) -> Result<Self, String> {
let matches = uu_app().get_matches_from(arg_iterate(args)?); 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.quiet = matches.is_present(options::QUIET_NAME);
options.verbose = matches.is_present(options::VERBOSE_NAME); options.verbose = matches.is_present(options::VERBOSE_NAME);

View file

@ -28,7 +28,7 @@ pub struct TakeAllBut<I: Iterator> {
} }
impl<I: Iterator> TakeAllBut<I> { impl<I: Iterator> TakeAllBut<I> {
pub fn new(mut iter: I, n: usize) -> TakeAllBut<I> { pub fn new(mut iter: I, n: usize) -> Self {
// Create a new ring buffer and fill it up. // Create a new ring buffer and fill it up.
// //
// If there are fewer than `n` elements in `iter`, then we // If there are fewer than `n` elements in `iter`, then we
@ -44,7 +44,7 @@ impl<I: Iterator> TakeAllBut<I> {
}; };
buf.push_back(value); buf.push_back(value);
} }
TakeAllBut { iter, buf } Self { iter, buf }
} }
} }

View file

@ -63,8 +63,8 @@ struct Settings {
} }
impl Default for Settings { impl Default for Settings {
fn default() -> Settings { fn default() -> Self {
Settings { Self {
key1: 0, key1: 0,
key2: 0, key2: 0,
print_unpaired1: false, print_unpaired1: false,
@ -163,8 +163,8 @@ struct Input {
} }
impl Input { impl Input {
fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Input { fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Self {
Input { Self {
separator, separator,
ignore_case, ignore_case,
check_order, check_order,
@ -198,14 +198,14 @@ enum Spec {
} }
impl Spec { impl Spec {
fn parse(format: &str) -> UResult<Spec> { fn parse(format: &str) -> UResult<Self> {
let mut chars = format.chars(); let mut chars = format.chars();
let file_num = match chars.next() { let file_num = match chars.next() {
Some('0') => { Some('0') => {
// Must be all alone without a field specifier. // Must be all alone without a field specifier.
if chars.next().is_none() { if chars.next().is_none() {
return Ok(Spec::Key); return Ok(Self::Key);
} }
return Err(USimpleError::new( return Err(USimpleError::new(
1, 1,
@ -223,7 +223,7 @@ impl Spec {
}; };
if let Some('.') = chars.next() { 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( Err(USimpleError::new(
@ -239,7 +239,7 @@ struct Line {
} }
impl Line { impl Line {
fn new(string: Vec<u8>, separator: Sep) -> Line { fn new(string: Vec<u8>, separator: Sep) -> Self {
let fields = match separator { let fields = match separator {
Sep::Whitespaces => string Sep::Whitespaces => string
// GNU join uses Bourne shell field splitters by default // GNU join uses Bourne shell field splitters by default
@ -251,7 +251,7 @@ impl Line {
Sep::Line => vec![string.clone()], Sep::Line => vec![string.clone()],
}; };
Line { fields, string } Self { fields, string }
} }
/// Get field at index. /// Get field at index.

View file

@ -339,7 +339,7 @@ struct PaddingCollection {
impl Config { impl Config {
#[allow(clippy::cognitive_complexity)] #[allow(clippy::cognitive_complexity)]
fn from(options: &clap::ArgMatches) -> UResult<Config> { fn from(options: &clap::ArgMatches) -> UResult<Self> {
let context = options.is_present(options::CONTEXT); let context = options.is_present(options::CONTEXT);
let (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) { let (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) {
( (
@ -661,7 +661,7 @@ impl Config {
Dereference::DirArgs Dereference::DirArgs
}; };
Ok(Config { Ok(Self {
format, format,
files, files,
sort, sort,

View file

@ -79,8 +79,8 @@ impl Iterator for EscapeOctal {
} }
impl EscapeOctal { impl EscapeOctal {
fn from(c: char) -> EscapeOctal { fn from(c: char) -> Self {
EscapeOctal { Self {
c, c,
idx: 2, idx: 2,
state: EscapeOctalState::Backslash, state: EscapeOctalState::Backslash,

View file

@ -18,7 +18,7 @@ impl Clone for FormatWriter {
} }
impl PartialEq for FormatWriter { impl PartialEq for FormatWriter {
fn eq(&self, other: &FormatWriter) -> bool { fn eq(&self, other: &Self) -> bool {
use crate::formatteriteminfo::FormatWriter::*; use crate::formatteriteminfo::FormatWriter::*;
match (self, other) { match (self, other) {

View file

@ -19,8 +19,8 @@ pub struct InputOffset {
impl InputOffset { impl InputOffset {
/// creates a new `InputOffset` using the provided values. /// creates a new `InputOffset` using the provided values.
pub fn new(radix: Radix, byte_pos: usize, label: Option<usize>) -> InputOffset { pub fn new(radix: Radix, byte_pos: usize, label: Option<usize>) -> Self {
InputOffset { Self {
radix, radix,
byte_pos, byte_pos,
label, label,

View file

@ -54,8 +54,8 @@ impl FailingMockStream {
/// ///
/// When `read` or `write` is called, it will return an error `repeat_count` times. /// 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. /// `kind` and `message` can be specified to define the exact error.
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream { pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> Self {
FailingMockStream { Self {
kind, kind,
message, message,
repeat_count, repeat_count,

View file

@ -121,7 +121,7 @@ struct OdOptions {
} }
impl OdOptions { impl OdOptions {
fn new(matches: &ArgMatches, args: &[String]) -> UResult<OdOptions> { fn new(matches: &ArgMatches, args: &[String]) -> UResult<Self> {
let byte_order = match matches.value_of(options::ENDIAN) { let byte_order = match matches.value_of(options::ENDIAN) {
None => ByteOrder::Native, None => ByteOrder::Native,
Some("little") => ByteOrder::Little, Some("little") => ByteOrder::Little,
@ -232,7 +232,7 @@ impl OdOptions {
} }
}; };
Ok(OdOptions { Ok(Self {
byte_order, byte_order,
skip_bytes, skip_bytes,
read_bytes, read_bytes,

View file

@ -54,7 +54,7 @@ impl OutputInfo {
line_bytes: usize, line_bytes: usize,
formats: &[ParsedFormatterItemInfo], formats: &[ParsedFormatterItemInfo],
output_duplicates: bool, output_duplicates: bool,
) -> OutputInfo { ) -> Self {
let byte_size_block = formats.iter().fold(1, |max, next| { let byte_size_block = formats.iter().fold(1, |max, next| {
cmp::max(max, next.formatter_item_info.byte_size) 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 print_width_line = print_width_block * (line_bytes / byte_size_block);
let spaced_formatters = 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, byte_size_line: line_bytes,
print_width_line, print_width_line,
byte_size_block, byte_size_block,
@ -90,7 +90,7 @@ impl OutputInfo {
.map(|f| SpacedFormatterItemInfo { .map(|f| SpacedFormatterItemInfo {
formatter_item_info: f.formatter_item_info, formatter_item_info: f.formatter_item_info,
add_ascii_dump: f.add_ascii_dump, 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() .collect()
} }

View file

@ -14,11 +14,8 @@ pub struct ParsedFormatterItemInfo {
} }
impl ParsedFormatterItemInfo { impl ParsedFormatterItemInfo {
pub fn new( pub fn new(formatter_item_info: FormatterItemInfo, add_ascii_dump: bool) -> Self {
formatter_item_info: FormatterItemInfo, Self {
add_ascii_dump: bool,
) -> ParsedFormatterItemInfo {
ParsedFormatterItemInfo {
formatter_item_info, formatter_item_info,
add_ascii_dump, add_ascii_dump,
} }

View file

@ -24,7 +24,7 @@ impl<R> PartialReader<R> {
/// `skip` bytes, and limits the output to `limit` bytes. Set `limit` /// `skip` bytes, and limits the output to `limit` bytes. Set `limit`
/// to `None` if there should be no limit. /// to `None` if there should be no limit.
pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self { pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self {
PartialReader { inner, skip, limit } Self { inner, skip, limit }
} }
} }

View file

@ -43,7 +43,7 @@ pub struct PeekReader<R> {
impl<R> PeekReader<R> { impl<R> PeekReader<R> {
/// Create a new `PeekReader` wrapping `inner` /// Create a new `PeekReader` wrapping `inner`
pub fn new(inner: R) -> Self { pub fn new(inner: R) -> Self {
PeekReader { Self {
inner, inner,
temp_buffer: Vec::new(), temp_buffer: Vec::new(),
} }

View file

@ -112,8 +112,8 @@ struct NumberingMode {
} }
impl Default for NumberingMode { impl Default for NumberingMode {
fn default() -> NumberingMode { fn default() -> Self {
NumberingMode { Self {
width: 5, width: 5,
separator: TAB.to_string(), separator: TAB.to_string(),
first_number: 1, first_number: 1,
@ -122,8 +122,8 @@ impl Default for NumberingMode {
} }
impl Default for FileLine { impl Default for FileLine {
fn default() -> FileLine { fn default() -> Self {
FileLine { Self {
file_id: 0, file_id: 0,
line_number: 0, line_number: 0,
page_number: 0, page_number: 0,
@ -136,7 +136,7 @@ impl Default for FileLine {
impl From<IOError> for PrError { impl From<IOError> for PrError {
fn from(err: IOError) -> Self { fn from(err: IOError) -> Self {
PrError::EncounteredErrors(err.to_string()) Self::EncounteredErrors(err.to_string())
} }
} }

View file

@ -52,8 +52,8 @@ struct Config {
} }
impl Default for Config { impl Default for Config {
fn default() -> Config { fn default() -> Self {
Config { Self {
format: OutFormat::Dumb, format: OutFormat::Dumb,
gnu_ext: true, gnu_ext: true,
auto_ref: false, auto_ref: false,
@ -96,7 +96,7 @@ struct WordFilter {
} }
impl WordFilter { impl WordFilter {
fn new(matches: &clap::ArgMatches, config: &Config) -> UResult<WordFilter> { fn new(matches: &clap::ArgMatches, config: &Config) -> UResult<Self> {
let (o, oset): (bool, HashSet<String>) = if matches.is_present(options::ONLY_FILE) { let (o, oset): (bool, HashSet<String>) = if matches.is_present(options::ONLY_FILE) {
let words = let words =
read_word_filter_file(matches, options::ONLY_FILE).map_err_context(String::new)?; 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, only_specified: o,
ignore_specified: i, ignore_specified: i,
only_set: oset, only_set: oset,

View file

@ -94,12 +94,12 @@ pub(crate) struct RunconError {
} }
impl RunconError { impl RunconError {
pub(crate) fn new(e: Error) -> RunconError { pub(crate) fn new(e: Error) -> Self {
RunconError::with_code(error_exit_status::ANOTHER_ERROR, e) Self::with_code(error_exit_status::ANOTHER_ERROR, e)
} }
pub(crate) fn with_code(code: i32, e: Error) -> RunconError { pub(crate) fn with_code(code: i32, e: Error) -> Self {
RunconError { inner: e, code } Self { inner: e, code }
} }
} }

View file

@ -110,10 +110,10 @@ impl From<ExtendedBigInt> for ExtendedBigDecimal {
fn from(big_int: ExtendedBigInt) -> Self { fn from(big_int: ExtendedBigInt) -> Self {
match big_int { match big_int {
ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)), ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)),
ExtendedBigInt::Infinity => ExtendedBigDecimal::Infinity, ExtendedBigInt::Infinity => Self::Infinity,
ExtendedBigInt::MinusInfinity => ExtendedBigDecimal::MinusInfinity, ExtendedBigInt::MinusInfinity => Self::MinusInfinity,
ExtendedBigInt::MinusZero => ExtendedBigDecimal::MinusZero, ExtendedBigInt::MinusZero => Self::MinusZero,
ExtendedBigInt::Nan => ExtendedBigDecimal::Nan, ExtendedBigInt::Nan => Self::Nan,
} }
} }
} }
@ -124,7 +124,7 @@ impl Display for ExtendedBigDecimal {
ExtendedBigDecimal::BigDecimal(x) => { ExtendedBigDecimal::BigDecimal(x) => {
let (n, p) = x.as_bigint_and_exponent(); let (n, p) = x.as_bigint_and_exponent();
match p { 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), _ => x.fmt(f),
} }
} }
@ -145,7 +145,7 @@ impl Display for ExtendedBigDecimal {
impl Zero for ExtendedBigDecimal { impl Zero for ExtendedBigDecimal {
fn zero() -> Self { fn zero() -> Self {
ExtendedBigDecimal::BigDecimal(BigDecimal::zero()) Self::BigDecimal(BigDecimal::zero())
} }
fn is_zero(&self) -> bool { fn is_zero(&self) -> bool {
match self { match self {

View file

@ -42,7 +42,7 @@ impl ExtendedBigInt {
// We would like to implement `num_traits::One`, but it requires // We would like to implement `num_traits::One`, but it requires
// a multiplication implementation, and we don't want to // a multiplication implementation, and we don't want to
// implement that here. // implement that here.
ExtendedBigInt::BigInt(BigInt::one()) Self::BigInt(BigInt::one())
} }
} }
@ -51,10 +51,10 @@ impl From<ExtendedBigDecimal> for ExtendedBigInt {
match big_decimal { match big_decimal {
// TODO When can this fail? // TODO When can this fail?
ExtendedBigDecimal::BigDecimal(x) => Self::BigInt(x.to_bigint().unwrap()), ExtendedBigDecimal::BigDecimal(x) => Self::BigInt(x.to_bigint().unwrap()),
ExtendedBigDecimal::Infinity => ExtendedBigInt::Infinity, ExtendedBigDecimal::Infinity => Self::Infinity,
ExtendedBigDecimal::MinusInfinity => ExtendedBigInt::MinusInfinity, ExtendedBigDecimal::MinusInfinity => Self::MinusInfinity,
ExtendedBigDecimal::MinusZero => ExtendedBigInt::MinusZero, ExtendedBigDecimal::MinusZero => Self::MinusZero,
ExtendedBigDecimal::Nan => ExtendedBigInt::Nan, ExtendedBigDecimal::Nan => Self::Nan,
} }
} }
} }
@ -62,22 +62,22 @@ impl From<ExtendedBigDecimal> for ExtendedBigInt {
impl Display for ExtendedBigInt { impl Display for ExtendedBigInt {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
ExtendedBigInt::BigInt(n) => n.fmt(f), Self::BigInt(n) => n.fmt(f),
ExtendedBigInt::Infinity => f32::INFINITY.fmt(f), Self::Infinity => f32::INFINITY.fmt(f),
ExtendedBigInt::MinusInfinity => f32::NEG_INFINITY.fmt(f), Self::MinusInfinity => f32::NEG_INFINITY.fmt(f),
ExtendedBigInt::MinusZero => { Self::MinusZero => {
// FIXME Come up with a way of formatting this with a // FIXME Come up with a way of formatting this with a
// "-" prefix. // "-" prefix.
0.fmt(f) 0.fmt(f)
} }
ExtendedBigInt::Nan => "nan".fmt(f), Self::Nan => "nan".fmt(f),
} }
} }
} }
impl Zero for ExtendedBigInt { impl Zero for ExtendedBigInt {
fn zero() -> Self { fn zero() -> Self {
ExtendedBigInt::BigInt(BigInt::zero()) Self::BigInt(BigInt::zero())
} }
fn is_zero(&self) -> bool { fn is_zero(&self) -> bool {
match self { match self {

View file

@ -42,7 +42,7 @@ impl Number {
// We would like to implement `num_traits::One`, but it requires // We would like to implement `num_traits::One`, but it requires
// a multiplication implementation, and we don't want to // a multiplication implementation, and we don't want to
// implement that here. // implement that here.
Number::Int(ExtendedBigInt::one()) Self::Int(ExtendedBigInt::one())
} }
/// Round this number towards the given other number. /// Round this number towards the given other number.
@ -89,12 +89,8 @@ pub struct PreciseNumber {
} }
impl PreciseNumber { impl PreciseNumber {
pub fn new( pub fn new(number: Number, num_integral_digits: usize, num_fractional_digits: usize) -> Self {
number: Number, Self {
num_integral_digits: usize,
num_fractional_digits: usize,
) -> PreciseNumber {
PreciseNumber {
number, number,
num_integral_digits, num_integral_digits,
num_fractional_digits, num_fractional_digits,
@ -106,7 +102,7 @@ impl PreciseNumber {
// We would like to implement `num_traits::One`, but it requires // We would like to implement `num_traits::One`, but it requires
// a multiplication implementation, and we don't want to // a multiplication implementation, and we don't want to
// implement that here. // 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). /// Decide whether this number is zero (either positive or negative).

View file

@ -68,9 +68,9 @@ struct FilenameGenerator {
} }
impl FilenameGenerator { impl FilenameGenerator {
fn new(name_len: usize) -> FilenameGenerator { fn new(name_len: usize) -> Self {
let indices: Vec<usize> = vec![0; name_len]; let indices: Vec<usize> = vec![0; name_len];
FilenameGenerator { Self {
name_len, name_len,
name_charset_indices: RefCell::new(indices), name_charset_indices: RefCell::new(indices),
exhausted: Cell::new(false), exhausted: Cell::new(false),

View file

@ -38,8 +38,8 @@ pub struct ReadRng<R> {
impl<R: Read> ReadRng<R> { impl<R: Read> ReadRng<R> {
/// Create a new `ReadRng` from a `Read`. /// Create a new `ReadRng` from a `Read`.
pub fn new(r: R) -> ReadRng<R> { pub fn new(r: R) -> Self {
ReadRng { reader: r } Self { reader: r }
} }
} }

View file

@ -100,7 +100,7 @@ pub struct RecycledChunk {
impl RecycledChunk { impl RecycledChunk {
pub fn new(capacity: usize) -> Self { pub fn new(capacity: usize) -> Self {
RecycledChunk { Self {
lines: Vec::new(), lines: Vec::new(),
selections: Vec::new(), selections: Vec::new(),
num_infos: Vec::new(), num_infos: Vec::new(),

View file

@ -415,7 +415,7 @@ impl WriteableTmpFile for WriteablePlainTmpFile {
type InnerWrite = BufWriter<File>; type InnerWrite = BufWriter<File>;
fn create((file, path): (File, PathBuf), _: Option<&str>) -> UResult<Self> { fn create((file, path): (File, PathBuf), _: Option<&str>) -> UResult<Self> {
Ok(WriteablePlainTmpFile { Ok(Self {
file: BufWriter::new(file), file: BufWriter::new(file),
path, path,
}) })
@ -484,7 +484,7 @@ impl WriteableTmpFile for WriteableCompressedTmpFile {
code: err.raw_os_error().unwrap(), code: err.raw_os_error().unwrap(),
})?; })?;
let child_stdin = child.stdin.take().unwrap(); let child_stdin = child.stdin.take().unwrap();
Ok(WriteableCompressedTmpFile { Ok(Self {
path, path,
compress_prog: compress_prog.to_owned(), compress_prog: compress_prog.to_owned(),
child, child,

View file

@ -85,12 +85,12 @@ impl NumInfo {
let has_si_unit = parse_settings.accept_si_units let has_si_unit = parse_settings.accept_si_units
&& matches!(char, 'K' | 'k' | 'M' | 'G' | 'T' | 'P' | 'E' | 'Z' | 'Y'); && 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 }, start..if has_si_unit { idx + 1 } else { idx },
) )
} else { } else {
( (
NumInfo { Self {
sign: Sign::Positive, sign: Sign::Positive,
exponent: 0, exponent: 0,
}, },
@ -127,10 +127,10 @@ impl NumInfo {
} }
} }
if let Some(start) = start { if let Some(start) = start {
(NumInfo { exponent, sign }, start..num.len()) (Self { exponent, sign }, start..num.len())
} else { } else {
( (
NumInfo { Self {
sign: Sign::Positive, sign: Sign::Positive,
exponent: 0, exponent: 0,
}, },

View file

@ -323,7 +323,7 @@ pub struct GlobalSettings {
/// Data needed for sorting. Should be computed once before starting to sort /// Data needed for sorting. Should be computed once before starting to sort
/// by calling `GlobalSettings::init_precomputed`. /// by calling `GlobalSettings::init_precomputed`.
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
struct Precomputed { struct Precomputed {
needs_tokens: bool, needs_tokens: bool,
num_infos_per_line: usize, num_infos_per_line: usize,
@ -378,8 +378,8 @@ impl GlobalSettings {
} }
impl Default for GlobalSettings { impl Default for GlobalSettings {
fn default() -> GlobalSettings { fn default() -> Self {
GlobalSettings { Self {
mode: SortMode::Default, mode: SortMode::Default,
debug: false, debug: false,
ignore_leading_blanks: false, ignore_leading_blanks: false,
@ -400,12 +400,7 @@ impl Default for GlobalSettings {
buffer_size: DEFAULT_BUF_SIZE, buffer_size: DEFAULT_BUF_SIZE,
compress_prog: None, compress_prog: None,
merge_batch_size: 32, merge_batch_size: 32,
precomputed: Precomputed { precomputed: Precomputed::default(),
num_infos_per_line: 0,
floats_per_line: 0,
selections_per_line: 0,
needs_tokens: false,
},
} }
} }
} }
@ -784,7 +779,7 @@ impl KeyPosition {
impl Default for KeyPosition { impl Default for KeyPosition {
fn default() -> Self { fn default() -> Self {
KeyPosition { Self {
field: 1, field: 1,
char: 1, char: 1,
ignore_blanks: false, ignore_blanks: false,

View file

@ -39,10 +39,10 @@ struct WithEnvVarSet {
} }
impl WithEnvVarSet { impl WithEnvVarSet {
/// Save previous value assigned to key, set key=value /// 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); let previous_env_value = env::var(key);
env::set_var(key, value); env::set_var(key, value);
WithEnvVarSet { Self {
_previous_var_key: String::from(key), _previous_var_key: String::from(key),
_previous_var_value: previous_env_value, _previous_var_value: previous_env_value,
} }
@ -66,7 +66,7 @@ impl FilterWriter {
/// ///
/// * `command` - The shell command to execute /// * `command` - The shell command to execute
/// * `filepath` - Path of the output file (forwarded to command as $FILE) /// * `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) // set $FILE, save previous value (if there was one)
let _with_env_var_set = WithEnvVarSet::new("FILE", filepath); let _with_env_var_set = WithEnvVarSet::new("FILE", filepath);
@ -78,7 +78,7 @@ impl FilterWriter {
.spawn() .spawn()
.expect("Couldn't spawn filter command"); .expect("Couldn't spawn filter command");
FilterWriter { shell_process } Self { shell_process }
} }
} }

View file

@ -182,31 +182,31 @@ impl Strategy {
matches.occurrences_of(OPT_LINE_BYTES), matches.occurrences_of(OPT_LINE_BYTES),
matches.occurrences_of(OPT_NUMBER), 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) => { (1, 0, 0, 0) => {
let s = matches.value_of(OPT_LINES).unwrap(); let s = matches.value_of(OPT_LINES).unwrap();
let n = parse_size(s) let n = parse_size(s)
.map_err(|e| USimpleError::new(1, format!("invalid number of lines: {}", e)))?; .map_err(|e| USimpleError::new(1, format!("invalid number of lines: {}", e)))?;
Ok(Strategy::Lines(n)) Ok(Self::Lines(n))
} }
(0, 1, 0, 0) => { (0, 1, 0, 0) => {
let s = matches.value_of(OPT_BYTES).unwrap(); let s = matches.value_of(OPT_BYTES).unwrap();
let n = parse_size(s) let n = parse_size(s)
.map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?;
Ok(Strategy::Bytes(n)) Ok(Self::Bytes(n))
} }
(0, 0, 1, 0) => { (0, 0, 1, 0) => {
let s = matches.value_of(OPT_LINE_BYTES).unwrap(); let s = matches.value_of(OPT_LINE_BYTES).unwrap();
let n = parse_size(s) let n = parse_size(s)
.map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?; .map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?;
Ok(Strategy::LineBytes(n)) Ok(Self::LineBytes(n))
} }
(0, 0, 0, 1) => { (0, 0, 0, 1) => {
let s = matches.value_of(OPT_NUMBER).unwrap(); let s = matches.value_of(OPT_NUMBER).unwrap();
let n = s.parse::<usize>().map_err(|e| { let n = s.parse::<usize>().map_err(|e| {
USimpleError::new(1, format!("invalid number of chunks: {}", 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")), _ => Err(UUsageError::new(1, "cannot split in more than one way")),
} }
@ -232,7 +232,7 @@ struct Settings {
impl Settings { impl Settings {
/// Parse a strategy from the command-line arguments. /// Parse a strategy from the command-line arguments.
fn from(matches: ArgMatches) -> UResult<Self> { fn from(matches: ArgMatches) -> UResult<Self> {
let result = Settings { let result = Self {
suffix_length: matches suffix_length: matches
.value_of(OPT_SUFFIX_LENGTH) .value_of(OPT_SUFFIX_LENGTH)
.unwrap() .unwrap()
@ -275,8 +275,8 @@ struct LineSplitter {
} }
impl LineSplitter { impl LineSplitter {
fn new(chunk_size: usize) -> LineSplitter { fn new(chunk_size: usize) -> Self {
LineSplitter { Self {
lines_per_split: chunk_size, lines_per_split: chunk_size,
} }
} }
@ -314,8 +314,8 @@ struct ByteSplitter {
} }
impl ByteSplitter { impl ByteSplitter {
fn new(chunk_size: usize) -> ByteSplitter { fn new(chunk_size: usize) -> Self {
ByteSplitter { Self {
bytes_per_split: u128::try_from(chunk_size).unwrap(), bytes_per_split: u128::try_from(chunk_size).unwrap(),
} }
} }

View file

@ -461,7 +461,7 @@ impl Stater {
Ok(tokens) Ok(tokens)
} }
fn new(matches: &ArgMatches) -> UResult<Stater> { fn new(matches: &ArgMatches) -> UResult<Self> {
let files: Vec<String> = matches let files: Vec<String> = matches
.values_of(ARG_FILES) .values_of(ARG_FILES)
.map(|v| v.map(ToString::to_string).collect()) .map(|v| v.map(ToString::to_string).collect())
@ -480,12 +480,12 @@ impl Stater {
let show_fs = matches.is_present(options::FILE_SYSTEM); let show_fs = matches.is_present(options::FILE_SYSTEM);
let default_tokens = if format_str.is_empty() { 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 { } else {
Stater::generate_tokens(format_str, use_printf)? Self::generate_tokens(format_str, use_printf)?
}; };
let default_dev_tokens = 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 { let mount_list = if show_fs {
// mount points aren't displayed when showing filesystem information // mount points aren't displayed when showing filesystem information
@ -501,7 +501,7 @@ impl Stater {
Some(mount_list) Some(mount_list)
}; };
Ok(Stater { Ok(Self {
follow: matches.is_present(options::DEREFERENCE), follow: matches.is_present(options::DEREFERENCE),
show_fs, show_fs,
from_user: !format_str.is_empty(), from_user: !format_str.is_empty(),

View file

@ -70,7 +70,7 @@ impl<'a> TryFrom<&ArgMatches> for ProgramOptions {
type Error = ProgramOptionsError; type Error = ProgramOptionsError;
fn try_from(matches: &ArgMatches) -> Result<Self, Self::Error> { fn try_from(matches: &ArgMatches) -> Result<Self, Self::Error> {
Ok(ProgramOptions { Ok(Self {
stdin: check_option(matches, options::INPUT)?, stdin: check_option(matches, options::INPUT)?,
stdout: check_option(matches, options::OUTPUT)?, stdout: check_option(matches, options::OUTPUT)?,
stderr: check_option(matches, options::ERROR)?, stderr: check_option(matches, options::ERROR)?,

View file

@ -25,8 +25,8 @@ pub struct ProcessChecker {
} }
impl ProcessChecker { impl ProcessChecker {
pub fn new(process_id: self::Pid) -> ProcessChecker { pub fn new(process_id: self::Pid) -> Self {
ProcessChecker { pid: process_id } Self { pid: process_id }
} }
// Borrowing mutably to be aligned with Windows implementation // Borrowing mutably to be aligned with Windows implementation

View file

@ -72,7 +72,7 @@ enum FilterMode {
impl Default for FilterMode { impl Default for FilterMode {
fn default() -> Self { 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<Self, String> { pub fn get_from(args: impl uucore::Args) -> Result<Self, String> {
let matches = uu_app().get_matches_from(arg_iterate(args)?); let matches = uu_app().get_matches_from(arg_iterate(args)?);
let mut settings: Settings = Settings { let mut settings: Self = Self {
sleep_msec: 1000, sleep_msec: 1000,
follow: matches.is_present(options::FOLLOW), follow: matches.is_present(options::FOLLOW),
..Default::default() ..Default::default()

View file

@ -44,26 +44,26 @@ impl Symbol {
/// Create a new Symbol from an OsString. /// Create a new Symbol from an OsString.
/// ///
/// Returns Symbol::None in place of None /// Returns Symbol::None in place of None
fn new(token: Option<OsString>) -> Symbol { fn new(token: Option<OsString>) -> Self {
match token { match token {
Some(s) => match s.to_str() { Some(s) => match s.to_str() {
Some(t) => match t { Some(t) => match t {
"(" => Symbol::LParen, "(" => Self::LParen,
"!" => Symbol::Bang, "!" => Self::Bang,
"-a" | "-o" => Symbol::BoolOp(s), "-a" | "-o" => Self::BoolOp(s),
"=" | "==" | "!=" => Symbol::Op(Operator::String(s)), "=" | "==" | "!=" => Self::Op(Operator::String(s)),
"-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Symbol::Op(Operator::Int(s)), "-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Self::Op(Operator::Int(s)),
"-ef" | "-nt" | "-ot" => Symbol::Op(Operator::File(s)), "-ef" | "-nt" | "-ot" => Self::Op(Operator::File(s)),
"-n" | "-z" => Symbol::UnaryOp(UnaryOperator::StrlenOp(s)), "-n" | "-z" => Self::UnaryOp(UnaryOperator::StrlenOp(s)),
"-b" | "-c" | "-d" | "-e" | "-f" | "-g" | "-G" | "-h" | "-k" | "-L" | "-O" "-b" | "-c" | "-d" | "-e" | "-f" | "-g" | "-G" | "-h" | "-k" | "-L" | "-O"
| "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => { | "-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
/// ///
/// Panics if `self` is Symbol::None /// Panics if `self` is Symbol::None
fn into_literal(self) -> Symbol { fn into_literal(self) -> Self {
Symbol::Literal(match self { Self::Literal(match self {
Symbol::LParen => OsString::from("("), Self::LParen => OsString::from("("),
Symbol::Bang => OsString::from("!"), Self::Bang => OsString::from("!"),
Symbol::BoolOp(s) Self::BoolOp(s)
| Symbol::Literal(s) | Self::Literal(s)
| Symbol::Op(Operator::String(s)) | Self::Op(Operator::String(s))
| Symbol::Op(Operator::Int(s)) | Self::Op(Operator::Int(s))
| Symbol::Op(Operator::File(s)) | Self::Op(Operator::File(s))
| Symbol::UnaryOp(UnaryOperator::StrlenOp(s)) | Self::UnaryOp(UnaryOperator::StrlenOp(s))
| Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) => s, | Self::UnaryOp(UnaryOperator::FiletestOp(s)) => s,
Symbol::None => panic!(), Self::None => panic!(),
}) })
} }
} }
@ -120,8 +120,8 @@ struct Parser {
impl Parser { impl Parser {
/// Construct a new Parser from a `Vec<OsString>` of tokens. /// Construct a new Parser from a `Vec<OsString>` of tokens.
fn new(tokens: Vec<OsString>) -> Parser { fn new(tokens: Vec<OsString>) -> Self {
Parser { Self {
tokens: tokens.into_iter().peekable(), tokens: tokens.into_iter().peekable(),
stack: vec![], stack: vec![],
} }

View file

@ -57,7 +57,7 @@ struct Config {
} }
impl Config { impl Config {
fn from(options: &clap::ArgMatches) -> Config { fn from(options: &clap::ArgMatches) -> Self {
let signal = match options.value_of(options::SIGNAL) { let signal = match options.value_of(options::SIGNAL) {
Some(signal_) => { Some(signal_) => {
let signal_result = signal_by_name_or_value(signal_); let signal_result = signal_by_name_or_value(signal_);
@ -88,7 +88,7 @@ impl Config {
.map(String::from) .map(String::from)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Config { Self {
foreground, foreground,
kill_after, kill_after,
signal, signal,

View file

@ -140,10 +140,10 @@ impl Sequence {
set2_str: &str, set2_str: &str,
truncate_set1_flag: bool, truncate_set1_flag: bool,
) -> Result<(Vec<char>, Vec<char>), BadSequence> { ) -> Result<(Vec<char>, Vec<char>), BadSequence> {
let set1 = Sequence::from_str(set1_str)?; let set1 = Self::from_str(set1_str)?;
let set2 = Sequence::from_str(set2_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(); let set1_star_count = set1.iter().filter(is_char_star).count();
if set1_star_count == 0 { if set1_star_count == 0 {
let set2_star_count = set2.iter().filter(is_char_star).count(); let set2_star_count = set2.iter().filter(is_char_star).count();
@ -152,17 +152,15 @@ impl Sequence {
Sequence::CharStar(c) => Some(c), Sequence::CharStar(c) => Some(c),
_ => None, _ => None,
}); });
let mut partition = set2 let mut partition = set2.as_slice().split(|s| matches!(s, Self::CharStar(_)));
.as_slice() let set1_len = set1.iter().flat_map(Self::flatten).count();
.split(|s| matches!(s, Sequence::CharStar(_)));
let set1_len = set1.iter().flat_map(Sequence::flatten).count();
let set2_len = set2 let set2_len = set2
.iter() .iter()
.filter_map(|s| match s { .filter_map(|s| match s {
Sequence::CharStar(_) => None, Sequence::CharStar(_) => None,
r => Some(r), r => Some(r),
}) })
.flat_map(Sequence::flatten) .flat_map(Self::flatten)
.count(); .count();
let star_compensate_len = set1_len.saturating_sub(set2_len); let star_compensate_len = set1_len.saturating_sub(set2_len);
let (left, right) = (partition.next(), partition.next()); let (left, right) = (partition.next(), partition.next());
@ -175,35 +173,35 @@ impl Sequence {
if let Some(c) = char_star { if let Some(c) = char_star {
std::iter::repeat(*c) std::iter::repeat(*c)
.take(star_compensate_len) .take(star_compensate_len)
.chain(set2_b.iter().flat_map(Sequence::flatten)) .chain(set2_b.iter().flat_map(Self::flatten))
.collect() .collect()
} else { } 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(set2_a), None) => match char_star {
Some(c) => set2_a Some(c) => set2_a
.iter() .iter()
.flat_map(Sequence::flatten) .flat_map(Self::flatten)
.chain(std::iter::repeat(*c).take(star_compensate_len)) .chain(std::iter::repeat(*c).take(star_compensate_len))
.collect(), .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(set2_a), Some(set2_b)) => match char_star {
Some(c) => set2_a Some(c) => set2_a
.iter() .iter()
.flat_map(Sequence::flatten) .flat_map(Self::flatten)
.chain(std::iter::repeat(*c).take(star_compensate_len)) .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(), .collect(),
None => set2_a None => set2_a
.iter() .iter()
.chain(set2_b.iter()) .chain(set2_b.iter())
.flat_map(Sequence::flatten) .flat_map(Self::flatten)
.collect(), .collect(),
}, },
}; };
let mut set1_solved: Vec<char> = set1.iter().flat_map(Sequence::flatten).collect(); let mut set1_solved: Vec<char> = set1.iter().flat_map(Self::flatten).collect();
if truncate_set1_flag { if truncate_set1_flag {
set1_solved.truncate(set2_solved.len()); set1_solved.truncate(set2_solved.len());
} }
@ -218,15 +216,15 @@ impl Sequence {
} }
impl Sequence { impl Sequence {
pub fn from_str(input: &str) -> Result<Vec<Sequence>, BadSequence> { pub fn from_str(input: &str) -> Result<Vec<Self>, BadSequence> {
many0(alt(( many0(alt((
Sequence::parse_char_range, Self::parse_char_range,
Sequence::parse_char_star, Self::parse_char_star,
Sequence::parse_char_repeat, Self::parse_char_repeat,
Sequence::parse_class, Self::parse_class,
Sequence::parse_char_equal, Self::parse_char_equal,
// NOTE: This must be the last one // 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) )))(input)
.map(|(_, r)| r) .map(|(_, r)| r)
.unwrap() .unwrap()
@ -251,64 +249,64 @@ impl Sequence {
} }
fn parse_backslash_or_char(input: &str) -> IResult<&str, char> { 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<Sequence, BadSequence>> { fn parse_char_range(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
separated_pair( separated_pair(
Sequence::parse_backslash_or_char, Self::parse_backslash_or_char,
tag("-"), tag("-"),
Sequence::parse_backslash_or_char, Self::parse_backslash_or_char,
)(input) )(input)
.map(|(l, (a, b))| { .map(|(l, (a, b))| {
(l, { (l, {
let (start, end) = (u32::from(a), u32::from(b)); 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<Sequence, BadSequence>> { fn parse_char_star(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
delimited(tag("["), Sequence::parse_backslash_or_char, tag("*]"))(input) delimited(tag("["), Self::parse_backslash_or_char, tag("*]"))(input)
.map(|(l, a)| (l, Ok(Sequence::CharStar(a)))) .map(|(l, a)| (l, Ok(Self::CharStar(a))))
} }
fn parse_char_repeat(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> { fn parse_char_repeat(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
delimited( delimited(
tag("["), tag("["),
separated_pair(Sequence::parse_backslash_or_char, tag("*"), digit1), separated_pair(Self::parse_backslash_or_char, tag("*"), digit1),
tag("]"), tag("]"),
)(input) )(input)
.map(|(l, (c, str))| { .map(|(l, (c, str))| {
( (
l, l,
match usize::from_str_radix(str, 8) { match usize::from_str_radix(str, 8) {
Ok(0) => Ok(Sequence::CharStar(c)), Ok(0) => Ok(Self::CharStar(c)),
Ok(count) => Ok(Sequence::CharRepeat(c, count)), Ok(count) => Ok(Self::CharRepeat(c, count)),
Err(_) => Err(BadSequence::InvalidRepeatCount(str.to_string())), Err(_) => Err(BadSequence::InvalidRepeatCount(str.to_string())),
}, },
) )
}) })
} }
fn parse_class(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> { fn parse_class(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
delimited( delimited(
tag("[:"), tag("[:"),
alt(( alt((
map( map(
alt(( alt((
value(Sequence::Alnum, tag("alnum")), value(Self::Alnum, tag("alnum")),
value(Sequence::Alpha, tag("alpha")), value(Self::Alpha, tag("alpha")),
value(Sequence::Blank, tag("blank")), value(Self::Blank, tag("blank")),
value(Sequence::Control, tag("cntrl")), value(Self::Control, tag("cntrl")),
value(Sequence::Digit, tag("digit")), value(Self::Digit, tag("digit")),
value(Sequence::Graph, tag("graph")), value(Self::Graph, tag("graph")),
value(Sequence::Lower, tag("lower")), value(Self::Lower, tag("lower")),
value(Sequence::Print, tag("print")), value(Self::Print, tag("print")),
value(Sequence::Punct, tag("punct")), value(Self::Punct, tag("punct")),
value(Sequence::Space, tag("space")), value(Self::Space, tag("space")),
value(Sequence::Upper, tag("upper")), value(Self::Upper, tag("upper")),
value(Sequence::Xdigit, tag("xdigit")), value(Self::Xdigit, tag("xdigit")),
)), )),
Ok, Ok,
), ),
@ -318,7 +316,7 @@ impl Sequence {
)(input) )(input)
} }
fn parse_char_equal(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> { fn parse_char_equal(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
delimited( delimited(
tag("[="), tag("[="),
alt(( alt((
@ -326,7 +324,7 @@ impl Sequence {
Err(BadSequence::MissingEquivalentClassChar), Err(BadSequence::MissingEquivalentClassChar),
peek(tag("=]")), 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("=]"), tag("=]"),
)(input) )(input)
@ -344,8 +342,8 @@ pub struct DeleteOperation {
} }
impl DeleteOperation { impl DeleteOperation {
pub fn new(set: Vec<char>, complement_flag: bool) -> DeleteOperation { pub fn new(set: Vec<char>, complement_flag: bool) -> Self {
DeleteOperation { Self {
set, set,
complement_flag, complement_flag,
} }
@ -372,8 +370,8 @@ pub struct TranslateOperationComplement {
} }
impl TranslateOperationComplement { impl TranslateOperationComplement {
fn new(set1: Vec<char>, set2: Vec<char>) -> TranslateOperationComplement { fn new(set1: Vec<char>, set2: Vec<char>) -> Self {
TranslateOperationComplement { Self {
iter: 0, iter: 0,
set2_iter: 0, set2_iter: 0,
set1, set1,
@ -389,16 +387,16 @@ pub struct TranslateOperationStandard {
} }
impl TranslateOperationStandard { impl TranslateOperationStandard {
fn new(set1: Vec<char>, set2: Vec<char>) -> Result<TranslateOperationStandard, BadSequence> { fn new(set1: Vec<char>, set2: Vec<char>) -> Result<Self, BadSequence> {
if let Some(fallback) = set2.last().copied() { if let Some(fallback) = set2.last().copied() {
Ok(TranslateOperationStandard { Ok(Self {
translation_map: set1 translation_map: set1
.into_iter() .into_iter()
.zip(set2.into_iter().chain(std::iter::repeat(fallback))) .zip(set2.into_iter().chain(std::iter::repeat(fallback)))
.collect::<HashMap<_, _>>(), .collect::<HashMap<_, _>>(),
}) })
} else if set1.is_empty() && set2.is_empty() { } else if set1.is_empty() && set2.is_empty() {
Ok(TranslateOperationStandard { Ok(Self {
translation_map: HashMap::new(), translation_map: HashMap::new(),
}) })
} else { } else {
@ -424,19 +422,13 @@ impl TranslateOperation {
} }
impl TranslateOperation { impl TranslateOperation {
pub fn new( pub fn new(set1: Vec<char>, set2: Vec<char>, complement: bool) -> Result<Self, BadSequence> {
set1: Vec<char>,
set2: Vec<char>,
complement: bool,
) -> Result<TranslateOperation, BadSequence> {
if complement { if complement {
Ok(TranslateOperation::Complement( Ok(Self::Complement(TranslateOperationComplement::new(
TranslateOperationComplement::new(set1, set2), set1, set2,
)) )))
} else { } else {
Ok(TranslateOperation::Standard( Ok(Self::Standard(TranslateOperationStandard::new(set1, set2)?))
TranslateOperationStandard::new(set1, set2)?,
))
} }
} }
} }
@ -444,13 +436,13 @@ impl TranslateOperation {
impl SymbolTranslator for TranslateOperation { impl SymbolTranslator for TranslateOperation {
fn translate(&mut self, current: char) -> Option<char> { fn translate(&mut self, current: char) -> Option<char> {
match self { match self {
TranslateOperation::Standard(TranslateOperationStandard { translation_map }) => Some( Self::Standard(TranslateOperationStandard { translation_map }) => Some(
translation_map translation_map
.iter() .iter()
.find_map(|(l, r)| if l.eq(&current) { Some(*r) } else { None }) .find_map(|(l, r)| if l.eq(&current) { Some(*r) } else { None })
.unwrap_or(current), .unwrap_or(current),
), ),
TranslateOperation::Complement(TranslateOperationComplement { Self::Complement(TranslateOperationComplement {
iter, iter,
set2_iter, set2_iter,
set1, set1,
@ -467,8 +459,7 @@ impl SymbolTranslator for TranslateOperation {
} else { } else {
while translation_map.get(&current).is_none() { while translation_map.get(&current).is_none() {
if let Some(value) = set2.get(*set2_iter) { if let Some(value) = set2.get(*set2_iter) {
let (next_iter, next_key) = let (next_iter, next_key) = Self::next_complement_char(*iter, &*set1);
TranslateOperation::next_complement_char(*iter, &*set1);
*iter = next_iter; *iter = next_iter;
*set2_iter = set2_iter.saturating_add(1); *set2_iter = set2_iter.saturating_add(1);
translation_map.insert(next_key, *value); translation_map.insert(next_key, *value);
@ -491,8 +482,8 @@ pub struct SqueezeOperation {
} }
impl SqueezeOperation { impl SqueezeOperation {
pub fn new(set1: Vec<char>, complement: bool) -> SqueezeOperation { pub fn new(set1: Vec<char>, complement: bool) -> Self {
SqueezeOperation { Self {
set1: set1.into_iter().collect(), set1: set1.into_iter().collect(),
complement, complement,
previous: None, previous: None,

View file

@ -104,6 +104,7 @@ pub fn uu_app<'a>() -> App<'a> {
// We use String as a representation of node here // We use String as a representation of node here
// but using integer may improve performance. // but using integer may improve performance.
#[derive(Default)]
struct Graph { struct Graph {
in_edges: HashMap<String, HashSet<String>>, in_edges: HashMap<String, HashSet<String>>,
out_edges: HashMap<String, Vec<String>>, out_edges: HashMap<String, Vec<String>>,
@ -111,12 +112,8 @@ struct Graph {
} }
impl Graph { impl Graph {
fn new() -> Graph { fn new() -> Self {
Graph { Self::default()
in_edges: HashMap::new(),
out_edges: HashMap::new(),
result: vec![],
}
} }
fn has_node(&self, n: &str) -> bool { fn has_node(&self, n: &str) -> bool {

View file

@ -67,7 +67,7 @@ struct Options {
} }
impl Options { impl Options {
fn new(matches: &clap::ArgMatches) -> Options { fn new(matches: &clap::ArgMatches) -> Self {
let tabstops = match matches.value_of(options::TABS) { let tabstops = match matches.value_of(options::TABS) {
None => vec![DEFAULT_TABSTOP], None => vec![DEFAULT_TABSTOP],
Some(s) => tabstops_parse(s), Some(s) => tabstops_parse(s),
@ -82,7 +82,7 @@ impl Options {
None => vec!["-".to_owned()], None => vec!["-".to_owned()],
}; };
Options { Self {
files, files,
tabstops, tabstops,
aflag, aflag,

View file

@ -39,8 +39,8 @@ struct Settings {
} }
impl Settings { impl Settings {
fn new(matches: &ArgMatches) -> Settings { fn new(matches: &ArgMatches) -> Self {
let settings = Settings { let settings = Self {
show_bytes: matches.is_present(options::BYTES), show_bytes: matches.is_present(options::BYTES),
show_chars: matches.is_present(options::CHAR), show_chars: matches.is_present(options::CHAR),
show_lines: matches.is_present(options::LINES), show_lines: matches.is_present(options::LINES),
@ -57,7 +57,7 @@ impl Settings {
return settings; return settings;
} }
Settings { Self {
show_bytes: true, show_bytes: true,
show_chars: false, show_chars: false,
show_lines: true, show_lines: true,

View file

@ -55,7 +55,7 @@ type Result<T> = std::result::Result<T, Error>;
impl From<nix::Error> for Error { impl From<nix::Error> for Error {
fn from(error: nix::Error) -> Self { 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))
} }
} }

View file

@ -107,7 +107,7 @@ pub struct Data<R: Read> {
impl<R: Read> Data<R> { impl<R: Read> Data<R> {
pub fn new(input: R, format: Format) -> Self { pub fn new(input: R, format: Format) -> Self {
Data { Self {
line_wrap: 76, line_wrap: 76,
ignore_garbage: false, ignore_garbage: false,
input, input,

View file

@ -175,7 +175,7 @@ impl Passwd {
/// SAFETY: All the pointed-to strings must be valid and not change while /// SAFETY: All the pointed-to strings must be valid and not change while
/// the function runs. That means PW_LOCK must be held. /// the function runs. That means PW_LOCK must be held.
unsafe fn from_raw(raw: passwd) -> Self { unsafe fn from_raw(raw: passwd) -> Self {
Passwd { Self {
name: cstr2string(raw.pw_name), name: cstr2string(raw.pw_name),
uid: raw.pw_uid, uid: raw.pw_uid,
gid: raw.pw_gid, gid: raw.pw_gid,
@ -243,7 +243,7 @@ impl Group {
/// SAFETY: gr_name must be valid and not change while /// SAFETY: gr_name must be valid and not change while
/// the function runs. That means PW_LOCK must be held. /// the function runs. That means PW_LOCK must be held.
unsafe fn from_raw(raw: group) -> Self { unsafe fn from_raw(raw: group) -> Self {
Group { Self {
name: cstr2string(raw.gr_name), name: cstr2string(raw.gr_name),
gid: raw.gr_gid, gid: raw.gr_gid,
} }

View file

@ -197,7 +197,7 @@ impl MountInfo {
} }
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn new(file_name: &str, raw: &[&str]) -> Option<MountInfo> { fn new(file_name: &str, raw: &[&str]) -> Option<Self> {
match file_name { match file_name {
// spell-checker:ignore (word) noatime // spell-checker:ignore (word) noatime
// Format: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue // 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() let after_fields = raw[FIELDS_OFFSET..].iter().position(|c| *c == "-").unwrap()
+ FIELDS_OFFSET + FIELDS_OFFSET
+ 1; + 1;
let mut m = MountInfo { let mut m = Self {
dev_id: "".to_string(), dev_id: "".to_string(),
dev_name: raw[after_fields + 1].to_string(), dev_name: raw[after_fields + 1].to_string(),
fs_type: raw[after_fields].to_string(), fs_type: raw[after_fields].to_string(),
@ -221,7 +221,7 @@ impl MountInfo {
Some(m) Some(m)
} }
LINUX_MTAB => { LINUX_MTAB => {
let mut m = MountInfo { let mut m = Self {
dev_id: "".to_string(), dev_id: "".to_string(),
dev_name: raw[0].to_string(), dev_name: raw[0].to_string(),
fs_type: raw[2].to_string(), fs_type: raw[2].to_string(),
@ -496,9 +496,9 @@ pub struct FsUsage {
impl FsUsage { impl FsUsage {
#[cfg(unix)] #[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` ? blocksize: statvfs.f_bsize as u64, // or `statvfs.f_frsize` ?
blocks: statvfs.f_blocks as u64, blocks: statvfs.f_blocks as u64,
bfree: statvfs.f_bfree as u64, bfree: statvfs.f_bfree as u64,
@ -510,7 +510,7 @@ impl FsUsage {
} }
} }
#[cfg(not(unix))] #[cfg(not(unix))]
pub fn new(path: &Path) -> FsUsage { pub fn new(path: &Path) -> Self {
let mut root_path = [0u16; MAX_PATH]; let mut root_path = [0u16; MAX_PATH];
let success = unsafe { let success = unsafe {
GetVolumePathNamesForVolumeNameW( GetVolumePathNamesForVolumeNameW(

View file

@ -26,8 +26,8 @@ fn warn_excess_args(first_arg: &str) {
} }
impl Memo { impl Memo {
pub fn new(pf_string: &str, pf_args_it: &mut Peekable<Iter<String>>) -> Memo { pub fn new(pf_string: &str, pf_args_it: &mut Peekable<Iter<String>>) -> Self {
let mut pm = Memo { tokens: Vec::new() }; let mut pm = Self { tokens: Vec::new() };
let mut tmp_token: Option<Box<dyn Token>>; let mut tmp_token: Option<Box<dyn Token>>;
let mut it = put_back_n(pf_string.chars()); let mut it = put_back_n(pf_string.chars());
let mut has_sub = false; let mut has_sub = false;
@ -73,7 +73,7 @@ impl Memo {
} }
pub fn run_all(pf_string: &str, pf_args: &[String]) { pub fn run_all(pf_string: &str, pf_args: &[String]) {
let mut arg_it = pf_args.iter().peekable(); 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 { loop {
if arg_it.peek().is_none() { if arg_it.peek().is_none() {
break; break;

View file

@ -56,12 +56,12 @@ impl ExitStatus {
use std::os::unix::process::ExitStatusExt; use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() { 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 // 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 { pub fn success(&self) -> bool {

View file

@ -42,15 +42,15 @@ pub struct RingBuffer<T> {
} }
impl<T> RingBuffer<T> { impl<T> RingBuffer<T> {
pub fn new(size: usize) -> RingBuffer<T> { pub fn new(size: usize) -> Self {
RingBuffer { Self {
data: VecDeque::new(), data: VecDeque::new(),
size, size,
} }
} }
pub fn from_iter(iter: impl Iterator<Item = T>, size: usize) -> RingBuffer<T> { pub fn from_iter(iter: impl Iterator<Item = T>, size: usize) -> Self {
let mut ring_buffer = RingBuffer::new(size); let mut ring_buffer = Self::new(size);
for value in iter { for value in iter {
ring_buffer.push_back(value); ring_buffer.push_back(value);
} }

View file

@ -8,13 +8,14 @@ use super::base_conv;
use super::base_conv::RadixDef; use super::base_conv::RadixDef;
use super::float_common::{primitive_to_str_common, FloatAnalysis}; use super::float_common::{primitive_to_str_common, FloatAnalysis};
#[derive(Default)]
pub struct CninetyNineHexFloatf { pub struct CninetyNineHexFloatf {
#[allow(dead_code)] #[allow(dead_code)]
as_num: f64, as_num: f64,
} }
impl CninetyNineHexFloatf { impl CninetyNineHexFloatf {
pub fn new() -> CninetyNineHexFloatf { pub fn new() -> Self {
CninetyNineHexFloatf { as_num: 0.0 } Self::default()
} }
} }

View file

@ -25,8 +25,8 @@ fn get_len_fmt_primitive(fmt: &FormatPrimitive) -> usize {
pub struct Decf; pub struct Decf;
impl Decf { impl Decf {
pub fn new() -> Decf { pub fn new() -> Self {
Decf Self
} }
} }
impl Formatter for Decf { impl Formatter for Decf {

View file

@ -46,12 +46,12 @@ impl FloatAnalysis {
max_sd_opt: Option<usize>, max_sd_opt: Option<usize>,
max_after_dec_opt: Option<usize>, max_after_dec_opt: Option<usize>,
hex_output: bool, hex_output: bool,
) -> FloatAnalysis { ) -> Self {
// this fn assumes // this fn assumes
// the input string // the input string
// has no leading spaces or 0s // has no leading spaces or 0s
let str_it = get_it_at(initial_prefix.offset, str_in); let str_it = get_it_at(initial_prefix.offset, str_in);
let mut ret = FloatAnalysis { let mut ret = Self {
len_important: 0, len_important: 0,
decimal_pos: None, decimal_pos: None,
follow: None, follow: None,

View file

@ -6,10 +6,11 @@ use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
#[derive(Default)]
pub struct Floatf; pub struct Floatf;
impl Floatf { impl Floatf {
pub fn new() -> Floatf { pub fn new() -> Self {
Floatf Self::default()
} }
} }
impl Formatter for Floatf { impl Formatter for Floatf {

View file

@ -11,6 +11,7 @@ use super::super::formatter::{
use std::i64; use std::i64;
use std::u64; use std::u64;
#[derive(Default)]
pub struct Intf { pub struct Intf {
_a: u32, _a: u32,
} }
@ -24,8 +25,8 @@ struct IntAnalysis {
} }
impl Intf { impl Intf {
pub fn new() -> Intf { pub fn new() -> Self {
Intf { _a: 0 } Self::default()
} }
// take a ref to argument string, and basic information // take a ref to argument string, and basic information
// about prefix (offset, radix, sign), and analyze string // about prefix (offset, radix, sign), and analyze string
@ -166,7 +167,7 @@ impl Intf {
fmt_prim.pre_decimal = Some(format!("{}", i)); fmt_prim.pre_decimal = Some(format!("{}", i));
fmt_prim 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) { _ => match u64::from_str_radix(segment, radix_in as u32) {
Ok(u) => { Ok(u) => {
@ -180,7 +181,7 @@ impl Intf {
}); });
fmt_prim 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 // get information about the string. see Intf::Analyze
// def above. // def above.
let convert_hints = Intf::analyze( let convert_hints = Self::analyze(
str_in, str_in,
*field.field_char == 'i' || *field.field_char == 'd', *field.field_char == 'i' || *field.field_char == 'd',
initial_prefix, initial_prefix,
@ -226,7 +227,7 @@ impl Formatter for Intf {
if convert_hints.check_past_max || decrease_from_max || radix_mismatch { if convert_hints.check_past_max || decrease_from_max || radix_mismatch {
// radix of in and out is the same. // radix of in and out is the same.
let segment = String::from(&str_in[begin..end]); let segment = String::from(&str_in[begin..end]);
Intf::conv_from_segment( Self::conv_from_segment(
&segment, &segment,
initial_prefix.radix_in.clone(), initial_prefix.radix_in.clone(),
*field.field_char, *field.field_char,
@ -246,7 +247,7 @@ impl Formatter for Intf {
fmt_prim fmt_prim
} }
} else { } 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 { fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {

View file

@ -5,11 +5,12 @@ use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix}; use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix};
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
#[derive(Default)]
pub struct Scif; pub struct Scif;
impl Scif { impl Scif {
pub fn new() -> Scif { pub fn new() -> Self {
Scif Self::default()
} }
} }
impl Formatter for Scif { impl Formatter for Scif {

View file

@ -67,7 +67,7 @@ impl Sub {
second_field: CanAsterisk<Option<u32>>, second_field: CanAsterisk<Option<u32>>,
field_char: char, field_char: char,
orig: String, orig: String,
) -> Sub { ) -> Self {
// for more dry printing, field characters are grouped // for more dry printing, field characters are grouped
// in initialization of token. // in initialization of token.
let field_type = match field_char { let field_type = match field_char {
@ -84,7 +84,7 @@ impl Sub {
exit(EXIT_ERR); exit(EXIT_ERR);
} }
}; };
Sub { Self {
min_width, min_width,
second_field, second_field,
field_char, field_char,
@ -94,6 +94,7 @@ impl Sub {
} }
} }
#[derive(Default)]
struct SubParser { struct SubParser {
min_width_tmp: Option<String>, min_width_tmp: Option<String>,
min_width_is_asterisk: bool, min_width_is_asterisk: bool,
@ -106,32 +107,23 @@ struct SubParser {
} }
impl SubParser { impl SubParser {
fn new() -> SubParser { fn new() -> Self {
SubParser { Self::default()
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 from_it( fn from_it(
it: &mut PutBackN<Chars>, it: &mut PutBackN<Chars>,
args: &mut Peekable<Iter<String>>, args: &mut Peekable<Iter<String>>,
) -> Option<Box<dyn token::Token>> { ) -> Option<Box<dyn token::Token>> {
let mut parser = SubParser::new(); let mut parser = Self::new();
if parser.sub_vals_retrieved(it) { if parser.sub_vals_retrieved(it) {
let t: Box<dyn token::Token> = SubParser::build_token(parser); let t: Box<dyn token::Token> = Self::build_token(parser);
t.print(args); t.print(args);
Some(t) Some(t)
} else { } else {
None None
} }
} }
fn build_token(parser: SubParser) -> Box<dyn token::Token> { fn build_token(parser: Self) -> Box<dyn token::Token> {
// not a self method so as to allow move of sub-parser vals. // not a self method so as to allow move of sub-parser vals.
// return new Sub struct as token // return new Sub struct as token
let t: Box<dyn token::Token> = Box::new(Sub::new( let t: Box<dyn token::Token> = Box::new(Sub::new(
@ -151,7 +143,7 @@ impl SubParser {
t t
} }
fn sub_vals_retrieved(&mut self, it: &mut PutBackN<Chars>) -> bool { fn sub_vals_retrieved(&mut self, it: &mut PutBackN<Chars>) -> 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; return false;
} }
// this fn in particular is much longer than it needs to be // this fn in particular is much longer than it needs to be

View file

@ -35,10 +35,11 @@ fn flush_bytes(bslice: &[u8]) {
let _ = stdout().flush(); let _ = stdout().flush();
} }
#[derive(Default)]
pub struct UnescapedText(Vec<u8>); pub struct UnescapedText(Vec<u8>);
impl UnescapedText { impl UnescapedText {
fn new() -> UnescapedText { fn new() -> Self {
UnescapedText(Vec::new()) Self::default()
} }
// take an iterator to the format string // take an iterator to the format string
// consume between min and max chars // consume between min and max chars
@ -133,7 +134,7 @@ impl UnescapedText {
_ => {} _ => {}
} }
if !ignore { 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); byte_vec.push(val);
let bvec = [val]; let bvec = [val];
flush_bytes(&bvec); flush_bytes(&bvec);
@ -170,8 +171,8 @@ impl UnescapedText {
'u' => 4, 'u' => 4,
/* 'U' | */ _ => 8, /* 'U' | */ _ => 8,
}; };
let val = UnescapedText::base_to_u32(len, len, 16, it); let val = Self::base_to_u32(len, len, 16, it);
UnescapedText::validate_iec(val, false); Self::validate_iec(val, false);
if let Some(c) = from_u32(val) { if let Some(c) = from_u32(val) {
c c
} else { } else {
@ -199,7 +200,7 @@ impl UnescapedText {
subs_mode: bool, subs_mode: bool,
) -> Option<Box<dyn token::Token>> { ) -> Option<Box<dyn token::Token>> {
let mut addchar = false; let mut addchar = false;
let mut new_text = UnescapedText::new(); let mut new_text = Self::new();
let mut tmp_str = String::new(); let mut tmp_str = String::new();
{ {
let new_vec: &mut Vec<u8> = &mut (new_text.0); let new_vec: &mut Vec<u8> = &mut (new_text.0);
@ -227,7 +228,7 @@ impl UnescapedText {
new_vec.extend(tmp_str.bytes()); new_vec.extend(tmp_str.bytes());
tmp_str = String::new(); 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 => { x if x == '%' && !subs_mode => {
if let Some(follow) = it.next() { if let Some(follow) = it.next() {
@ -266,7 +267,7 @@ impl token::Tokenizer for UnescapedText {
it: &mut PutBackN<Chars>, it: &mut PutBackN<Chars>,
_: &mut Peekable<Iter<String>>, _: &mut Peekable<Iter<String>>,
) -> Option<Box<dyn token::Token>> { ) -> Option<Box<dyn token::Token>> {
UnescapedText::from_it_core(it, false) Self::from_it_core(it, false)
} }
} }
impl token::Token for UnescapedText { impl token::Token for UnescapedText {

View file

@ -322,7 +322,7 @@ impl UtmpxIter {
fn new() -> Self { fn new() -> Self {
// PoisonErrors can safely be ignored // PoisonErrors can safely be ignored
let guard = LOCK.lock().unwrap_or_else(|err| err.into_inner()); let guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
UtmpxIter { Self {
guard, guard,
phantom: PhantomData, phantom: PhantomData,
} }

View file

@ -265,7 +265,7 @@ impl<T> From<T> for Box<dyn UError>
where where
T: UError + 'static, T: UError + 'static,
{ {
fn from(t: T) -> Box<dyn UError> { fn from(t: T) -> Self {
Box::new(t) Box::new(t)
} }
} }
@ -490,8 +490,8 @@ impl FromIo<Box<UIoError>> for std::io::ErrorKind {
} }
impl From<std::io::Error> for UIoError { impl From<std::io::Error> for UIoError {
fn from(f: std::io::Error) -> UIoError { fn from(f: std::io::Error) -> Self {
UIoError { Self {
context: None, context: None,
inner: f, inner: f,
} }
@ -499,9 +499,9 @@ impl From<std::io::Error> for UIoError {
} }
impl From<std::io::Error> for Box<dyn UError> { impl From<std::io::Error> for Box<dyn UError> {
fn from(f: std::io::Error) -> Box<dyn UError> { fn from(f: std::io::Error) -> Self {
let u_error: UIoError = f.into(); let u_error: UIoError = f.into();
Box::new(u_error) as Box<dyn UError> Box::new(u_error) as Self
} }
} }

View file

@ -20,7 +20,7 @@ pub struct Range {
impl FromStr for Range { impl FromStr for Range {
type Err = &'static str; type Err = &'static str;
fn from_str(s: &str) -> Result<Range, &'static str> { fn from_str(s: &str) -> Result<Self, &'static str> {
use std::usize::MAX; use std::usize::MAX;
let mut parts = s.splitn(2, '-'); let mut parts = s.splitn(2, '-');
@ -33,7 +33,7 @@ impl FromStr for Range {
(Some(nm), None) => { (Some(nm), None) => {
if let Ok(nm) = nm.parse::<usize>() { if let Ok(nm) = nm.parse::<usize>() {
if nm > 0 { if nm > 0 {
Ok(Range { low: nm, high: nm }) Ok(Self { low: nm, high: nm })
} else { } else {
Err(field) Err(field)
} }
@ -44,7 +44,7 @@ impl FromStr for Range {
(Some(n), Some(m)) if m.is_empty() => { (Some(n), Some(m)) if m.is_empty() => {
if let Ok(low) = n.parse::<usize>() { if let Ok(low) = n.parse::<usize>() {
if low > 0 { if low > 0 {
Ok(Range { low, high: MAX - 1 }) Ok(Self { low, high: MAX - 1 })
} else { } else {
Err(field) Err(field)
} }
@ -55,7 +55,7 @@ impl FromStr for Range {
(Some(n), Some(m)) if n.is_empty() => { (Some(n), Some(m)) if n.is_empty() => {
if let Ok(high) = m.parse::<usize>() { if let Ok(high) = m.parse::<usize>() {
if high > 0 { if high > 0 {
Ok(Range { low: 1, high }) Ok(Self { low: 1, high })
} else { } else {
Err(field) Err(field)
} }
@ -66,7 +66,7 @@ impl FromStr for Range {
(Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) { (Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) {
(Ok(low), Ok(high)) => { (Ok(low), Ok(high)) => {
if low > 0 && low <= high { if low > 0 && low <= high {
Ok(Range { low, high }) Ok(Self { low, high })
} else if low == 0 { } else if low == 0 {
Err(field) Err(field)
} else { } else {
@ -81,10 +81,10 @@ impl FromStr for Range {
} }
impl Range { impl Range {
pub fn from_list(list: &str) -> Result<Vec<Range>, String> { pub fn from_list(list: &str) -> Result<Vec<Self>, String> {
use std::cmp::max; use std::cmp::max;
let mut ranges: Vec<Range> = vec![]; let mut ranges: Vec<Self> = vec![];
for item in list.split(',') { for item in list.split(',') {
let range_item = FromStr::from_str(item) let range_item = FromStr::from_str(item)

View file

@ -113,7 +113,7 @@ impl fmt::Display for ParseSizeError {
// but there's a lot of downstream code that constructs these errors manually // but there's a lot of downstream code that constructs these errors manually
// that would be affected // that would be affected
impl ParseSizeError { impl ParseSizeError {
fn parse_failure(s: &str) -> ParseSizeError { fn parse_failure(s: &str) -> Self {
// stderr on linux (GNU coreutils 8.32) (LC_ALL=C) // stderr on linux (GNU coreutils 8.32) (LC_ALL=C)
// has to be handled in the respective uutils because strings differ, e.g.: // has to be handled in the respective uutils because strings differ, e.g.:
// //
@ -145,10 +145,10 @@ impl ParseSizeError {
// --width // --width
// --strings // --strings
// etc. // 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) // stderr on linux (GNU coreutils 8.32) (LC_ALL=C)
// has to be handled in the respective uutils because strings differ, e.g.: // 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.: // 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 // 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 // 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", "{}: Value too large for defined data type",
s.quote() s.quote()
)) ))

View file

@ -13,8 +13,8 @@ impl Target {
// Creates a target that will naturally die after some time if not killed // Creates a target that will naturally die after some time if not killed
// fast enough. // fast enough.
// This timeout avoids hanging failing tests. // This timeout avoids hanging failing tests.
fn new() -> Target { fn new() -> Self {
Target { Self {
child: Command::new("sleep") child: Command::new("sleep")
.arg("30") .arg("30")
.spawn() .spawn()

View file

@ -32,8 +32,8 @@ struct Glob {
} }
impl Glob { impl Glob {
fn new(at: &AtPath, directory: &str, regex: &str) -> Glob { fn new(at: &AtPath, directory: &str, regex: &str) -> Self {
Glob { Self {
directory: AtPath::new(Path::new(&at.plus_as_string(directory))), directory: AtPath::new(Path::new(&at.plus_as_string(directory))),
regex: Regex::new(regex).unwrap(), regex: Regex::new(regex).unwrap(),
} }
@ -83,8 +83,8 @@ impl RandomFile {
const LINESIZE: usize = 32; const LINESIZE: usize = 32;
/// `create()` file handle located at `at` / `name` /// `create()` file handle located at `at` / `name`
fn new(at: &AtPath, name: &str) -> RandomFile { fn new(at: &AtPath, name: &str) -> Self {
RandomFile { Self {
inner: File::create(&at.plus(name)).unwrap(), inner: File::create(&at.plus(name)).unwrap(),
} }
} }
@ -113,7 +113,7 @@ impl RandomFile {
fn add_lines(&mut self, lines: usize) { fn add_lines(&mut self, lines: usize) {
let mut n = lines; let mut n = lines;
while n > 0 { while n > 0 {
writeln!(self.inner, "{}", random_chars(RandomFile::LINESIZE)).unwrap(); writeln!(self.inner, "{}", random_chars(Self::LINESIZE)).unwrap();
n -= 1; n -= 1;
} }
} }

View file

@ -88,8 +88,8 @@ impl CmdResult {
success: bool, success: bool,
stdout: &[u8], stdout: &[u8],
stderr: &[u8], stderr: &[u8],
) -> CmdResult { ) -> Self {
CmdResult { Self {
bin_path, bin_path,
util_name, util_name,
tmpd, tmpd,
@ -150,7 +150,7 @@ impl CmdResult {
self.code.expect("Program must be run first") 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); assert_eq!(self.code(), expected_code);
self self
} }
@ -170,7 +170,7 @@ impl CmdResult {
} }
/// asserts that the command resulted in a success (zero) status code /// asserts that the command resulted in a success (zero) status code
pub fn success(&self) -> &CmdResult { pub fn success(&self) -> &Self {
assert!( assert!(
self.success, self.success,
"Command was expected to succeed.\nstdout = {}\n stderr = {}", "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 /// asserts that the command resulted in a failure (non-zero) status code
pub fn failure(&self) -> &CmdResult { pub fn failure(&self) -> &Self {
assert!( assert!(
!self.success, !self.success,
"Command was expected to fail.\nstdout = {}\n stderr = {}", "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 /// 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)); assert_eq!(self.code, Some(code));
self self
} }
@ -202,7 +202,7 @@ impl CmdResult {
/// but you might find yourself using this function if /// but you might find yourself using this function if
/// 1. you can not know exactly what stdout will be or /// 1. you can not know exactly what stdout will be or
/// 2. you know that stdout will also be empty /// 2. you know that stdout will also be empty
pub fn no_stderr(&self) -> &CmdResult { pub fn no_stderr(&self) -> &Self {
assert!( assert!(
self.stderr.is_empty(), self.stderr.is_empty(),
"Expected stderr to be empty, but it's:\n{}", "Expected stderr to be empty, but it's:\n{}",
@ -217,7 +217,7 @@ impl CmdResult {
/// but you might find yourself using this function if /// but you might find yourself using this function if
/// 1. you can not know exactly what stderr will be or /// 1. you can not know exactly what stderr will be or
/// 2. you know that stderr will also be empty /// 2. you know that stderr will also be empty
pub fn no_stdout(&self) -> &CmdResult { pub fn no_stdout(&self) -> &Self {
assert!( assert!(
self.stdout.is_empty(), self.stdout.is_empty(),
"Expected stdout to be empty, but it's:\n{}", "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 /// asserts that the command resulted in stdout stream output that equals the
/// passed in value, trailing whitespace are kept to force strict comparison (#1235) /// 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 /// stdout_only is a better choice unless stderr may or will be non-empty
pub fn stdout_is<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self {
assert_eq!(self.stdout_str(), String::from(msg.as_ref())); assert_eq!(self.stdout_str(), String::from(msg.as_ref()));
self self
} }
/// like `stdout_is`, but succeeds if any elements of `expected` matches stdout. /// like `stdout_is`, but succeeds if any elements of `expected` matches stdout.
pub fn stdout_is_any<T: AsRef<str> + std::fmt::Debug>(&self, expected: &[T]) -> &CmdResult { pub fn stdout_is_any<T: AsRef<str> + std::fmt::Debug>(&self, expected: &[T]) -> &Self {
if !expected.iter().any(|msg| self.stdout_str() == msg.as_ref()) { if !expected.iter().any(|msg| self.stdout_str() == msg.as_ref()) {
panic!( panic!(
"stdout was {}\nExpected any of {:#?}", "stdout was {}\nExpected any of {:#?}",
@ -247,7 +247,7 @@ impl CmdResult {
} }
/// Like `stdout_is` but newlines are normalized to `\n`. /// Like `stdout_is` but newlines are normalized to `\n`.
pub fn normalized_newlines_stdout_is<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn normalized_newlines_stdout_is<T: AsRef<str>>(&self, msg: T) -> &Self {
let msg = msg.as_ref().replace("\r\n", "\n"); let msg = msg.as_ref().replace("\r\n", "\n");
assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg); assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg);
self self
@ -255,13 +255,13 @@ impl CmdResult {
/// asserts that the command resulted in stdout stream output, /// asserts that the command resulted in stdout stream output,
/// whose bytes equal those of the passed in slice /// whose bytes equal those of the passed in slice
pub fn stdout_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &CmdResult { pub fn stdout_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
assert_eq!(self.stdout, msg.as_ref()); assert_eq!(self.stdout, msg.as_ref());
self self
} }
/// like stdout_is(...), but expects the contents of the file at the provided relative path /// like stdout_is(...), but expects the contents of the file at the provided relative path
pub fn stdout_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &CmdResult { pub fn stdout_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path); let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stdout_is(String::from_utf8(contents).unwrap()) self.stdout_is(String::from_utf8(contents).unwrap())
} }
@ -271,7 +271,7 @@ impl CmdResult {
&self, &self,
file_rel_path: T, file_rel_path: T,
template_vars: &[(&str, &str)], template_vars: &[(&str, &str)],
) -> &CmdResult { ) -> &Self {
let mut contents = let mut contents =
String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap(); String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap();
for kv in template_vars { for kv in template_vars {
@ -300,7 +300,7 @@ impl CmdResult {
/// asserts that the command resulted in stderr stream output that equals the /// asserts that the command resulted in stderr stream output that equals the
/// passed in value, when both are trimmed of trailing whitespace /// passed in value, when both are trimmed of trailing whitespace
/// stderr_only is a better choice unless stdout may or will be non-empty /// stderr_only is a better choice unless stdout may or will be non-empty
pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &Self {
assert_eq!( assert_eq!(
self.stderr_str().trim_end(), self.stderr_str().trim_end(),
String::from(msg.as_ref()).trim_end() String::from(msg.as_ref()).trim_end()
@ -310,13 +310,13 @@ impl CmdResult {
/// asserts that the command resulted in stderr stream output, /// asserts that the command resulted in stderr stream output,
/// whose bytes equal those of the passed in slice /// whose bytes equal those of the passed in slice
pub fn stderr_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &CmdResult { pub fn stderr_is_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
assert_eq!(self.stderr, msg.as_ref()); assert_eq!(self.stderr, msg.as_ref());
self self
} }
/// Like stdout_is_fixture, but for stderr /// Like stdout_is_fixture, but for stderr
pub fn stderr_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &CmdResult { pub fn stderr_is_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path); let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stderr_is(String::from_utf8(contents).unwrap()) 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 /// 1. the command resulted in stdout stream output that equals the
/// passed in value /// passed in value
/// 2. the command resulted in empty (zero-length) stderr stream output /// 2. the command resulted in empty (zero-length) stderr stream output
pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &Self {
self.no_stderr().stdout_is(msg) self.no_stderr().stdout_is(msg)
} }
@ -333,12 +333,12 @@ impl CmdResult {
/// 1. the command resulted in a stdout stream whose bytes /// 1. the command resulted in a stdout stream whose bytes
/// equal those of the passed in value /// equal those of the passed in value
/// 2. the command resulted in an empty stderr stream /// 2. the command resulted in an empty stderr stream
pub fn stdout_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &CmdResult { pub fn stdout_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
self.no_stderr().stdout_is_bytes(msg) self.no_stderr().stdout_is_bytes(msg)
} }
/// like stdout_only(...), but expects the contents of the file at the provided relative path /// like stdout_only(...), but expects the contents of the file at the provided relative path
pub fn stdout_only_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &CmdResult { pub fn stdout_only_fixture<T: AsRef<OsStr>>(&self, file_rel_path: T) -> &Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path); let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.stdout_only_bytes(contents) self.stdout_only_bytes(contents)
} }
@ -347,7 +347,7 @@ impl CmdResult {
/// 1. the command resulted in stderr stream output that equals the /// 1. the command resulted in stderr stream output that equals the
/// passed in value, when both are trimmed of trailing whitespace /// passed in value, when both are trimmed of trailing whitespace
/// 2. the command resulted in empty (zero-length) stdout stream output /// 2. the command resulted in empty (zero-length) stdout stream output
pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &Self {
self.no_stdout().stderr_is(msg) 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 /// 1. the command resulted in a stderr stream whose bytes equal the ones
/// of the passed value /// of the passed value
/// 2. the command resulted in an empty stdout stream /// 2. the command resulted in an empty stdout stream
pub fn stderr_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &CmdResult { pub fn stderr_only_bytes<T: AsRef<[u8]>>(&self, msg: T) -> &Self {
self.no_stderr().stderr_is_bytes(msg) self.no_stderr().stderr_is_bytes(msg)
} }
pub fn fails_silently(&self) -> &CmdResult { pub fn fails_silently(&self) -> &Self {
assert!(!self.success); assert!(!self.success);
assert!(self.stderr.is_empty()); assert!(self.stderr.is_empty());
self self
@ -373,7 +373,7 @@ impl CmdResult {
/// `msg` should be the same as the one provided to UUsageError::new or show_error! /// `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 /// 2. the command resulted in empty (zero-length) stdout stream output
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &CmdResult { pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &Self {
self.stderr_only(format!( self.stderr_only(format!(
"{0}: {2}\nTry '{1} {0} --help' for more information.", "{0}: {2}\nTry '{1} {0} --help' for more information.",
self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command 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<T: AsRef<str>>(&self, cmp: T) -> &CmdResult { pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!( assert!(
self.stdout_str().contains(cmp.as_ref()), self.stdout_str().contains(cmp.as_ref()),
"'{}' does not contain '{}'", "'{}' does not contain '{}'",
@ -392,7 +392,7 @@ impl CmdResult {
self self
} }
pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &CmdResult { pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!( assert!(
self.stderr_str().contains(cmp.as_ref()), self.stderr_str().contains(cmp.as_ref()),
"'{}' does not contain '{}'", "'{}' does not contain '{}'",
@ -402,7 +402,7 @@ impl CmdResult {
self self
} }
pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &CmdResult { pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!( assert!(
!self.stdout_str().contains(cmp.as_ref()), !self.stdout_str().contains(cmp.as_ref()),
"'{}' contains '{}' but should not", "'{}' contains '{}' but should not",
@ -412,19 +412,19 @@ impl CmdResult {
self self
} }
pub fn stderr_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &CmdResult { pub fn stderr_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self {
assert!(!self.stderr_str().contains(cmp.as_ref())); assert!(!self.stderr_str().contains(cmp.as_ref()));
self self
} }
pub fn stdout_matches(&self, regex: &regex::Regex) -> &CmdResult { pub fn stdout_matches(&self, regex: &regex::Regex) -> &Self {
if !regex.is_match(self.stdout_str().trim()) { if !regex.is_match(self.stdout_str().trim()) {
panic!("Stdout does not match regex:\n{}", self.stdout_str()); panic!("Stdout does not match regex:\n{}", self.stdout_str());
} }
self self
} }
pub fn stdout_does_not_match(&self, regex: &regex::Regex) -> &CmdResult { pub fn stdout_does_not_match(&self, regex: &regex::Regex) -> &Self {
if regex.is_match(self.stdout_str().trim()) { if regex.is_match(self.stdout_str().trim()) {
panic!("Stdout matches regex:\n{}", self.stdout_str()); panic!("Stdout matches regex:\n{}", self.stdout_str());
} }
@ -469,8 +469,8 @@ pub struct AtPath {
} }
impl AtPath { impl AtPath {
pub fn new(subdir: &Path) -> AtPath { pub fn new(subdir: &Path) -> Self {
AtPath { Self {
subdir: PathBuf::from(subdir), subdir: PathBuf::from(subdir),
} }
} }
@ -776,9 +776,9 @@ pub struct TestScenario {
} }
impl 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 tmpd = Rc::new(TempDir::new().unwrap());
let ts = TestScenario { let ts = Self {
bin_path: { bin_path: {
// Instead of hard coding the path relative to the current // Instead of hard coding the path relative to the current
// directory, use Cargo's OUT_DIR to find path to executable. // directory, use Cargo's OUT_DIR to find path to executable.
@ -875,11 +875,11 @@ impl UCommand {
util_name: &Option<S>, util_name: &Option<S>,
curdir: U, curdir: U,
env_clear: bool, env_clear: bool,
) -> UCommand { ) -> Self {
let bin_path = bin_path.as_ref(); let bin_path = bin_path.as_ref();
let util_name = util_name.as_ref().map(|un| un.as_ref()); let util_name = util_name.as_ref().map(|un| un.as_ref());
let mut ucmd = UCommand { let mut ucmd = Self {
tmpd: None, tmpd: None,
has_run: false, has_run: false,
raw: { raw: {
@ -927,31 +927,31 @@ impl UCommand {
util_name: &Option<S>, util_name: &Option<S>,
tmpd: Rc<TempDir>, tmpd: Rc<TempDir>,
env_clear: bool, env_clear: bool,
) -> UCommand { ) -> Self {
let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap())); 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.tmpd = Some(tmpd);
ucmd ucmd
} }
pub fn set_stdin<T: Into<Stdio>>(&mut self, stdin: T) -> &mut UCommand { pub fn set_stdin<T: Into<Stdio>>(&mut self, stdin: T) -> &mut Self {
self.stdin = Some(stdin.into()); self.stdin = Some(stdin.into());
self self
} }
pub fn set_stdout<T: Into<Stdio>>(&mut self, stdout: T) -> &mut UCommand { pub fn set_stdout<T: Into<Stdio>>(&mut self, stdout: T) -> &mut Self {
self.stdout = Some(stdout.into()); self.stdout = Some(stdout.into());
self self
} }
pub fn set_stderr<T: Into<Stdio>>(&mut self, stderr: T) -> &mut UCommand { pub fn set_stderr<T: Into<Stdio>>(&mut self, stderr: T) -> &mut Self {
self.stderr = Some(stderr.into()); self.stderr = Some(stderr.into());
self self
} }
/// Add a parameter to the invocation. Path arguments are treated relative /// Add a parameter to the invocation. Path arguments are treated relative
/// to the test environment directory. /// to the test environment directory.
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut UCommand { pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
assert!(!self.has_run, "{}", ALREADY_RUN); assert!(!self.has_run, "{}", ALREADY_RUN);
self.comm_string.push(' '); self.comm_string.push(' ');
self.comm_string self.comm_string
@ -962,7 +962,7 @@ impl UCommand {
/// Add multiple parameters to the invocation. Path arguments are treated relative /// Add multiple parameters to the invocation. Path arguments are treated relative
/// to the test environment directory. /// to the test environment directory.
pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut UCommand { pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Self {
assert!(!self.has_run, "{}", MULTIPLE_STDIN_MEANINGLESS); assert!(!self.has_run, "{}", MULTIPLE_STDIN_MEANINGLESS);
let strings = args let strings = args
.iter() .iter()
@ -980,7 +980,7 @@ impl UCommand {
} }
/// provides standard input to feed in to the command when spawned /// provides standard input to feed in to the command when spawned
pub fn pipe_in<T: Into<Vec<u8>>>(&mut self, input: T) -> &mut UCommand { pub fn pipe_in<T: Into<Vec<u8>>>(&mut self, input: T) -> &mut Self {
assert!( assert!(
self.bytes_into_stdin.is_none(), 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 /// 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<S: AsRef<OsStr>>(&mut self, file_rel_path: S) -> &mut UCommand { pub fn pipe_in_fixture<S: AsRef<OsStr>>(&mut self, file_rel_path: S) -> &mut Self {
let contents = read_scenario_fixture(&self.tmpd, file_rel_path); let contents = read_scenario_fixture(&self.tmpd, file_rel_path);
self.pipe_in(contents) self.pipe_in(contents)
} }
@ -999,13 +999,13 @@ impl UCommand {
/// Ignores error caused by feeding stdin to the command. /// Ignores error caused by feeding stdin to the command.
/// This is typically useful to test non-standard workflows /// This is typically useful to test non-standard workflows
/// like feeding something to a command that does not read it /// 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); assert!(self.bytes_into_stdin.is_some(), "{}", NO_STDIN_MEANINGLESS);
self.ignore_stdin_write_error = true; self.ignore_stdin_write_error = true;
self self
} }
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut UCommand pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
where where
K: AsRef<OsStr>, K: AsRef<OsStr>,
V: AsRef<OsStr>, V: AsRef<OsStr>,