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
+2 -2
View File
@@ -38,7 +38,7 @@ pub mod options {
}
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) {
Some(mut values) => {
let name = values.next().unwrap();
@@ -76,7 +76,7 @@ impl Config {
})
.transpose()?;
Ok(Config {
Ok(Self {
decode: options.is_present(options::DECODE),
ignore_garbage: options.is_present(options::IGNORE_GARBAGE),
wrap_cols: cols,
+27 -27
View File
@@ -495,43 +495,43 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
impl ClobberMode {
fn from_matches(matches: &ArgMatches) -> ClobberMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::FORCE) {
ClobberMode::Force
Self::Force
} else if matches.is_present(options::REMOVE_DESTINATION) {
ClobberMode::RemoveDestination
Self::RemoveDestination
} else {
ClobberMode::Standard
Self::Standard
}
}
}
impl OverwriteMode {
fn from_matches(matches: &ArgMatches) -> OverwriteMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::INTERACTIVE) {
OverwriteMode::Interactive(ClobberMode::from_matches(matches))
Self::Interactive(ClobberMode::from_matches(matches))
} else if matches.is_present(options::NO_CLOBBER) {
OverwriteMode::NoClobber
Self::NoClobber
} else {
OverwriteMode::Clobber(ClobberMode::from_matches(matches))
Self::Clobber(ClobberMode::from_matches(matches))
}
}
}
impl CopyMode {
fn from_matches(matches: &ArgMatches) -> CopyMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::LINK) {
CopyMode::Link
Self::Link
} else if matches.is_present(options::SYMBOLIC_LINK) {
CopyMode::SymLink
Self::SymLink
} else if matches.is_present(options::SPARSE) {
CopyMode::Sparse
Self::Sparse
} else if matches.is_present(options::UPDATE) {
CopyMode::Update
Self::Update
} else if matches.is_present(options::ATTRIBUTES_ONLY) {
CopyMode::AttrOnly
Self::AttrOnly
} else {
CopyMode::Copy
Self::Copy
}
}
}
@@ -539,16 +539,16 @@ impl CopyMode {
impl FromStr for Attribute {
type Err = Error;
fn from_str(value: &str) -> CopyResult<Attribute> {
fn from_str(value: &str) -> CopyResult<Self> {
Ok(match &*value.to_lowercase() {
"mode" => Attribute::Mode,
"mode" => Self::Mode,
#[cfg(unix)]
"ownership" => Attribute::Ownership,
"timestamps" => Attribute::Timestamps,
"ownership" => Self::Ownership,
"timestamps" => Self::Timestamps,
#[cfg(feature = "feat_selinux")]
"context" => Attribute::Context,
"links" => Attribute::Links,
"xattr" => Attribute::Xattr,
"context" => Self::Context,
"links" => Self::Links,
"xattr" => Self::Xattr,
_ => {
return Err(Error::InvalidArgument(format!(
"invalid attribute {}",
@@ -577,7 +577,7 @@ fn add_all_attributes() -> Vec<Attribute> {
}
impl Options {
fn from_matches(matches: &ArgMatches) -> CopyResult<Options> {
fn from_matches(matches: &ArgMatches) -> CopyResult<Self> {
let not_implemented_opts = vec![
options::COPY_CONTENTS,
options::SPARSE,
@@ -646,7 +646,7 @@ impl Options {
// if not executed first.
preserve_attributes.sort_unstable();
let options = Options {
let options = Self {
attributes_only: matches.is_present(options::ATTRIBUTES_ONLY),
copy_contents: matches.is_present(options::COPY_CONTENTS),
copy_mode: CopyMode::from_matches(matches),
@@ -703,11 +703,11 @@ impl TargetType {
///
/// Treat target as a dir if we have multiple sources or the target
/// exists and already is a directory
fn determine(sources: &[Source], target: &TargetSlice) -> TargetType {
fn determine(sources: &[Source], target: &TargetSlice) -> Self {
if sources.len() > 1 || target.is_dir() {
TargetType::Directory
Self::Directory
} else {
TargetType::File
Self::File
}
}
}
+4 -4
View File
@@ -57,13 +57,13 @@ pub struct CsplitOptions {
}
impl CsplitOptions {
fn new(matches: &ArgMatches) -> CsplitOptions {
fn new(matches: &ArgMatches) -> Self {
let keep_files = matches.is_present(options::KEEP_FILES);
let quiet = matches.is_present(options::QUIET);
let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES);
let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED);
CsplitOptions {
Self {
split_name: crash_if_err!(
1,
SplitName::new(
@@ -477,8 +477,8 @@ impl<I> InputSplitter<I>
where
I: Iterator<Item = (usize, io::Result<String>)>,
{
fn new(iter: I) -> InputSplitter<I> {
InputSplitter {
fn new(iter: I) -> Self {
Self {
iter,
buffer: Vec::new(),
rewind: false,
+1 -1
View File
@@ -35,7 +35,7 @@ pub enum CsplitError {
impl From<io::Error> for CsplitError {
fn from(error: io::Error) -> Self {
CsplitError::IoError(error)
Self::IoError(error)
}
}
+4 -4
View File
@@ -44,8 +44,8 @@ pub enum ExecutePattern {
impl ExecutePattern {
pub fn iter(&self) -> ExecutePatternIter {
match self {
ExecutePattern::Times(n) => ExecutePatternIter::new(Some(*n)),
ExecutePattern::Always => ExecutePatternIter::new(None),
Self::Times(n) => ExecutePatternIter::new(Some(*n)),
Self::Always => ExecutePatternIter::new(None),
}
}
}
@@ -56,8 +56,8 @@ pub struct ExecutePatternIter {
}
impl ExecutePatternIter {
fn new(max: Option<usize>) -> ExecutePatternIter {
ExecutePatternIter { max, cur: 0 }
fn new(max: Option<usize>) -> Self {
Self { max, cur: 0 }
}
}
+2 -2
View File
@@ -29,7 +29,7 @@ impl SplitName {
prefix_opt: Option<String>,
format_opt: Option<String>,
n_digits_opt: Option<String>,
) -> Result<SplitName, CsplitError> {
) -> Result<Self, CsplitError> {
// get the prefix
let prefix = prefix_opt.unwrap_or_else(|| "xx".to_string());
// the width for the split offset
@@ -231,7 +231,7 @@ impl SplitName {
}
};
Ok(SplitName { fn_split_name })
Ok(Self { fn_split_name })
}
/// Returns the filename of the i-th split.
+8 -8
View File
@@ -111,11 +111,11 @@ enum Iso8601Format {
impl<'a> From<&'a str> for Iso8601Format {
fn from(s: &str) -> Self {
match s {
HOURS | HOUR => Iso8601Format::Hours,
MINUTES | MINUTE => Iso8601Format::Minutes,
SECONDS | SECOND => Iso8601Format::Seconds,
NS => Iso8601Format::Ns,
DATE => Iso8601Format::Date,
HOURS | HOUR => Self::Hours,
MINUTES | MINUTE => Self::Minutes,
SECONDS | SECOND => Self::Seconds,
NS => Self::Ns,
DATE => Self::Date,
// Should be caught by clap
_ => panic!("Invalid format: {}", s),
}
@@ -131,9 +131,9 @@ enum Rfc3339Format {
impl<'a> From<&'a str> for Rfc3339Format {
fn from(s: &str) -> Self {
match s {
DATE => Rfc3339Format::Date,
SECONDS | SECOND => Rfc3339Format::Seconds,
NS => Rfc3339Format::Ns,
DATE => Self::Date,
SECONDS | SECOND => Self::Seconds,
NS => Self::Ns,
// Should be caught by clap
_ => panic!("Invalid format: {}", s),
}
+4 -4
View File
@@ -69,7 +69,7 @@ impl Input<io::Stdin> {
let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?;
let count = parseargs::parse_count(&iflags, matches)?;
let mut i = Input {
let mut i = Self {
src: io::stdin(),
non_ascii,
ibs,
@@ -157,7 +157,7 @@ impl Input<File> {
.map_err_context(|| "failed to seek in input file".to_string())?;
}
let i = Input {
let i = Self {
src,
non_ascii,
ibs,
@@ -306,7 +306,7 @@ impl OutputTrait for Output<io::Stdout> {
.map_err_context(|| String::from("write error"))?;
}
Ok(Output { dst, obs, cflags })
Ok(Self { dst, obs, cflags })
}
fn fsync(&mut self) -> io::Result<()> {
@@ -497,7 +497,7 @@ impl OutputTrait for Output<File> {
.map_err_context(|| "failed to seek in output file".to_string())?;
}
Ok(Output { dst, obs, cflags })
Ok(Self { dst, obs, cflags })
} else {
// The following error should only occur if someone
// mistakenly calls Output::<File>::new() without checking
+3 -3
View File
@@ -296,9 +296,9 @@ impl std::str::FromStr for StatusLevel {
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"none" => Ok(StatusLevel::None),
"noxfer" => Ok(StatusLevel::Noxfer),
"progress" => Ok(StatusLevel::Progress),
"none" => Ok(Self::None),
"noxfer" => Ok(Self::Noxfer),
"progress" => Ok(Self::Progress),
_ => Err(ParseError::StatusLevelNotRecognized(s.to_string())),
}
}
+8 -10
View File
@@ -52,6 +52,7 @@ static OPT_EXCLUDE_TYPE: &str = "exclude-type";
/// Store names of file systems as a selector.
/// Note: `exclude` takes priority over `include`.
#[derive(Default)]
struct FsSelector {
include: HashSet<String>,
exclude: HashSet<String>,
@@ -79,11 +80,8 @@ fn usage() -> String {
}
impl FsSelector {
fn new() -> FsSelector {
FsSelector {
include: HashSet::new(),
exclude: HashSet::new(),
}
fn new() -> Self {
Self::default()
}
#[inline(always)]
@@ -105,8 +103,8 @@ impl FsSelector {
}
impl Options {
fn new() -> Options {
Options {
fn new() -> Self {
Self {
show_local_fs: false,
show_all_fs: false,
show_listed_fs: false,
@@ -124,7 +122,7 @@ impl Options {
impl Filesystem {
// TODO: resolve uuid in `mount_info.dev_name` if exists
fn new(mount_info: MountInfo) -> Option<Filesystem> {
fn new(mount_info: MountInfo) -> Option<Self> {
let _stat_path = if !mount_info.mount_dir.is_empty() {
mount_info.mount_dir.clone()
} else {
@@ -145,14 +143,14 @@ impl Filesystem {
if statfs_fn(path.as_ptr(), &mut statvfs) < 0 {
None
} else {
Some(Filesystem {
Some(Self {
mount_info,
usage: FsUsage::new(statvfs),
})
}
}
#[cfg(windows)]
Some(Filesystem {
Some(Self {
mount_info,
usage: FsUsage::new(Path::new(&_stat_path)),
})
+6 -6
View File
@@ -114,7 +114,7 @@ struct Stat {
}
impl Stat {
fn new(path: PathBuf, options: &Options) -> Result<Stat> {
fn new(path: PathBuf, options: &Options) -> Result<Self> {
let metadata = if options.dereference {
fs::metadata(&path)?
} else {
@@ -127,7 +127,7 @@ impl Stat {
dev_id: metadata.dev(),
};
#[cfg(not(windows))]
return Ok(Stat {
return Ok(Self {
path,
is_dir: metadata.is_dir(),
size: metadata.len(),
@@ -815,9 +815,9 @@ impl FromStr for Threshold {
let size = u64::try_from(parse_size(&s[offset..])?).unwrap();
if s.starts_with('-') {
Ok(Threshold::Upper(size))
Ok(Self::Upper(size))
} else {
Ok(Threshold::Lower(size))
Ok(Self::Lower(size))
}
}
}
@@ -825,8 +825,8 @@ impl FromStr for Threshold {
impl Threshold {
fn should_exclude(&self, size: u64) -> bool {
match *self {
Threshold::Upper(threshold) => size > threshold,
Threshold::Lower(threshold) => size < threshold,
Self::Upper(threshold) => size > threshold,
Self::Lower(threshold) => size < threshold,
}
}
}
+2 -2
View File
@@ -133,7 +133,7 @@ struct Options {
}
impl Options {
fn new(matches: &ArgMatches) -> Options {
fn new(matches: &ArgMatches) -> Self {
let (remaining_mode, tabstops) = match matches.value_of(options::TABS) {
Some(s) => tabstops_parse(s),
None => (RemainingMode::None, vec![DEFAULT_TABSTOP]),
@@ -160,7 +160,7 @@ impl Options {
None => vec!["-".to_owned()],
};
Options {
Self {
files,
tabstops,
tspaces,
+6 -6
View File
@@ -66,23 +66,23 @@ impl AstNode {
}
}
fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<AstNode> {
Box::new(AstNode::Node {
fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<Self> {
Box::new(Self::Node {
token_idx,
op_type: op_type.into(),
operands,
})
}
fn new_leaf(token_idx: usize, value: &str) -> Box<AstNode> {
Box::new(AstNode::Leaf {
fn new_leaf(token_idx: usize, value: &str) -> Box<Self> {
Box::new(Self::Leaf {
token_idx,
value: value.into(),
})
}
pub fn evaluate(&self) -> Result<String, String> {
match self {
AstNode::Leaf { value, .. } => Ok(value.clone()),
AstNode::Node { op_type, .. } => match self.operand_values() {
Self::Leaf { value, .. } => Ok(value.clone()),
Self::Node { op_type, .. } => match self.operand_values() {
Err(reason) => Err(reason),
Ok(operand_values) => match op_type.as_ref() {
"+" => {
+4 -4
View File
@@ -42,25 +42,25 @@ pub enum Token {
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Token::InfixOp {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Token::Value { value: v.into() }
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Token::InfixOp { value, .. } => value == "+",
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Token::Value { value, .. } => value.parse::<BigInt>().is_ok(),
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
+14 -14
View File
@@ -15,6 +15,7 @@ use std::slice::Iter;
/// This is a reasonably efficient implementation based on
/// O'Neill, M. E. "[The Genuine Sieve of Eratosthenes.](http://dx.doi.org/10.1017%2FS0956796808007004)"
/// Journal of Functional Programming, Volume 19, Issue 1, 2009, pp. 95--106.
#[derive(Default)]
pub struct Sieve {
inner: Wheel,
filts: PrimeHeap,
@@ -58,23 +59,20 @@ impl Iterator for Sieve {
}
impl Sieve {
fn new() -> Sieve {
Sieve {
inner: Wheel::new(),
filts: PrimeHeap::new(),
}
fn new() -> Self {
Self::default()
}
#[allow(dead_code)]
#[inline]
pub fn primes() -> PrimeSieve {
INIT_PRIMES.iter().copied().chain(Sieve::new())
INIT_PRIMES.iter().copied().chain(Self::new())
}
#[allow(dead_code)]
#[inline]
pub fn odd_primes() -> PrimeSieve {
INIT_PRIMES[1..].iter().copied().chain(Sieve::new())
INIT_PRIMES[1..].iter().copied().chain(Self::new())
}
}
@@ -106,14 +104,20 @@ impl Iterator for Wheel {
impl Wheel {
#[inline]
fn new() -> Wheel {
Wheel {
fn new() -> Self {
Self {
next: 11u64,
increment: WHEEL_INCS.iter().cycle(),
}
}
}
impl Default for Wheel {
fn default() -> Self {
Self::new()
}
}
/// The increments of a wheel of circumference 210
/// (i.e., a wheel that skips all multiples of 2, 3, 5, 7)
const WHEEL_INCS: &[u64] = &[
@@ -124,16 +128,12 @@ const INIT_PRIMES: &[u64] = &[2, 3, 5, 7];
/// A min-heap of "infinite lists" of prime multiples, where a list is
/// represented as (head, increment).
#[derive(Debug)]
#[derive(Debug, Default)]
struct PrimeHeap {
data: Vec<(u64, u64)>,
}
impl PrimeHeap {
fn new() -> PrimeHeap {
PrimeHeap { data: Vec::new() }
}
fn peek(&self) -> Option<(u64, u64)> {
if let Some(&(x, y)) = self.data.get(0) {
Some((x, y))
+8 -8
View File
@@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table};
type Exponent = u8;
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
// spell-checker:ignore (names) ErdősKac * Erdős Kac
@@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
const NUM_FACTORS_INLINE: usize = 5;
impl Decomposition {
fn one() -> Decomposition {
Decomposition(SmallVec::new())
fn one() -> Self {
Self::default()
}
fn add(&mut self, factor: u64, exp: Exponent) {
@@ -51,7 +51,7 @@ impl Decomposition {
}
impl PartialEq for Decomposition {
fn eq(&self, other: &Decomposition) -> bool {
fn eq(&self, other: &Self) -> bool {
for p in &self.0 {
if other.get(p.0) != Some(p) {
return false;
@@ -73,8 +73,8 @@ impl Eq for Decomposition {}
pub struct Factors(RefCell<Decomposition>);
impl Factors {
pub fn one() -> Factors {
Factors(RefCell::new(Decomposition::one()))
pub fn one() -> Self {
Self(RefCell::new(Decomposition::one()))
}
pub fn add(&mut self, prime: u64, exp: Exponent) {
@@ -286,9 +286,9 @@ impl quickcheck::Arbitrary for Factors {
impl std::ops::BitXor<Exponent> for Factors {
type Output = Self;
fn bitxor(self, rhs: Exponent) -> Factors {
fn bitxor(self, rhs: Exponent) -> Self {
debug_assert_ne!(rhs, 0);
let mut r = Factors::one();
let mut r = Self::one();
for (p, e) in self.0.borrow().0.iter() {
r.add(*p, rhs * e);
}
+1 -1
View File
@@ -42,7 +42,7 @@ pub(crate) enum Result {
impl Result {
pub(crate) fn is_prime(&self) -> bool {
*self == Result::Prime
*self == Self::Prime
}
}
+1 -1
View File
@@ -106,7 +106,7 @@ impl<T: DoubleInt> Arithmetic for Montgomery<T> {
let n = T::from_u64(n);
let a = modular_inverse(n).wrapping_neg();
debug_assert_eq!(n.wrapping_mul(&a), T::one().wrapping_neg());
Montgomery { a, n }
Self { a, n }
}
fn modulus(&self) -> u64 {
+1 -1
View File
@@ -61,7 +61,7 @@ macro_rules! double_int {
fn as_double_width(self) -> $y {
self as _
}
fn from_double_width(n: $y) -> $x {
fn from_double_width(n: $y) -> Self {
n as _
}
}
+3 -3
View File
@@ -40,7 +40,7 @@ pub trait Digest {
impl Digest for md5::Context {
fn new() -> Self {
md5::Context::new()
Self::new()
}
fn input(&mut self, input: &[u8]) {
@@ -52,7 +52,7 @@ impl Digest for md5::Context {
}
fn reset(&mut self) {
*self = md5::Context::new();
*self = Self::new();
}
fn output_bits(&self) -> usize {
@@ -85,7 +85,7 @@ impl Digest for blake2b_simd::State {
impl Digest for sha1::Sha1 {
fn new() -> Self {
sha1::Sha1::new()
Self::new()
}
fn input(&mut self, input: &[u8]) {

Some files were not shown because too many files have changed in this diff Show More