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:
parent
2f85610cc3
commit
ba45fe312a
79 changed files with 445 additions and 474 deletions
|
@ -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,
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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),
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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())),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)),
|
||||
})
|
||||
|
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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() {
|
||||
"+" => {
|
||||
|
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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))
|
||||
|
|
|
@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table};
|
|||
|
||||
type Exponent = u8;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
|
||||
|
||||
// spell-checker:ignore (names) Erdős–Kac * Erdős Kac
|
||||
|
@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
|
|||
const NUM_FACTORS_INLINE: usize = 5;
|
||||
|
||||
impl Decomposition {
|
||||
fn one() -> Decomposition {
|
||||
Decomposition(SmallVec::new())
|
||||
fn one() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn add(&mut self, factor: u64, exp: Exponent) {
|
||||
|
@ -51,7 +51,7 @@ impl Decomposition {
|
|||
}
|
||||
|
||||
impl PartialEq for Decomposition {
|
||||
fn eq(&self, other: &Decomposition) -> bool {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
for p in &self.0 {
|
||||
if other.get(p.0) != Some(p) {
|
||||
return false;
|
||||
|
@ -73,8 +73,8 @@ impl Eq for Decomposition {}
|
|||
pub struct Factors(RefCell<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);
|
||||
}
|
||||
|
|
|
@ -42,7 +42,7 @@ pub(crate) enum Result {
|
|||
|
||||
impl Result {
|
||||
pub(crate) fn is_prime(&self) -> bool {
|
||||
*self == Result::Prime
|
||||
*self == Self::Prime
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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 _
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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]) {
|
||||
|
|
|
@ -112,7 +112,7 @@ enum Modes {
|
|||
|
||||
impl Default for Modes {
|
||||
fn default() -> Self {
|
||||
Modes::Lines(10)
|
||||
Self::Lines(10)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -167,7 +167,7 @@ impl HeadOptions {
|
|||
pub fn get_from(args: impl uucore::Args) -> Result<Self, String> {
|
||||
let matches = uu_app().get_matches_from(arg_iterate(args)?);
|
||||
|
||||
let mut options: HeadOptions = Default::default();
|
||||
let mut options = Self::default();
|
||||
|
||||
options.quiet = matches.is_present(options::QUIET_NAME);
|
||||
options.verbose = matches.is_present(options::VERBOSE_NAME);
|
||||
|
|
|
@ -28,7 +28,7 @@ pub struct TakeAllBut<I: Iterator> {
|
|||
}
|
||||
|
||||
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.
|
||||
//
|
||||
// If there are fewer than `n` elements in `iter`, then we
|
||||
|
@ -44,7 +44,7 @@ impl<I: Iterator> TakeAllBut<I> {
|
|||
};
|
||||
buf.push_back(value);
|
||||
}
|
||||
TakeAllBut { iter, buf }
|
||||
Self { iter, buf }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -63,8 +63,8 @@ struct Settings {
|
|||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Settings {
|
||||
Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
key1: 0,
|
||||
key2: 0,
|
||||
print_unpaired1: false,
|
||||
|
@ -163,8 +163,8 @@ struct Input {
|
|||
}
|
||||
|
||||
impl Input {
|
||||
fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Input {
|
||||
Input {
|
||||
fn new(separator: Sep, ignore_case: bool, check_order: CheckOrder) -> Self {
|
||||
Self {
|
||||
separator,
|
||||
ignore_case,
|
||||
check_order,
|
||||
|
@ -198,14 +198,14 @@ enum Spec {
|
|||
}
|
||||
|
||||
impl Spec {
|
||||
fn parse(format: &str) -> UResult<Spec> {
|
||||
fn parse(format: &str) -> UResult<Self> {
|
||||
let mut chars = format.chars();
|
||||
|
||||
let file_num = match chars.next() {
|
||||
Some('0') => {
|
||||
// Must be all alone without a field specifier.
|
||||
if chars.next().is_none() {
|
||||
return Ok(Spec::Key);
|
||||
return Ok(Self::Key);
|
||||
}
|
||||
return Err(USimpleError::new(
|
||||
1,
|
||||
|
@ -223,7 +223,7 @@ impl Spec {
|
|||
};
|
||||
|
||||
if let Some('.') = chars.next() {
|
||||
return Ok(Spec::Field(file_num, parse_field_number(chars.as_str())?));
|
||||
return Ok(Self::Field(file_num, parse_field_number(chars.as_str())?));
|
||||
}
|
||||
|
||||
Err(USimpleError::new(
|
||||
|
@ -239,7 +239,7 @@ struct Line {
|
|||
}
|
||||
|
||||
impl Line {
|
||||
fn new(string: Vec<u8>, separator: Sep) -> Line {
|
||||
fn new(string: Vec<u8>, separator: Sep) -> Self {
|
||||
let fields = match separator {
|
||||
Sep::Whitespaces => string
|
||||
// GNU join uses Bourne shell field splitters by default
|
||||
|
@ -251,7 +251,7 @@ impl Line {
|
|||
Sep::Line => vec![string.clone()],
|
||||
};
|
||||
|
||||
Line { fields, string }
|
||||
Self { fields, string }
|
||||
}
|
||||
|
||||
/// Get field at index.
|
||||
|
|
|
@ -339,7 +339,7 @@ struct PaddingCollection {
|
|||
|
||||
impl Config {
|
||||
#[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 (mut format, opt) = if let Some(format_) = options.value_of(options::FORMAT) {
|
||||
(
|
||||
|
@ -661,7 +661,7 @@ impl Config {
|
|||
Dereference::DirArgs
|
||||
};
|
||||
|
||||
Ok(Config {
|
||||
Ok(Self {
|
||||
format,
|
||||
files,
|
||||
sort,
|
||||
|
|
|
@ -79,8 +79,8 @@ impl Iterator for EscapeOctal {
|
|||
}
|
||||
|
||||
impl EscapeOctal {
|
||||
fn from(c: char) -> EscapeOctal {
|
||||
EscapeOctal {
|
||||
fn from(c: char) -> Self {
|
||||
Self {
|
||||
c,
|
||||
idx: 2,
|
||||
state: EscapeOctalState::Backslash,
|
||||
|
|
|
@ -18,7 +18,7 @@ impl Clone for FormatWriter {
|
|||
}
|
||||
|
||||
impl PartialEq for FormatWriter {
|
||||
fn eq(&self, other: &FormatWriter) -> bool {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
use crate::formatteriteminfo::FormatWriter::*;
|
||||
|
||||
match (self, other) {
|
||||
|
|
|
@ -19,8 +19,8 @@ pub struct InputOffset {
|
|||
|
||||
impl InputOffset {
|
||||
/// creates a new `InputOffset` using the provided values.
|
||||
pub fn new(radix: Radix, byte_pos: usize, label: Option<usize>) -> InputOffset {
|
||||
InputOffset {
|
||||
pub fn new(radix: Radix, byte_pos: usize, label: Option<usize>) -> Self {
|
||||
Self {
|
||||
radix,
|
||||
byte_pos,
|
||||
label,
|
||||
|
|
|
@ -54,8 +54,8 @@ impl FailingMockStream {
|
|||
///
|
||||
/// When `read` or `write` is called, it will return an error `repeat_count` times.
|
||||
/// `kind` and `message` can be specified to define the exact error.
|
||||
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream {
|
||||
FailingMockStream {
|
||||
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message,
|
||||
repeat_count,
|
||||
|
|
|
@ -121,7 +121,7 @@ struct 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) {
|
||||
None => ByteOrder::Native,
|
||||
Some("little") => ByteOrder::Little,
|
||||
|
@ -232,7 +232,7 @@ impl OdOptions {
|
|||
}
|
||||
};
|
||||
|
||||
Ok(OdOptions {
|
||||
Ok(Self {
|
||||
byte_order,
|
||||
skip_bytes,
|
||||
read_bytes,
|
||||
|
|
|
@ -54,7 +54,7 @@ impl OutputInfo {
|
|||
line_bytes: usize,
|
||||
formats: &[ParsedFormatterItemInfo],
|
||||
output_duplicates: bool,
|
||||
) -> OutputInfo {
|
||||
) -> Self {
|
||||
let byte_size_block = formats.iter().fold(1, |max, next| {
|
||||
cmp::max(max, next.formatter_item_info.byte_size)
|
||||
});
|
||||
|
@ -68,9 +68,9 @@ impl OutputInfo {
|
|||
let print_width_line = print_width_block * (line_bytes / byte_size_block);
|
||||
|
||||
let spaced_formatters =
|
||||
OutputInfo::create_spaced_formatter_info(formats, byte_size_block, print_width_block);
|
||||
Self::create_spaced_formatter_info(formats, byte_size_block, print_width_block);
|
||||
|
||||
OutputInfo {
|
||||
Self {
|
||||
byte_size_line: line_bytes,
|
||||
print_width_line,
|
||||
byte_size_block,
|
||||
|
@ -90,7 +90,7 @@ impl OutputInfo {
|
|||
.map(|f| SpacedFormatterItemInfo {
|
||||
formatter_item_info: f.formatter_item_info,
|
||||
add_ascii_dump: f.add_ascii_dump,
|
||||
spacing: OutputInfo::calculate_alignment(f, byte_size_block, print_width_block),
|
||||
spacing: Self::calculate_alignment(f, byte_size_block, print_width_block),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
|
|
@ -14,11 +14,8 @@ pub struct ParsedFormatterItemInfo {
|
|||
}
|
||||
|
||||
impl ParsedFormatterItemInfo {
|
||||
pub fn new(
|
||||
formatter_item_info: FormatterItemInfo,
|
||||
add_ascii_dump: bool,
|
||||
) -> ParsedFormatterItemInfo {
|
||||
ParsedFormatterItemInfo {
|
||||
pub fn new(formatter_item_info: FormatterItemInfo, add_ascii_dump: bool) -> Self {
|
||||
Self {
|
||||
formatter_item_info,
|
||||
add_ascii_dump,
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ impl<R> PartialReader<R> {
|
|||
/// `skip` bytes, and limits the output to `limit` bytes. Set `limit`
|
||||
/// to `None` if there should be no limit.
|
||||
pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self {
|
||||
PartialReader { inner, skip, limit }
|
||||
Self { inner, skip, limit }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -43,7 +43,7 @@ pub struct PeekReader<R> {
|
|||
impl<R> PeekReader<R> {
|
||||
/// Create a new `PeekReader` wrapping `inner`
|
||||
pub fn new(inner: R) -> Self {
|
||||
PeekReader {
|
||||
Self {
|
||||
inner,
|
||||
temp_buffer: Vec::new(),
|
||||
}
|
||||
|
|
|
@ -112,8 +112,8 @@ struct NumberingMode {
|
|||
}
|
||||
|
||||
impl Default for NumberingMode {
|
||||
fn default() -> NumberingMode {
|
||||
NumberingMode {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
width: 5,
|
||||
separator: TAB.to_string(),
|
||||
first_number: 1,
|
||||
|
@ -122,8 +122,8 @@ impl Default for NumberingMode {
|
|||
}
|
||||
|
||||
impl Default for FileLine {
|
||||
fn default() -> FileLine {
|
||||
FileLine {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
file_id: 0,
|
||||
line_number: 0,
|
||||
page_number: 0,
|
||||
|
@ -136,7 +136,7 @@ impl Default for FileLine {
|
|||
|
||||
impl From<IOError> for PrError {
|
||||
fn from(err: IOError) -> Self {
|
||||
PrError::EncounteredErrors(err.to_string())
|
||||
Self::EncounteredErrors(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -52,8 +52,8 @@ struct Config {
|
|||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Config {
|
||||
Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
format: OutFormat::Dumb,
|
||||
gnu_ext: true,
|
||||
auto_ref: false,
|
||||
|
@ -96,7 +96,7 @@ struct WordFilter {
|
|||
}
|
||||
|
||||
impl WordFilter {
|
||||
fn new(matches: &clap::ArgMatches, config: &Config) -> UResult<WordFilter> {
|
||||
fn new(matches: &clap::ArgMatches, config: &Config) -> UResult<Self> {
|
||||
let (o, oset): (bool, HashSet<String>) = if matches.is_present(options::ONLY_FILE) {
|
||||
let words =
|
||||
read_word_filter_file(matches, options::ONLY_FILE).map_err_context(String::new)?;
|
||||
|
@ -139,7 +139,7 @@ impl WordFilter {
|
|||
}
|
||||
}
|
||||
};
|
||||
Ok(WordFilter {
|
||||
Ok(Self {
|
||||
only_specified: o,
|
||||
ignore_specified: i,
|
||||
only_set: oset,
|
||||
|
|
|
@ -94,12 +94,12 @@ pub(crate) struct RunconError {
|
|||
}
|
||||
|
||||
impl RunconError {
|
||||
pub(crate) fn new(e: Error) -> RunconError {
|
||||
RunconError::with_code(error_exit_status::ANOTHER_ERROR, e)
|
||||
pub(crate) fn new(e: Error) -> Self {
|
||||
Self::with_code(error_exit_status::ANOTHER_ERROR, e)
|
||||
}
|
||||
|
||||
pub(crate) fn with_code(code: i32, e: Error) -> RunconError {
|
||||
RunconError { inner: e, code }
|
||||
pub(crate) fn with_code(code: i32, e: Error) -> Self {
|
||||
Self { inner: e, code }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -110,10 +110,10 @@ impl From<ExtendedBigInt> for ExtendedBigDecimal {
|
|||
fn from(big_int: ExtendedBigInt) -> Self {
|
||||
match big_int {
|
||||
ExtendedBigInt::BigInt(n) => Self::BigDecimal(BigDecimal::from(n)),
|
||||
ExtendedBigInt::Infinity => ExtendedBigDecimal::Infinity,
|
||||
ExtendedBigInt::MinusInfinity => ExtendedBigDecimal::MinusInfinity,
|
||||
ExtendedBigInt::MinusZero => ExtendedBigDecimal::MinusZero,
|
||||
ExtendedBigInt::Nan => ExtendedBigDecimal::Nan,
|
||||
ExtendedBigInt::Infinity => Self::Infinity,
|
||||
ExtendedBigInt::MinusInfinity => Self::MinusInfinity,
|
||||
ExtendedBigInt::MinusZero => Self::MinusZero,
|
||||
ExtendedBigInt::Nan => Self::Nan,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -124,7 +124,7 @@ impl Display for ExtendedBigDecimal {
|
|||
ExtendedBigDecimal::BigDecimal(x) => {
|
||||
let (n, p) = x.as_bigint_and_exponent();
|
||||
match p {
|
||||
0 => ExtendedBigDecimal::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f),
|
||||
0 => Self::BigDecimal(BigDecimal::new(n * 10, 1)).fmt(f),
|
||||
_ => x.fmt(f),
|
||||
}
|
||||
}
|
||||
|
@ -145,7 +145,7 @@ impl Display for ExtendedBigDecimal {
|
|||
|
||||
impl Zero for ExtendedBigDecimal {
|
||||
fn zero() -> Self {
|
||||
ExtendedBigDecimal::BigDecimal(BigDecimal::zero())
|
||||
Self::BigDecimal(BigDecimal::zero())
|
||||
}
|
||||
fn is_zero(&self) -> bool {
|
||||
match self {
|
||||
|
|
|
@ -42,7 +42,7 @@ impl ExtendedBigInt {
|
|||
// We would like to implement `num_traits::One`, but it requires
|
||||
// a multiplication implementation, and we don't want to
|
||||
// implement that here.
|
||||
ExtendedBigInt::BigInt(BigInt::one())
|
||||
Self::BigInt(BigInt::one())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -51,10 +51,10 @@ impl From<ExtendedBigDecimal> for ExtendedBigInt {
|
|||
match big_decimal {
|
||||
// TODO When can this fail?
|
||||
ExtendedBigDecimal::BigDecimal(x) => Self::BigInt(x.to_bigint().unwrap()),
|
||||
ExtendedBigDecimal::Infinity => ExtendedBigInt::Infinity,
|
||||
ExtendedBigDecimal::MinusInfinity => ExtendedBigInt::MinusInfinity,
|
||||
ExtendedBigDecimal::MinusZero => ExtendedBigInt::MinusZero,
|
||||
ExtendedBigDecimal::Nan => ExtendedBigInt::Nan,
|
||||
ExtendedBigDecimal::Infinity => Self::Infinity,
|
||||
ExtendedBigDecimal::MinusInfinity => Self::MinusInfinity,
|
||||
ExtendedBigDecimal::MinusZero => Self::MinusZero,
|
||||
ExtendedBigDecimal::Nan => Self::Nan,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -62,22 +62,22 @@ impl From<ExtendedBigDecimal> for ExtendedBigInt {
|
|||
impl Display for ExtendedBigInt {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ExtendedBigInt::BigInt(n) => n.fmt(f),
|
||||
ExtendedBigInt::Infinity => f32::INFINITY.fmt(f),
|
||||
ExtendedBigInt::MinusInfinity => f32::NEG_INFINITY.fmt(f),
|
||||
ExtendedBigInt::MinusZero => {
|
||||
Self::BigInt(n) => n.fmt(f),
|
||||
Self::Infinity => f32::INFINITY.fmt(f),
|
||||
Self::MinusInfinity => f32::NEG_INFINITY.fmt(f),
|
||||
Self::MinusZero => {
|
||||
// FIXME Come up with a way of formatting this with a
|
||||
// "-" prefix.
|
||||
0.fmt(f)
|
||||
}
|
||||
ExtendedBigInt::Nan => "nan".fmt(f),
|
||||
Self::Nan => "nan".fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Zero for ExtendedBigInt {
|
||||
fn zero() -> Self {
|
||||
ExtendedBigInt::BigInt(BigInt::zero())
|
||||
Self::BigInt(BigInt::zero())
|
||||
}
|
||||
fn is_zero(&self) -> bool {
|
||||
match self {
|
||||
|
|
|
@ -42,7 +42,7 @@ impl Number {
|
|||
// We would like to implement `num_traits::One`, but it requires
|
||||
// a multiplication implementation, and we don't want to
|
||||
// implement that here.
|
||||
Number::Int(ExtendedBigInt::one())
|
||||
Self::Int(ExtendedBigInt::one())
|
||||
}
|
||||
|
||||
/// Round this number towards the given other number.
|
||||
|
@ -89,12 +89,8 @@ pub struct PreciseNumber {
|
|||
}
|
||||
|
||||
impl PreciseNumber {
|
||||
pub fn new(
|
||||
number: Number,
|
||||
num_integral_digits: usize,
|
||||
num_fractional_digits: usize,
|
||||
) -> PreciseNumber {
|
||||
PreciseNumber {
|
||||
pub fn new(number: Number, num_integral_digits: usize, num_fractional_digits: usize) -> Self {
|
||||
Self {
|
||||
number,
|
||||
num_integral_digits,
|
||||
num_fractional_digits,
|
||||
|
@ -106,7 +102,7 @@ impl PreciseNumber {
|
|||
// We would like to implement `num_traits::One`, but it requires
|
||||
// a multiplication implementation, and we don't want to
|
||||
// implement that here.
|
||||
PreciseNumber::new(Number::one(), 1, 0)
|
||||
Self::new(Number::one(), 1, 0)
|
||||
}
|
||||
|
||||
/// Decide whether this number is zero (either positive or negative).
|
||||
|
|
|
@ -68,9 +68,9 @@ struct FilenameGenerator {
|
|||
}
|
||||
|
||||
impl FilenameGenerator {
|
||||
fn new(name_len: usize) -> FilenameGenerator {
|
||||
fn new(name_len: usize) -> Self {
|
||||
let indices: Vec<usize> = vec![0; name_len];
|
||||
FilenameGenerator {
|
||||
Self {
|
||||
name_len,
|
||||
name_charset_indices: RefCell::new(indices),
|
||||
exhausted: Cell::new(false),
|
||||
|
|
|
@ -38,8 +38,8 @@ pub struct ReadRng<R> {
|
|||
|
||||
impl<R: Read> ReadRng<R> {
|
||||
/// Create a new `ReadRng` from a `Read`.
|
||||
pub fn new(r: R) -> ReadRng<R> {
|
||||
ReadRng { reader: r }
|
||||
pub fn new(r: R) -> Self {
|
||||
Self { reader: r }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -100,7 +100,7 @@ pub struct RecycledChunk {
|
|||
|
||||
impl RecycledChunk {
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
RecycledChunk {
|
||||
Self {
|
||||
lines: Vec::new(),
|
||||
selections: Vec::new(),
|
||||
num_infos: Vec::new(),
|
||||
|
|
|
@ -415,7 +415,7 @@ impl WriteableTmpFile for WriteablePlainTmpFile {
|
|||
type InnerWrite = BufWriter<File>;
|
||||
|
||||
fn create((file, path): (File, PathBuf), _: Option<&str>) -> UResult<Self> {
|
||||
Ok(WriteablePlainTmpFile {
|
||||
Ok(Self {
|
||||
file: BufWriter::new(file),
|
||||
path,
|
||||
})
|
||||
|
@ -484,7 +484,7 @@ impl WriteableTmpFile for WriteableCompressedTmpFile {
|
|||
code: err.raw_os_error().unwrap(),
|
||||
})?;
|
||||
let child_stdin = child.stdin.take().unwrap();
|
||||
Ok(WriteableCompressedTmpFile {
|
||||
Ok(Self {
|
||||
path,
|
||||
compress_prog: compress_prog.to_owned(),
|
||||
child,
|
||||
|
|
|
@ -85,12 +85,12 @@ impl NumInfo {
|
|||
let has_si_unit = parse_settings.accept_si_units
|
||||
&& matches!(char, 'K' | 'k' | 'M' | 'G' | 'T' | 'P' | 'E' | 'Z' | 'Y');
|
||||
(
|
||||
NumInfo { exponent, sign },
|
||||
Self { exponent, sign },
|
||||
start..if has_si_unit { idx + 1 } else { idx },
|
||||
)
|
||||
} else {
|
||||
(
|
||||
NumInfo {
|
||||
Self {
|
||||
sign: Sign::Positive,
|
||||
exponent: 0,
|
||||
},
|
||||
|
@ -127,10 +127,10 @@ impl NumInfo {
|
|||
}
|
||||
}
|
||||
if let Some(start) = start {
|
||||
(NumInfo { exponent, sign }, start..num.len())
|
||||
(Self { exponent, sign }, start..num.len())
|
||||
} else {
|
||||
(
|
||||
NumInfo {
|
||||
Self {
|
||||
sign: Sign::Positive,
|
||||
exponent: 0,
|
||||
},
|
||||
|
|
|
@ -323,7 +323,7 @@ pub struct GlobalSettings {
|
|||
|
||||
/// Data needed for sorting. Should be computed once before starting to sort
|
||||
/// by calling `GlobalSettings::init_precomputed`.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Precomputed {
|
||||
needs_tokens: bool,
|
||||
num_infos_per_line: usize,
|
||||
|
@ -378,8 +378,8 @@ impl GlobalSettings {
|
|||
}
|
||||
|
||||
impl Default for GlobalSettings {
|
||||
fn default() -> GlobalSettings {
|
||||
GlobalSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: SortMode::Default,
|
||||
debug: false,
|
||||
ignore_leading_blanks: false,
|
||||
|
@ -400,12 +400,7 @@ impl Default for GlobalSettings {
|
|||
buffer_size: DEFAULT_BUF_SIZE,
|
||||
compress_prog: None,
|
||||
merge_batch_size: 32,
|
||||
precomputed: Precomputed {
|
||||
num_infos_per_line: 0,
|
||||
floats_per_line: 0,
|
||||
selections_per_line: 0,
|
||||
needs_tokens: false,
|
||||
},
|
||||
precomputed: Precomputed::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -784,7 +779,7 @@ impl KeyPosition {
|
|||
|
||||
impl Default for KeyPosition {
|
||||
fn default() -> Self {
|
||||
KeyPosition {
|
||||
Self {
|
||||
field: 1,
|
||||
char: 1,
|
||||
ignore_blanks: false,
|
||||
|
|
|
@ -39,10 +39,10 @@ struct WithEnvVarSet {
|
|||
}
|
||||
impl WithEnvVarSet {
|
||||
/// Save previous value assigned to key, set key=value
|
||||
fn new(key: &str, value: &str) -> WithEnvVarSet {
|
||||
fn new(key: &str, value: &str) -> Self {
|
||||
let previous_env_value = env::var(key);
|
||||
env::set_var(key, value);
|
||||
WithEnvVarSet {
|
||||
Self {
|
||||
_previous_var_key: String::from(key),
|
||||
_previous_var_value: previous_env_value,
|
||||
}
|
||||
|
@ -66,7 +66,7 @@ impl FilterWriter {
|
|||
///
|
||||
/// * `command` - The shell command to execute
|
||||
/// * `filepath` - Path of the output file (forwarded to command as $FILE)
|
||||
fn new(command: &str, filepath: &str) -> FilterWriter {
|
||||
fn new(command: &str, filepath: &str) -> Self {
|
||||
// set $FILE, save previous value (if there was one)
|
||||
let _with_env_var_set = WithEnvVarSet::new("FILE", filepath);
|
||||
|
||||
|
@ -78,7 +78,7 @@ impl FilterWriter {
|
|||
.spawn()
|
||||
.expect("Couldn't spawn filter command");
|
||||
|
||||
FilterWriter { shell_process }
|
||||
Self { shell_process }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -182,31 +182,31 @@ impl Strategy {
|
|||
matches.occurrences_of(OPT_LINE_BYTES),
|
||||
matches.occurrences_of(OPT_NUMBER),
|
||||
) {
|
||||
(0, 0, 0, 0) => Ok(Strategy::Lines(1000)),
|
||||
(0, 0, 0, 0) => Ok(Self::Lines(1000)),
|
||||
(1, 0, 0, 0) => {
|
||||
let s = matches.value_of(OPT_LINES).unwrap();
|
||||
let n = parse_size(s)
|
||||
.map_err(|e| USimpleError::new(1, format!("invalid number of lines: {}", e)))?;
|
||||
Ok(Strategy::Lines(n))
|
||||
Ok(Self::Lines(n))
|
||||
}
|
||||
(0, 1, 0, 0) => {
|
||||
let s = matches.value_of(OPT_BYTES).unwrap();
|
||||
let n = parse_size(s)
|
||||
.map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?;
|
||||
Ok(Strategy::Bytes(n))
|
||||
Ok(Self::Bytes(n))
|
||||
}
|
||||
(0, 0, 1, 0) => {
|
||||
let s = matches.value_of(OPT_LINE_BYTES).unwrap();
|
||||
let n = parse_size(s)
|
||||
.map_err(|e| USimpleError::new(1, format!("invalid number of bytes: {}", e)))?;
|
||||
Ok(Strategy::LineBytes(n))
|
||||
Ok(Self::LineBytes(n))
|
||||
}
|
||||
(0, 0, 0, 1) => {
|
||||
let s = matches.value_of(OPT_NUMBER).unwrap();
|
||||
let n = s.parse::<usize>().map_err(|e| {
|
||||
USimpleError::new(1, format!("invalid number of chunks: {}", e))
|
||||
})?;
|
||||
Ok(Strategy::Number(n))
|
||||
Ok(Self::Number(n))
|
||||
}
|
||||
_ => Err(UUsageError::new(1, "cannot split in more than one way")),
|
||||
}
|
||||
|
@ -232,7 +232,7 @@ struct Settings {
|
|||
impl Settings {
|
||||
/// Parse a strategy from the command-line arguments.
|
||||
fn from(matches: ArgMatches) -> UResult<Self> {
|
||||
let result = Settings {
|
||||
let result = Self {
|
||||
suffix_length: matches
|
||||
.value_of(OPT_SUFFIX_LENGTH)
|
||||
.unwrap()
|
||||
|
@ -275,8 +275,8 @@ struct LineSplitter {
|
|||
}
|
||||
|
||||
impl LineSplitter {
|
||||
fn new(chunk_size: usize) -> LineSplitter {
|
||||
LineSplitter {
|
||||
fn new(chunk_size: usize) -> Self {
|
||||
Self {
|
||||
lines_per_split: chunk_size,
|
||||
}
|
||||
}
|
||||
|
@ -314,8 +314,8 @@ struct ByteSplitter {
|
|||
}
|
||||
|
||||
impl ByteSplitter {
|
||||
fn new(chunk_size: usize) -> ByteSplitter {
|
||||
ByteSplitter {
|
||||
fn new(chunk_size: usize) -> Self {
|
||||
Self {
|
||||
bytes_per_split: u128::try_from(chunk_size).unwrap(),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -461,7 +461,7 @@ impl Stater {
|
|||
Ok(tokens)
|
||||
}
|
||||
|
||||
fn new(matches: &ArgMatches) -> UResult<Stater> {
|
||||
fn new(matches: &ArgMatches) -> UResult<Self> {
|
||||
let files: Vec<String> = matches
|
||||
.values_of(ARG_FILES)
|
||||
.map(|v| v.map(ToString::to_string).collect())
|
||||
|
@ -480,12 +480,12 @@ impl Stater {
|
|||
let show_fs = matches.is_present(options::FILE_SYSTEM);
|
||||
|
||||
let default_tokens = if format_str.is_empty() {
|
||||
Stater::generate_tokens(&Stater::default_format(show_fs, terse, false), use_printf)?
|
||||
Self::generate_tokens(&Self::default_format(show_fs, terse, false), use_printf)?
|
||||
} else {
|
||||
Stater::generate_tokens(format_str, use_printf)?
|
||||
Self::generate_tokens(format_str, use_printf)?
|
||||
};
|
||||
let default_dev_tokens =
|
||||
Stater::generate_tokens(&Stater::default_format(show_fs, terse, true), use_printf)?;
|
||||
Self::generate_tokens(&Self::default_format(show_fs, terse, true), use_printf)?;
|
||||
|
||||
let mount_list = if show_fs {
|
||||
// mount points aren't displayed when showing filesystem information
|
||||
|
@ -501,7 +501,7 @@ impl Stater {
|
|||
Some(mount_list)
|
||||
};
|
||||
|
||||
Ok(Stater {
|
||||
Ok(Self {
|
||||
follow: matches.is_present(options::DEREFERENCE),
|
||||
show_fs,
|
||||
from_user: !format_str.is_empty(),
|
||||
|
|
|
@ -70,7 +70,7 @@ impl<'a> TryFrom<&ArgMatches> for ProgramOptions {
|
|||
type Error = ProgramOptionsError;
|
||||
|
||||
fn try_from(matches: &ArgMatches) -> Result<Self, Self::Error> {
|
||||
Ok(ProgramOptions {
|
||||
Ok(Self {
|
||||
stdin: check_option(matches, options::INPUT)?,
|
||||
stdout: check_option(matches, options::OUTPUT)?,
|
||||
stderr: check_option(matches, options::ERROR)?,
|
||||
|
|
|
@ -25,8 +25,8 @@ pub struct ProcessChecker {
|
|||
}
|
||||
|
||||
impl ProcessChecker {
|
||||
pub fn new(process_id: self::Pid) -> ProcessChecker {
|
||||
ProcessChecker { pid: process_id }
|
||||
pub fn new(process_id: self::Pid) -> Self {
|
||||
Self { pid: process_id }
|
||||
}
|
||||
|
||||
// Borrowing mutably to be aligned with Windows implementation
|
||||
|
|
|
@ -72,7 +72,7 @@ enum FilterMode {
|
|||
|
||||
impl Default for FilterMode {
|
||||
fn default() -> Self {
|
||||
FilterMode::Lines(10, b'\n')
|
||||
Self::Lines(10, b'\n')
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -92,7 +92,7 @@ impl Settings {
|
|||
pub fn get_from(args: impl uucore::Args) -> Result<Self, String> {
|
||||
let matches = uu_app().get_matches_from(arg_iterate(args)?);
|
||||
|
||||
let mut settings: Settings = Settings {
|
||||
let mut settings: Self = Self {
|
||||
sleep_msec: 1000,
|
||||
follow: matches.is_present(options::FOLLOW),
|
||||
..Default::default()
|
||||
|
|
|
@ -44,26 +44,26 @@ impl Symbol {
|
|||
/// Create a new Symbol from an OsString.
|
||||
///
|
||||
/// Returns Symbol::None in place of None
|
||||
fn new(token: Option<OsString>) -> Symbol {
|
||||
fn new(token: Option<OsString>) -> Self {
|
||||
match token {
|
||||
Some(s) => match s.to_str() {
|
||||
Some(t) => match t {
|
||||
"(" => Symbol::LParen,
|
||||
"!" => Symbol::Bang,
|
||||
"-a" | "-o" => Symbol::BoolOp(s),
|
||||
"=" | "==" | "!=" => Symbol::Op(Operator::String(s)),
|
||||
"-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Symbol::Op(Operator::Int(s)),
|
||||
"-ef" | "-nt" | "-ot" => Symbol::Op(Operator::File(s)),
|
||||
"-n" | "-z" => Symbol::UnaryOp(UnaryOperator::StrlenOp(s)),
|
||||
"(" => Self::LParen,
|
||||
"!" => Self::Bang,
|
||||
"-a" | "-o" => Self::BoolOp(s),
|
||||
"=" | "==" | "!=" => Self::Op(Operator::String(s)),
|
||||
"-eq" | "-ge" | "-gt" | "-le" | "-lt" | "-ne" => Self::Op(Operator::Int(s)),
|
||||
"-ef" | "-nt" | "-ot" => Self::Op(Operator::File(s)),
|
||||
"-n" | "-z" => Self::UnaryOp(UnaryOperator::StrlenOp(s)),
|
||||
"-b" | "-c" | "-d" | "-e" | "-f" | "-g" | "-G" | "-h" | "-k" | "-L" | "-O"
|
||||
| "-p" | "-r" | "-s" | "-S" | "-t" | "-u" | "-w" | "-x" => {
|
||||
Symbol::UnaryOp(UnaryOperator::FiletestOp(s))
|
||||
Self::UnaryOp(UnaryOperator::FiletestOp(s))
|
||||
}
|
||||
_ => Symbol::Literal(s),
|
||||
_ => Self::Literal(s),
|
||||
},
|
||||
None => Symbol::Literal(s),
|
||||
None => Self::Literal(s),
|
||||
},
|
||||
None => Symbol::None,
|
||||
None => Self::None,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -74,18 +74,18 @@ impl Symbol {
|
|||
/// # Panics
|
||||
///
|
||||
/// Panics if `self` is Symbol::None
|
||||
fn into_literal(self) -> Symbol {
|
||||
Symbol::Literal(match self {
|
||||
Symbol::LParen => OsString::from("("),
|
||||
Symbol::Bang => OsString::from("!"),
|
||||
Symbol::BoolOp(s)
|
||||
| Symbol::Literal(s)
|
||||
| Symbol::Op(Operator::String(s))
|
||||
| Symbol::Op(Operator::Int(s))
|
||||
| Symbol::Op(Operator::File(s))
|
||||
| Symbol::UnaryOp(UnaryOperator::StrlenOp(s))
|
||||
| Symbol::UnaryOp(UnaryOperator::FiletestOp(s)) => s,
|
||||
Symbol::None => panic!(),
|
||||
fn into_literal(self) -> Self {
|
||||
Self::Literal(match self {
|
||||
Self::LParen => OsString::from("("),
|
||||
Self::Bang => OsString::from("!"),
|
||||
Self::BoolOp(s)
|
||||
| Self::Literal(s)
|
||||
| Self::Op(Operator::String(s))
|
||||
| Self::Op(Operator::Int(s))
|
||||
| Self::Op(Operator::File(s))
|
||||
| Self::UnaryOp(UnaryOperator::StrlenOp(s))
|
||||
| Self::UnaryOp(UnaryOperator::FiletestOp(s)) => s,
|
||||
Self::None => panic!(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -120,8 +120,8 @@ struct Parser {
|
|||
|
||||
impl Parser {
|
||||
/// Construct a new Parser from a `Vec<OsString>` of tokens.
|
||||
fn new(tokens: Vec<OsString>) -> Parser {
|
||||
Parser {
|
||||
fn new(tokens: Vec<OsString>) -> Self {
|
||||
Self {
|
||||
tokens: tokens.into_iter().peekable(),
|
||||
stack: vec![],
|
||||
}
|
||||
|
|
|
@ -57,7 +57,7 @@ struct Config {
|
|||
}
|
||||
|
||||
impl Config {
|
||||
fn from(options: &clap::ArgMatches) -> Config {
|
||||
fn from(options: &clap::ArgMatches) -> Self {
|
||||
let signal = match options.value_of(options::SIGNAL) {
|
||||
Some(signal_) => {
|
||||
let signal_result = signal_by_name_or_value(signal_);
|
||||
|
@ -88,7 +88,7 @@ impl Config {
|
|||
.map(String::from)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Config {
|
||||
Self {
|
||||
foreground,
|
||||
kill_after,
|
||||
signal,
|
||||
|
|
|
@ -140,10 +140,10 @@ impl Sequence {
|
|||
set2_str: &str,
|
||||
truncate_set1_flag: bool,
|
||||
) -> Result<(Vec<char>, Vec<char>), BadSequence> {
|
||||
let set1 = Sequence::from_str(set1_str)?;
|
||||
let set2 = Sequence::from_str(set2_str)?;
|
||||
let set1 = Self::from_str(set1_str)?;
|
||||
let set2 = Self::from_str(set2_str)?;
|
||||
|
||||
let is_char_star = |s: &&Sequence| -> bool { matches!(s, Sequence::CharStar(_)) };
|
||||
let is_char_star = |s: &&Self| -> bool { matches!(s, Sequence::CharStar(_)) };
|
||||
let set1_star_count = set1.iter().filter(is_char_star).count();
|
||||
if set1_star_count == 0 {
|
||||
let set2_star_count = set2.iter().filter(is_char_star).count();
|
||||
|
@ -152,17 +152,15 @@ impl Sequence {
|
|||
Sequence::CharStar(c) => Some(c),
|
||||
_ => None,
|
||||
});
|
||||
let mut partition = set2
|
||||
.as_slice()
|
||||
.split(|s| matches!(s, Sequence::CharStar(_)));
|
||||
let set1_len = set1.iter().flat_map(Sequence::flatten).count();
|
||||
let mut partition = set2.as_slice().split(|s| matches!(s, Self::CharStar(_)));
|
||||
let set1_len = set1.iter().flat_map(Self::flatten).count();
|
||||
let set2_len = set2
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Sequence::CharStar(_) => None,
|
||||
r => Some(r),
|
||||
})
|
||||
.flat_map(Sequence::flatten)
|
||||
.flat_map(Self::flatten)
|
||||
.count();
|
||||
let star_compensate_len = set1_len.saturating_sub(set2_len);
|
||||
let (left, right) = (partition.next(), partition.next());
|
||||
|
@ -175,35 +173,35 @@ impl Sequence {
|
|||
if let Some(c) = char_star {
|
||||
std::iter::repeat(*c)
|
||||
.take(star_compensate_len)
|
||||
.chain(set2_b.iter().flat_map(Sequence::flatten))
|
||||
.chain(set2_b.iter().flat_map(Self::flatten))
|
||||
.collect()
|
||||
} else {
|
||||
set2_b.iter().flat_map(Sequence::flatten).collect()
|
||||
set2_b.iter().flat_map(Self::flatten).collect()
|
||||
}
|
||||
}
|
||||
(Some(set2_a), None) => match char_star {
|
||||
Some(c) => set2_a
|
||||
.iter()
|
||||
.flat_map(Sequence::flatten)
|
||||
.flat_map(Self::flatten)
|
||||
.chain(std::iter::repeat(*c).take(star_compensate_len))
|
||||
.collect(),
|
||||
None => set2_a.iter().flat_map(Sequence::flatten).collect(),
|
||||
None => set2_a.iter().flat_map(Self::flatten).collect(),
|
||||
},
|
||||
(Some(set2_a), Some(set2_b)) => match char_star {
|
||||
Some(c) => set2_a
|
||||
.iter()
|
||||
.flat_map(Sequence::flatten)
|
||||
.flat_map(Self::flatten)
|
||||
.chain(std::iter::repeat(*c).take(star_compensate_len))
|
||||
.chain(set2_b.iter().flat_map(Sequence::flatten))
|
||||
.chain(set2_b.iter().flat_map(Self::flatten))
|
||||
.collect(),
|
||||
None => set2_a
|
||||
.iter()
|
||||
.chain(set2_b.iter())
|
||||
.flat_map(Sequence::flatten)
|
||||
.flat_map(Self::flatten)
|
||||
.collect(),
|
||||
},
|
||||
};
|
||||
let mut set1_solved: Vec<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 {
|
||||
set1_solved.truncate(set2_solved.len());
|
||||
}
|
||||
|
@ -218,15 +216,15 @@ 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((
|
||||
Sequence::parse_char_range,
|
||||
Sequence::parse_char_star,
|
||||
Sequence::parse_char_repeat,
|
||||
Sequence::parse_class,
|
||||
Sequence::parse_char_equal,
|
||||
Self::parse_char_range,
|
||||
Self::parse_char_star,
|
||||
Self::parse_char_repeat,
|
||||
Self::parse_class,
|
||||
Self::parse_char_equal,
|
||||
// NOTE: This must be the last one
|
||||
map(Sequence::parse_backslash_or_char, |s| Ok(Sequence::Char(s))),
|
||||
map(Self::parse_backslash_or_char, |s| Ok(Self::Char(s))),
|
||||
)))(input)
|
||||
.map(|(_, r)| r)
|
||||
.unwrap()
|
||||
|
@ -251,64 +249,64 @@ impl Sequence {
|
|||
}
|
||||
|
||||
fn parse_backslash_or_char(input: &str) -> IResult<&str, char> {
|
||||
alt((Sequence::parse_backslash, anychar))(input)
|
||||
alt((Self::parse_backslash, anychar))(input)
|
||||
}
|
||||
|
||||
fn parse_char_range(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> {
|
||||
fn parse_char_range(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
|
||||
separated_pair(
|
||||
Sequence::parse_backslash_or_char,
|
||||
Self::parse_backslash_or_char,
|
||||
tag("-"),
|
||||
Sequence::parse_backslash_or_char,
|
||||
Self::parse_backslash_or_char,
|
||||
)(input)
|
||||
.map(|(l, (a, b))| {
|
||||
(l, {
|
||||
let (start, end) = (u32::from(a), u32::from(b));
|
||||
Ok(Sequence::CharRange(start, end))
|
||||
Ok(Self::CharRange(start, end))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_char_star(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> {
|
||||
delimited(tag("["), Sequence::parse_backslash_or_char, tag("*]"))(input)
|
||||
.map(|(l, a)| (l, Ok(Sequence::CharStar(a))))
|
||||
fn parse_char_star(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
|
||||
delimited(tag("["), Self::parse_backslash_or_char, tag("*]"))(input)
|
||||
.map(|(l, a)| (l, Ok(Self::CharStar(a))))
|
||||
}
|
||||
|
||||
fn parse_char_repeat(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> {
|
||||
fn parse_char_repeat(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
|
||||
delimited(
|
||||
tag("["),
|
||||
separated_pair(Sequence::parse_backslash_or_char, tag("*"), digit1),
|
||||
separated_pair(Self::parse_backslash_or_char, tag("*"), digit1),
|
||||
tag("]"),
|
||||
)(input)
|
||||
.map(|(l, (c, str))| {
|
||||
(
|
||||
l,
|
||||
match usize::from_str_radix(str, 8) {
|
||||
Ok(0) => Ok(Sequence::CharStar(c)),
|
||||
Ok(count) => Ok(Sequence::CharRepeat(c, count)),
|
||||
Ok(0) => Ok(Self::CharStar(c)),
|
||||
Ok(count) => Ok(Self::CharRepeat(c, count)),
|
||||
Err(_) => Err(BadSequence::InvalidRepeatCount(str.to_string())),
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_class(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> {
|
||||
fn parse_class(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
|
||||
delimited(
|
||||
tag("[:"),
|
||||
alt((
|
||||
map(
|
||||
alt((
|
||||
value(Sequence::Alnum, tag("alnum")),
|
||||
value(Sequence::Alpha, tag("alpha")),
|
||||
value(Sequence::Blank, tag("blank")),
|
||||
value(Sequence::Control, tag("cntrl")),
|
||||
value(Sequence::Digit, tag("digit")),
|
||||
value(Sequence::Graph, tag("graph")),
|
||||
value(Sequence::Lower, tag("lower")),
|
||||
value(Sequence::Print, tag("print")),
|
||||
value(Sequence::Punct, tag("punct")),
|
||||
value(Sequence::Space, tag("space")),
|
||||
value(Sequence::Upper, tag("upper")),
|
||||
value(Sequence::Xdigit, tag("xdigit")),
|
||||
value(Self::Alnum, tag("alnum")),
|
||||
value(Self::Alpha, tag("alpha")),
|
||||
value(Self::Blank, tag("blank")),
|
||||
value(Self::Control, tag("cntrl")),
|
||||
value(Self::Digit, tag("digit")),
|
||||
value(Self::Graph, tag("graph")),
|
||||
value(Self::Lower, tag("lower")),
|
||||
value(Self::Print, tag("print")),
|
||||
value(Self::Punct, tag("punct")),
|
||||
value(Self::Space, tag("space")),
|
||||
value(Self::Upper, tag("upper")),
|
||||
value(Self::Xdigit, tag("xdigit")),
|
||||
)),
|
||||
Ok,
|
||||
),
|
||||
|
@ -318,7 +316,7 @@ impl Sequence {
|
|||
)(input)
|
||||
}
|
||||
|
||||
fn parse_char_equal(input: &str) -> IResult<&str, Result<Sequence, BadSequence>> {
|
||||
fn parse_char_equal(input: &str) -> IResult<&str, Result<Self, BadSequence>> {
|
||||
delimited(
|
||||
tag("[="),
|
||||
alt((
|
||||
|
@ -326,7 +324,7 @@ impl Sequence {
|
|||
Err(BadSequence::MissingEquivalentClassChar),
|
||||
peek(tag("=]")),
|
||||
),
|
||||
map(Sequence::parse_backslash_or_char, |c| Ok(Sequence::Char(c))),
|
||||
map(Self::parse_backslash_or_char, |c| Ok(Self::Char(c))),
|
||||
)),
|
||||
tag("=]"),
|
||||
)(input)
|
||||
|
@ -344,8 +342,8 @@ pub struct DeleteOperation {
|
|||
}
|
||||
|
||||
impl DeleteOperation {
|
||||
pub fn new(set: Vec<char>, complement_flag: bool) -> DeleteOperation {
|
||||
DeleteOperation {
|
||||
pub fn new(set: Vec<char>, complement_flag: bool) -> Self {
|
||||
Self {
|
||||
set,
|
||||
complement_flag,
|
||||
}
|
||||
|
@ -372,8 +370,8 @@ pub struct TranslateOperationComplement {
|
|||
}
|
||||
|
||||
impl TranslateOperationComplement {
|
||||
fn new(set1: Vec<char>, set2: Vec<char>) -> TranslateOperationComplement {
|
||||
TranslateOperationComplement {
|
||||
fn new(set1: Vec<char>, set2: Vec<char>) -> Self {
|
||||
Self {
|
||||
iter: 0,
|
||||
set2_iter: 0,
|
||||
set1,
|
||||
|
@ -389,16 +387,16 @@ pub struct 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() {
|
||||
Ok(TranslateOperationStandard {
|
||||
Ok(Self {
|
||||
translation_map: set1
|
||||
.into_iter()
|
||||
.zip(set2.into_iter().chain(std::iter::repeat(fallback)))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
})
|
||||
} else if set1.is_empty() && set2.is_empty() {
|
||||
Ok(TranslateOperationStandard {
|
||||
Ok(Self {
|
||||
translation_map: HashMap::new(),
|
||||
})
|
||||
} else {
|
||||
|
@ -424,19 +422,13 @@ impl TranslateOperation {
|
|||
}
|
||||
|
||||
impl TranslateOperation {
|
||||
pub fn new(
|
||||
set1: Vec<char>,
|
||||
set2: Vec<char>,
|
||||
complement: bool,
|
||||
) -> Result<TranslateOperation, BadSequence> {
|
||||
pub fn new(set1: Vec<char>, set2: Vec<char>, complement: bool) -> Result<Self, BadSequence> {
|
||||
if complement {
|
||||
Ok(TranslateOperation::Complement(
|
||||
TranslateOperationComplement::new(set1, set2),
|
||||
))
|
||||
Ok(Self::Complement(TranslateOperationComplement::new(
|
||||
set1, set2,
|
||||
)))
|
||||
} else {
|
||||
Ok(TranslateOperation::Standard(
|
||||
TranslateOperationStandard::new(set1, set2)?,
|
||||
))
|
||||
Ok(Self::Standard(TranslateOperationStandard::new(set1, set2)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -444,13 +436,13 @@ impl TranslateOperation {
|
|||
impl SymbolTranslator for TranslateOperation {
|
||||
fn translate(&mut self, current: char) -> Option<char> {
|
||||
match self {
|
||||
TranslateOperation::Standard(TranslateOperationStandard { translation_map }) => Some(
|
||||
Self::Standard(TranslateOperationStandard { translation_map }) => Some(
|
||||
translation_map
|
||||
.iter()
|
||||
.find_map(|(l, r)| if l.eq(¤t) { Some(*r) } else { None })
|
||||
.unwrap_or(current),
|
||||
),
|
||||
TranslateOperation::Complement(TranslateOperationComplement {
|
||||
Self::Complement(TranslateOperationComplement {
|
||||
iter,
|
||||
set2_iter,
|
||||
set1,
|
||||
|
@ -467,8 +459,7 @@ impl SymbolTranslator for TranslateOperation {
|
|||
} else {
|
||||
while translation_map.get(¤t).is_none() {
|
||||
if let Some(value) = set2.get(*set2_iter) {
|
||||
let (next_iter, next_key) =
|
||||
TranslateOperation::next_complement_char(*iter, &*set1);
|
||||
let (next_iter, next_key) = Self::next_complement_char(*iter, &*set1);
|
||||
*iter = next_iter;
|
||||
*set2_iter = set2_iter.saturating_add(1);
|
||||
translation_map.insert(next_key, *value);
|
||||
|
@ -491,8 +482,8 @@ pub struct SqueezeOperation {
|
|||
}
|
||||
|
||||
impl SqueezeOperation {
|
||||
pub fn new(set1: Vec<char>, complement: bool) -> SqueezeOperation {
|
||||
SqueezeOperation {
|
||||
pub fn new(set1: Vec<char>, complement: bool) -> Self {
|
||||
Self {
|
||||
set1: set1.into_iter().collect(),
|
||||
complement,
|
||||
previous: None,
|
||||
|
|
|
@ -104,6 +104,7 @@ pub fn uu_app<'a>() -> App<'a> {
|
|||
|
||||
// We use String as a representation of node here
|
||||
// but using integer may improve performance.
|
||||
#[derive(Default)]
|
||||
struct Graph {
|
||||
in_edges: HashMap<String, HashSet<String>>,
|
||||
out_edges: HashMap<String, Vec<String>>,
|
||||
|
@ -111,12 +112,8 @@ struct Graph {
|
|||
}
|
||||
|
||||
impl Graph {
|
||||
fn new() -> Graph {
|
||||
Graph {
|
||||
in_edges: HashMap::new(),
|
||||
out_edges: HashMap::new(),
|
||||
result: vec![],
|
||||
}
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn has_node(&self, n: &str) -> bool {
|
||||
|
|
|
@ -67,7 +67,7 @@ struct Options {
|
|||
}
|
||||
|
||||
impl Options {
|
||||
fn new(matches: &clap::ArgMatches) -> Options {
|
||||
fn new(matches: &clap::ArgMatches) -> Self {
|
||||
let tabstops = match matches.value_of(options::TABS) {
|
||||
None => vec![DEFAULT_TABSTOP],
|
||||
Some(s) => tabstops_parse(s),
|
||||
|
@ -82,7 +82,7 @@ impl Options {
|
|||
None => vec!["-".to_owned()],
|
||||
};
|
||||
|
||||
Options {
|
||||
Self {
|
||||
files,
|
||||
tabstops,
|
||||
aflag,
|
||||
|
|
|
@ -39,8 +39,8 @@ struct Settings {
|
|||
}
|
||||
|
||||
impl Settings {
|
||||
fn new(matches: &ArgMatches) -> Settings {
|
||||
let settings = Settings {
|
||||
fn new(matches: &ArgMatches) -> Self {
|
||||
let settings = Self {
|
||||
show_bytes: matches.is_present(options::BYTES),
|
||||
show_chars: matches.is_present(options::CHAR),
|
||||
show_lines: matches.is_present(options::LINES),
|
||||
|
@ -57,7 +57,7 @@ impl Settings {
|
|||
return settings;
|
||||
}
|
||||
|
||||
Settings {
|
||||
Self {
|
||||
show_bytes: true,
|
||||
show_chars: false,
|
||||
show_lines: true,
|
||||
|
|
|
@ -55,7 +55,7 @@ type Result<T> = std::result::Result<T, Error>;
|
|||
|
||||
impl From<nix::Error> for Error {
|
||||
fn from(error: nix::Error) -> Self {
|
||||
Error::Io(io::Error::from_raw_os_error(error as i32))
|
||||
Self::Io(io::Error::from_raw_os_error(error as i32))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -107,7 +107,7 @@ pub struct Data<R: Read> {
|
|||
|
||||
impl<R: Read> Data<R> {
|
||||
pub fn new(input: R, format: Format) -> Self {
|
||||
Data {
|
||||
Self {
|
||||
line_wrap: 76,
|
||||
ignore_garbage: false,
|
||||
input,
|
||||
|
|
|
@ -175,7 +175,7 @@ impl Passwd {
|
|||
/// SAFETY: All the pointed-to strings must be valid and not change while
|
||||
/// the function runs. That means PW_LOCK must be held.
|
||||
unsafe fn from_raw(raw: passwd) -> Self {
|
||||
Passwd {
|
||||
Self {
|
||||
name: cstr2string(raw.pw_name),
|
||||
uid: raw.pw_uid,
|
||||
gid: raw.pw_gid,
|
||||
|
@ -243,7 +243,7 @@ impl Group {
|
|||
/// SAFETY: gr_name must be valid and not change while
|
||||
/// the function runs. That means PW_LOCK must be held.
|
||||
unsafe fn from_raw(raw: group) -> Self {
|
||||
Group {
|
||||
Self {
|
||||
name: cstr2string(raw.gr_name),
|
||||
gid: raw.gr_gid,
|
||||
}
|
||||
|
|
|
@ -197,7 +197,7 @@ impl MountInfo {
|
|||
}
|
||||
|
||||
#[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 {
|
||||
// spell-checker:ignore (word) noatime
|
||||
// Format: 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
|
||||
|
@ -207,7 +207,7 @@ impl MountInfo {
|
|||
let after_fields = raw[FIELDS_OFFSET..].iter().position(|c| *c == "-").unwrap()
|
||||
+ FIELDS_OFFSET
|
||||
+ 1;
|
||||
let mut m = MountInfo {
|
||||
let mut m = Self {
|
||||
dev_id: "".to_string(),
|
||||
dev_name: raw[after_fields + 1].to_string(),
|
||||
fs_type: raw[after_fields].to_string(),
|
||||
|
@ -221,7 +221,7 @@ impl MountInfo {
|
|||
Some(m)
|
||||
}
|
||||
LINUX_MTAB => {
|
||||
let mut m = MountInfo {
|
||||
let mut m = Self {
|
||||
dev_id: "".to_string(),
|
||||
dev_name: raw[0].to_string(),
|
||||
fs_type: raw[2].to_string(),
|
||||
|
@ -496,9 +496,9 @@ pub struct FsUsage {
|
|||
|
||||
impl FsUsage {
|
||||
#[cfg(unix)]
|
||||
pub fn new(statvfs: StatFs) -> FsUsage {
|
||||
pub fn new(statvfs: StatFs) -> Self {
|
||||
{
|
||||
FsUsage {
|
||||
Self {
|
||||
blocksize: statvfs.f_bsize as u64, // or `statvfs.f_frsize` ?
|
||||
blocks: statvfs.f_blocks as u64,
|
||||
bfree: statvfs.f_bfree as u64,
|
||||
|
@ -510,7 +510,7 @@ impl FsUsage {
|
|||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
pub fn new(path: &Path) -> FsUsage {
|
||||
pub fn new(path: &Path) -> Self {
|
||||
let mut root_path = [0u16; MAX_PATH];
|
||||
let success = unsafe {
|
||||
GetVolumePathNamesForVolumeNameW(
|
||||
|
|
|
@ -26,8 +26,8 @@ fn warn_excess_args(first_arg: &str) {
|
|||
}
|
||||
|
||||
impl Memo {
|
||||
pub fn new(pf_string: &str, pf_args_it: &mut Peekable<Iter<String>>) -> Memo {
|
||||
let mut pm = Memo { tokens: Vec::new() };
|
||||
pub fn new(pf_string: &str, pf_args_it: &mut Peekable<Iter<String>>) -> Self {
|
||||
let mut pm = Self { tokens: Vec::new() };
|
||||
let mut tmp_token: Option<Box<dyn Token>>;
|
||||
let mut it = put_back_n(pf_string.chars());
|
||||
let mut has_sub = false;
|
||||
|
@ -73,7 +73,7 @@ impl Memo {
|
|||
}
|
||||
pub fn run_all(pf_string: &str, pf_args: &[String]) {
|
||||
let mut arg_it = pf_args.iter().peekable();
|
||||
let pm = Memo::new(pf_string, &mut arg_it);
|
||||
let pm = Self::new(pf_string, &mut arg_it);
|
||||
loop {
|
||||
if arg_it.peek().is_none() {
|
||||
break;
|
||||
|
|
|
@ -56,12 +56,12 @@ impl ExitStatus {
|
|||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
if let Some(signal) = status.signal() {
|
||||
return ExitStatus::Signal(signal);
|
||||
return Self::Signal(signal);
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: this should never fail as we check if the program exited through a signal above
|
||||
ExitStatus::Code(status.code().unwrap())
|
||||
Self::Code(status.code().unwrap())
|
||||
}
|
||||
|
||||
pub fn success(&self) -> bool {
|
||||
|
|
|
@ -42,15 +42,15 @@ pub struct RingBuffer<T> {
|
|||
}
|
||||
|
||||
impl<T> RingBuffer<T> {
|
||||
pub fn new(size: usize) -> RingBuffer<T> {
|
||||
RingBuffer {
|
||||
pub fn new(size: usize) -> Self {
|
||||
Self {
|
||||
data: VecDeque::new(),
|
||||
size,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_iter(iter: impl Iterator<Item = T>, size: usize) -> RingBuffer<T> {
|
||||
let mut ring_buffer = RingBuffer::new(size);
|
||||
pub fn from_iter(iter: impl Iterator<Item = T>, size: usize) -> Self {
|
||||
let mut ring_buffer = Self::new(size);
|
||||
for value in iter {
|
||||
ring_buffer.push_back(value);
|
||||
}
|
||||
|
|
|
@ -8,13 +8,14 @@ use super::base_conv;
|
|||
use super::base_conv::RadixDef;
|
||||
use super::float_common::{primitive_to_str_common, FloatAnalysis};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CninetyNineHexFloatf {
|
||||
#[allow(dead_code)]
|
||||
as_num: f64,
|
||||
}
|
||||
impl CninetyNineHexFloatf {
|
||||
pub fn new() -> CninetyNineHexFloatf {
|
||||
CninetyNineHexFloatf { as_num: 0.0 }
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -25,8 +25,8 @@ fn get_len_fmt_primitive(fmt: &FormatPrimitive) -> usize {
|
|||
pub struct Decf;
|
||||
|
||||
impl Decf {
|
||||
pub fn new() -> Decf {
|
||||
Decf
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl Formatter for Decf {
|
||||
|
|
|
@ -46,12 +46,12 @@ impl FloatAnalysis {
|
|||
max_sd_opt: Option<usize>,
|
||||
max_after_dec_opt: Option<usize>,
|
||||
hex_output: bool,
|
||||
) -> FloatAnalysis {
|
||||
) -> Self {
|
||||
// this fn assumes
|
||||
// the input string
|
||||
// has no leading spaces or 0s
|
||||
let str_it = get_it_at(initial_prefix.offset, str_in);
|
||||
let mut ret = FloatAnalysis {
|
||||
let mut ret = Self {
|
||||
len_important: 0,
|
||||
decimal_pos: None,
|
||||
follow: None,
|
||||
|
|
|
@ -6,10 +6,11 @@ use super::super::format_field::FormatField;
|
|||
use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix};
|
||||
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Floatf;
|
||||
impl Floatf {
|
||||
pub fn new() -> Floatf {
|
||||
Floatf
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
impl Formatter for Floatf {
|
||||
|
|
|
@ -11,6 +11,7 @@ use super::super::formatter::{
|
|||
use std::i64;
|
||||
use std::u64;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Intf {
|
||||
_a: u32,
|
||||
}
|
||||
|
@ -24,8 +25,8 @@ struct IntAnalysis {
|
|||
}
|
||||
|
||||
impl Intf {
|
||||
pub fn new() -> Intf {
|
||||
Intf { _a: 0 }
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
// take a ref to argument string, and basic information
|
||||
// about prefix (offset, radix, sign), and analyze string
|
||||
|
@ -166,7 +167,7 @@ impl Intf {
|
|||
fmt_prim.pre_decimal = Some(format!("{}", i));
|
||||
fmt_prim
|
||||
}
|
||||
Err(_) => Intf::get_max(field_char, sign),
|
||||
Err(_) => Self::get_max(field_char, sign),
|
||||
},
|
||||
_ => match u64::from_str_radix(segment, radix_in as u32) {
|
||||
Ok(u) => {
|
||||
|
@ -180,7 +181,7 @@ impl Intf {
|
|||
});
|
||||
fmt_prim
|
||||
}
|
||||
Err(_) => Intf::get_max(field_char, sign),
|
||||
Err(_) => Self::get_max(field_char, sign),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -196,7 +197,7 @@ impl Formatter for Intf {
|
|||
|
||||
// get information about the string. see Intf::Analyze
|
||||
// def above.
|
||||
let convert_hints = Intf::analyze(
|
||||
let convert_hints = Self::analyze(
|
||||
str_in,
|
||||
*field.field_char == 'i' || *field.field_char == 'd',
|
||||
initial_prefix,
|
||||
|
@ -226,7 +227,7 @@ impl Formatter for Intf {
|
|||
if convert_hints.check_past_max || decrease_from_max || radix_mismatch {
|
||||
// radix of in and out is the same.
|
||||
let segment = String::from(&str_in[begin..end]);
|
||||
Intf::conv_from_segment(
|
||||
Self::conv_from_segment(
|
||||
&segment,
|
||||
initial_prefix.radix_in.clone(),
|
||||
*field.field_char,
|
||||
|
@ -246,7 +247,7 @@ impl Formatter for Intf {
|
|||
fmt_prim
|
||||
}
|
||||
} else {
|
||||
Intf::get_max(*field.field_char, initial_prefix.sign)
|
||||
Self::get_max(*field.field_char, initial_prefix.sign)
|
||||
})
|
||||
}
|
||||
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
|
||||
|
|
|
@ -5,11 +5,12 @@ use super::super::format_field::FormatField;
|
|||
use super::super::formatter::{FormatPrimitive, Formatter, InitialPrefix};
|
||||
use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Scif;
|
||||
|
||||
impl Scif {
|
||||
pub fn new() -> Scif {
|
||||
Scif
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
impl Formatter for Scif {
|
||||
|
|
|
@ -67,7 +67,7 @@ impl Sub {
|
|||
second_field: CanAsterisk<Option<u32>>,
|
||||
field_char: char,
|
||||
orig: String,
|
||||
) -> Sub {
|
||||
) -> Self {
|
||||
// for more dry printing, field characters are grouped
|
||||
// in initialization of token.
|
||||
let field_type = match field_char {
|
||||
|
@ -84,7 +84,7 @@ impl Sub {
|
|||
exit(EXIT_ERR);
|
||||
}
|
||||
};
|
||||
Sub {
|
||||
Self {
|
||||
min_width,
|
||||
second_field,
|
||||
field_char,
|
||||
|
@ -94,6 +94,7 @@ impl Sub {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SubParser {
|
||||
min_width_tmp: Option<String>,
|
||||
min_width_is_asterisk: bool,
|
||||
|
@ -106,32 +107,23 @@ struct SubParser {
|
|||
}
|
||||
|
||||
impl SubParser {
|
||||
fn new() -> SubParser {
|
||||
SubParser {
|
||||
min_width_tmp: None,
|
||||
min_width_is_asterisk: false,
|
||||
past_decimal: false,
|
||||
second_field_tmp: None,
|
||||
second_field_is_asterisk: false,
|
||||
specifiers_found: false,
|
||||
field_char: None,
|
||||
text_so_far: String::new(),
|
||||
}
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
fn from_it(
|
||||
it: &mut PutBackN<Chars>,
|
||||
args: &mut Peekable<Iter<String>>,
|
||||
) -> Option<Box<dyn token::Token>> {
|
||||
let mut parser = SubParser::new();
|
||||
let mut parser = Self::new();
|
||||
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);
|
||||
Some(t)
|
||||
} else {
|
||||
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.
|
||||
// return new Sub struct as token
|
||||
let t: Box<dyn token::Token> = Box::new(Sub::new(
|
||||
|
@ -151,7 +143,7 @@ impl SubParser {
|
|||
t
|
||||
}
|
||||
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;
|
||||
}
|
||||
// this fn in particular is much longer than it needs to be
|
||||
|
|
|
@ -35,10 +35,11 @@ fn flush_bytes(bslice: &[u8]) {
|
|||
let _ = stdout().flush();
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct UnescapedText(Vec<u8>);
|
||||
impl UnescapedText {
|
||||
fn new() -> UnescapedText {
|
||||
UnescapedText(Vec::new())
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
// take an iterator to the format string
|
||||
// consume between min and max chars
|
||||
|
@ -133,7 +134,7 @@ impl UnescapedText {
|
|||
_ => {}
|
||||
}
|
||||
if !ignore {
|
||||
let val = (UnescapedText::base_to_u32(min_len, max_len, base, it) % 256) as u8;
|
||||
let val = (Self::base_to_u32(min_len, max_len, base, it) % 256) as u8;
|
||||
byte_vec.push(val);
|
||||
let bvec = [val];
|
||||
flush_bytes(&bvec);
|
||||
|
@ -170,8 +171,8 @@ impl UnescapedText {
|
|||
'u' => 4,
|
||||
/* 'U' | */ _ => 8,
|
||||
};
|
||||
let val = UnescapedText::base_to_u32(len, len, 16, it);
|
||||
UnescapedText::validate_iec(val, false);
|
||||
let val = Self::base_to_u32(len, len, 16, it);
|
||||
Self::validate_iec(val, false);
|
||||
if let Some(c) = from_u32(val) {
|
||||
c
|
||||
} else {
|
||||
|
@ -199,7 +200,7 @@ impl UnescapedText {
|
|||
subs_mode: bool,
|
||||
) -> Option<Box<dyn token::Token>> {
|
||||
let mut addchar = false;
|
||||
let mut new_text = UnescapedText::new();
|
||||
let mut new_text = Self::new();
|
||||
let mut tmp_str = String::new();
|
||||
{
|
||||
let new_vec: &mut Vec<u8> = &mut (new_text.0);
|
||||
|
@ -227,7 +228,7 @@ impl UnescapedText {
|
|||
new_vec.extend(tmp_str.bytes());
|
||||
tmp_str = String::new();
|
||||
}
|
||||
UnescapedText::handle_escaped(new_vec, it, subs_mode);
|
||||
Self::handle_escaped(new_vec, it, subs_mode);
|
||||
}
|
||||
x if x == '%' && !subs_mode => {
|
||||
if let Some(follow) = it.next() {
|
||||
|
@ -266,7 +267,7 @@ impl token::Tokenizer for UnescapedText {
|
|||
it: &mut PutBackN<Chars>,
|
||||
_: &mut Peekable<Iter<String>>,
|
||||
) -> Option<Box<dyn token::Token>> {
|
||||
UnescapedText::from_it_core(it, false)
|
||||
Self::from_it_core(it, false)
|
||||
}
|
||||
}
|
||||
impl token::Token for UnescapedText {
|
||||
|
|
|
@ -322,7 +322,7 @@ impl UtmpxIter {
|
|||
fn new() -> Self {
|
||||
// PoisonErrors can safely be ignored
|
||||
let guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
|
||||
UtmpxIter {
|
||||
Self {
|
||||
guard,
|
||||
phantom: PhantomData,
|
||||
}
|
||||
|
|
|
@ -265,7 +265,7 @@ impl<T> From<T> for Box<dyn UError>
|
|||
where
|
||||
T: UError + 'static,
|
||||
{
|
||||
fn from(t: T) -> Box<dyn UError> {
|
||||
fn from(t: T) -> Self {
|
||||
Box::new(t)
|
||||
}
|
||||
}
|
||||
|
@ -490,8 +490,8 @@ impl FromIo<Box<UIoError>> for std::io::ErrorKind {
|
|||
}
|
||||
|
||||
impl From<std::io::Error> for UIoError {
|
||||
fn from(f: std::io::Error) -> UIoError {
|
||||
UIoError {
|
||||
fn from(f: std::io::Error) -> Self {
|
||||
Self {
|
||||
context: None,
|
||||
inner: f,
|
||||
}
|
||||
|
@ -499,9 +499,9 @@ impl From<std::io::Error> for UIoError {
|
|||
}
|
||||
|
||||
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();
|
||||
Box::new(u_error) as Box<dyn UError>
|
||||
Box::new(u_error) as Self
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -20,7 +20,7 @@ pub struct Range {
|
|||
impl FromStr for Range {
|
||||
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;
|
||||
|
||||
let mut parts = s.splitn(2, '-');
|
||||
|
@ -33,7 +33,7 @@ impl FromStr for Range {
|
|||
(Some(nm), None) => {
|
||||
if let Ok(nm) = nm.parse::<usize>() {
|
||||
if nm > 0 {
|
||||
Ok(Range { low: nm, high: nm })
|
||||
Ok(Self { low: nm, high: nm })
|
||||
} else {
|
||||
Err(field)
|
||||
}
|
||||
|
@ -44,7 +44,7 @@ impl FromStr for Range {
|
|||
(Some(n), Some(m)) if m.is_empty() => {
|
||||
if let Ok(low) = n.parse::<usize>() {
|
||||
if low > 0 {
|
||||
Ok(Range { low, high: MAX - 1 })
|
||||
Ok(Self { low, high: MAX - 1 })
|
||||
} else {
|
||||
Err(field)
|
||||
}
|
||||
|
@ -55,7 +55,7 @@ impl FromStr for Range {
|
|||
(Some(n), Some(m)) if n.is_empty() => {
|
||||
if let Ok(high) = m.parse::<usize>() {
|
||||
if high > 0 {
|
||||
Ok(Range { low: 1, high })
|
||||
Ok(Self { low: 1, high })
|
||||
} else {
|
||||
Err(field)
|
||||
}
|
||||
|
@ -66,7 +66,7 @@ impl FromStr for Range {
|
|||
(Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) {
|
||||
(Ok(low), Ok(high)) => {
|
||||
if low > 0 && low <= high {
|
||||
Ok(Range { low, high })
|
||||
Ok(Self { low, high })
|
||||
} else if low == 0 {
|
||||
Err(field)
|
||||
} else {
|
||||
|
@ -81,10 +81,10 @@ impl FromStr for Range {
|
|||
}
|
||||
|
||||
impl Range {
|
||||
pub fn from_list(list: &str) -> Result<Vec<Range>, String> {
|
||||
pub fn from_list(list: &str) -> Result<Vec<Self>, String> {
|
||||
use std::cmp::max;
|
||||
|
||||
let mut ranges: Vec<Range> = vec![];
|
||||
let mut ranges: Vec<Self> = vec![];
|
||||
|
||||
for item in list.split(',') {
|
||||
let range_item = FromStr::from_str(item)
|
||||
|
|
|
@ -113,7 +113,7 @@ impl fmt::Display for ParseSizeError {
|
|||
// but there's a lot of downstream code that constructs these errors manually
|
||||
// that would be affected
|
||||
impl ParseSizeError {
|
||||
fn parse_failure(s: &str) -> ParseSizeError {
|
||||
fn parse_failure(s: &str) -> Self {
|
||||
// stderr on linux (GNU coreutils 8.32) (LC_ALL=C)
|
||||
// has to be handled in the respective uutils because strings differ, e.g.:
|
||||
//
|
||||
|
@ -145,10 +145,10 @@ impl ParseSizeError {
|
|||
// --width
|
||||
// --strings
|
||||
// etc.
|
||||
ParseSizeError::ParseFailure(format!("{}", s.quote()))
|
||||
Self::ParseFailure(format!("{}", s.quote()))
|
||||
}
|
||||
|
||||
fn size_too_big(s: &str) -> ParseSizeError {
|
||||
fn size_too_big(s: &str) -> Self {
|
||||
// stderr on linux (GNU coreutils 8.32) (LC_ALL=C)
|
||||
// has to be handled in the respective uutils because strings differ, e.g.:
|
||||
//
|
||||
|
@ -165,7 +165,7 @@ impl ParseSizeError {
|
|||
// stderr on macos (brew - GNU coreutils 8.32) also differs for the same version, e.g.:
|
||||
// ghead: invalid number of bytes: '1Y': Value too large to be stored in data type
|
||||
// gtail: invalid number of bytes: '1Y': Value too large to be stored in data type
|
||||
ParseSizeError::SizeTooBig(format!(
|
||||
Self::SizeTooBig(format!(
|
||||
"{}: Value too large for defined data type",
|
||||
s.quote()
|
||||
))
|
||||
|
|
|
@ -13,8 +13,8 @@ impl Target {
|
|||
// Creates a target that will naturally die after some time if not killed
|
||||
// fast enough.
|
||||
// This timeout avoids hanging failing tests.
|
||||
fn new() -> Target {
|
||||
Target {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
child: Command::new("sleep")
|
||||
.arg("30")
|
||||
.spawn()
|
||||
|
|
|
@ -32,8 +32,8 @@ struct Glob {
|
|||
}
|
||||
|
||||
impl Glob {
|
||||
fn new(at: &AtPath, directory: &str, regex: &str) -> Glob {
|
||||
Glob {
|
||||
fn new(at: &AtPath, directory: &str, regex: &str) -> Self {
|
||||
Self {
|
||||
directory: AtPath::new(Path::new(&at.plus_as_string(directory))),
|
||||
regex: Regex::new(regex).unwrap(),
|
||||
}
|
||||
|
@ -83,8 +83,8 @@ impl RandomFile {
|
|||
const LINESIZE: usize = 32;
|
||||
|
||||
/// `create()` file handle located at `at` / `name`
|
||||
fn new(at: &AtPath, name: &str) -> RandomFile {
|
||||
RandomFile {
|
||||
fn new(at: &AtPath, name: &str) -> Self {
|
||||
Self {
|
||||
inner: File::create(&at.plus(name)).unwrap(),
|
||||
}
|
||||
}
|
||||
|
@ -113,7 +113,7 @@ impl RandomFile {
|
|||
fn add_lines(&mut self, lines: usize) {
|
||||
let mut n = lines;
|
||||
while n > 0 {
|
||||
writeln!(self.inner, "{}", random_chars(RandomFile::LINESIZE)).unwrap();
|
||||
writeln!(self.inner, "{}", random_chars(Self::LINESIZE)).unwrap();
|
||||
n -= 1;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -88,8 +88,8 @@ impl CmdResult {
|
|||
success: bool,
|
||||
stdout: &[u8],
|
||||
stderr: &[u8],
|
||||
) -> CmdResult {
|
||||
CmdResult {
|
||||
) -> Self {
|
||||
Self {
|
||||
bin_path,
|
||||
util_name,
|
||||
tmpd,
|
||||
|
@ -150,7 +150,7 @@ impl CmdResult {
|
|||
self.code.expect("Program must be run first")
|
||||
}
|
||||
|
||||
pub fn code_is(&self, expected_code: i32) -> &CmdResult {
|
||||
pub fn code_is(&self, expected_code: i32) -> &Self {
|
||||
assert_eq!(self.code(), expected_code);
|
||||
self
|
||||
}
|
||||
|
@ -170,7 +170,7 @@ impl CmdResult {
|
|||
}
|
||||
|
||||
/// asserts that the command resulted in a success (zero) status code
|
||||
pub fn success(&self) -> &CmdResult {
|
||||
pub fn success(&self) -> &Self {
|
||||
assert!(
|
||||
self.success,
|
||||
"Command was expected to succeed.\nstdout = {}\n stderr = {}",
|
||||
|
@ -181,7 +181,7 @@ impl CmdResult {
|
|||
}
|
||||
|
||||
/// asserts that the command resulted in a failure (non-zero) status code
|
||||
pub fn failure(&self) -> &CmdResult {
|
||||
pub fn failure(&self) -> &Self {
|
||||
assert!(
|
||||
!self.success,
|
||||
"Command was expected to fail.\nstdout = {}\n stderr = {}",
|
||||
|
@ -192,7 +192,7 @@ impl CmdResult {
|
|||
}
|
||||
|
||||
/// asserts that the command's exit code is the same as the given one
|
||||
pub fn status_code(&self, code: i32) -> &CmdResult {
|
||||
pub fn status_code(&self, code: i32) -> &Self {
|
||||
assert_eq!(self.code, Some(code));
|
||||
self
|
||||
}
|
||||
|
@ -202,7 +202,7 @@ impl CmdResult {
|
|||
/// but you might find yourself using this function if
|
||||
/// 1. you can not know exactly what stdout will be or
|
||||
/// 2. you know that stdout will also be empty
|
||||
pub fn no_stderr(&self) -> &CmdResult {
|
||||
pub fn no_stderr(&self) -> &Self {
|
||||
assert!(
|
||||
self.stderr.is_empty(),
|
||||
"Expected stderr to be empty, but it's:\n{}",
|
||||
|
@ -217,7 +217,7 @@ impl CmdResult {
|
|||
/// but you might find yourself using this function if
|
||||
/// 1. you can not know exactly what stderr will be or
|
||||
/// 2. you know that stderr will also be empty
|
||||
pub fn no_stdout(&self) -> &CmdResult {
|
||||
pub fn no_stdout(&self) -> &Self {
|
||||
assert!(
|
||||
self.stdout.is_empty(),
|
||||
"Expected stdout to be empty, but it's:\n{}",
|
||||
|
@ -229,13 +229,13 @@ impl CmdResult {
|
|||
/// asserts that the command resulted in stdout stream output that equals the
|
||||
/// passed in value, trailing whitespace are kept to force strict comparison (#1235)
|
||||
/// stdout_only is a better choice unless stderr may or will be non-empty
|
||||
pub fn stdout_is<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()));
|
||||
self
|
||||
}
|
||||
|
||||
/// 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()) {
|
||||
panic!(
|
||||
"stdout was {}\nExpected any of {:#?}",
|
||||
|
@ -247,7 +247,7 @@ impl CmdResult {
|
|||
}
|
||||
|
||||
/// Like `stdout_is` but newlines are normalized to `\n`.
|
||||
pub fn normalized_newlines_stdout_is<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");
|
||||
assert_eq!(self.stdout_str().replace("\r\n", "\n"), msg);
|
||||
self
|
||||
|
@ -255,13 +255,13 @@ impl CmdResult {
|
|||
|
||||
/// asserts that the command resulted in stdout stream output,
|
||||
/// whose bytes equal those of the passed in slice
|
||||
pub fn stdout_is_bytes<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());
|
||||
self
|
||||
}
|
||||
|
||||
/// 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);
|
||||
self.stdout_is(String::from_utf8(contents).unwrap())
|
||||
}
|
||||
|
@ -271,7 +271,7 @@ impl CmdResult {
|
|||
&self,
|
||||
file_rel_path: T,
|
||||
template_vars: &[(&str, &str)],
|
||||
) -> &CmdResult {
|
||||
) -> &Self {
|
||||
let mut contents =
|
||||
String::from_utf8(read_scenario_fixture(&self.tmpd, file_rel_path)).unwrap();
|
||||
for kv in template_vars {
|
||||
|
@ -300,7 +300,7 @@ impl CmdResult {
|
|||
/// asserts that the command resulted in stderr stream output that equals the
|
||||
/// passed in value, when both are trimmed of trailing whitespace
|
||||
/// stderr_only is a better choice unless stdout may or will be non-empty
|
||||
pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &CmdResult {
|
||||
pub fn stderr_is<T: AsRef<str>>(&self, msg: T) -> &Self {
|
||||
assert_eq!(
|
||||
self.stderr_str().trim_end(),
|
||||
String::from(msg.as_ref()).trim_end()
|
||||
|
@ -310,13 +310,13 @@ impl CmdResult {
|
|||
|
||||
/// asserts that the command resulted in stderr stream output,
|
||||
/// whose bytes equal those of the passed in slice
|
||||
pub fn stderr_is_bytes<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());
|
||||
self
|
||||
}
|
||||
|
||||
/// 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);
|
||||
self.stderr_is(String::from_utf8(contents).unwrap())
|
||||
}
|
||||
|
@ -325,7 +325,7 @@ impl CmdResult {
|
|||
/// 1. the command resulted in stdout stream output that equals the
|
||||
/// passed in value
|
||||
/// 2. the command resulted in empty (zero-length) stderr stream output
|
||||
pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &CmdResult {
|
||||
pub fn stdout_only<T: AsRef<str>>(&self, msg: T) -> &Self {
|
||||
self.no_stderr().stdout_is(msg)
|
||||
}
|
||||
|
||||
|
@ -333,12 +333,12 @@ impl CmdResult {
|
|||
/// 1. the command resulted in a stdout stream whose bytes
|
||||
/// equal those of the passed in value
|
||||
/// 2. the command resulted in an empty stderr stream
|
||||
pub fn stdout_only_bytes<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)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
self.stdout_only_bytes(contents)
|
||||
}
|
||||
|
@ -347,7 +347,7 @@ impl CmdResult {
|
|||
/// 1. the command resulted in stderr stream output that equals the
|
||||
/// passed in value, when both are trimmed of trailing whitespace
|
||||
/// 2. the command resulted in empty (zero-length) stdout stream output
|
||||
pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &CmdResult {
|
||||
pub fn stderr_only<T: AsRef<str>>(&self, msg: T) -> &Self {
|
||||
self.no_stdout().stderr_is(msg)
|
||||
}
|
||||
|
||||
|
@ -355,11 +355,11 @@ impl CmdResult {
|
|||
/// 1. the command resulted in a stderr stream whose bytes equal the ones
|
||||
/// of the passed value
|
||||
/// 2. the command resulted in an empty stdout stream
|
||||
pub fn stderr_only_bytes<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)
|
||||
}
|
||||
|
||||
pub fn fails_silently(&self) -> &CmdResult {
|
||||
pub fn fails_silently(&self) -> &Self {
|
||||
assert!(!self.success);
|
||||
assert!(self.stderr.is_empty());
|
||||
self
|
||||
|
@ -373,7 +373,7 @@ impl CmdResult {
|
|||
/// `msg` should be the same as the one provided to UUsageError::new or show_error!
|
||||
///
|
||||
/// 2. the command resulted in empty (zero-length) stdout stream output
|
||||
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &CmdResult {
|
||||
pub fn usage_error<T: AsRef<str>>(&self, msg: T) -> &Self {
|
||||
self.stderr_only(format!(
|
||||
"{0}: {2}\nTry '{1} {0} --help' for more information.",
|
||||
self.util_name.as_ref().unwrap(), // This shouldn't be called using a normal command
|
||||
|
@ -382,7 +382,7 @@ impl CmdResult {
|
|||
))
|
||||
}
|
||||
|
||||
pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &CmdResult {
|
||||
pub fn stdout_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
|
||||
assert!(
|
||||
self.stdout_str().contains(cmp.as_ref()),
|
||||
"'{}' does not contain '{}'",
|
||||
|
@ -392,7 +392,7 @@ impl CmdResult {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &CmdResult {
|
||||
pub fn stderr_contains<T: AsRef<str>>(&self, cmp: T) -> &Self {
|
||||
assert!(
|
||||
self.stderr_str().contains(cmp.as_ref()),
|
||||
"'{}' does not contain '{}'",
|
||||
|
@ -402,7 +402,7 @@ impl CmdResult {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &CmdResult {
|
||||
pub fn stdout_does_not_contain<T: AsRef<str>>(&self, cmp: T) -> &Self {
|
||||
assert!(
|
||||
!self.stdout_str().contains(cmp.as_ref()),
|
||||
"'{}' contains '{}' but should not",
|
||||
|
@ -412,19 +412,19 @@ impl CmdResult {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn stderr_does_not_contain<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()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn stdout_matches(&self, regex: ®ex::Regex) -> &CmdResult {
|
||||
pub fn stdout_matches(&self, regex: ®ex::Regex) -> &Self {
|
||||
if !regex.is_match(self.stdout_str().trim()) {
|
||||
panic!("Stdout does not match regex:\n{}", self.stdout_str());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &CmdResult {
|
||||
pub fn stdout_does_not_match(&self, regex: ®ex::Regex) -> &Self {
|
||||
if regex.is_match(self.stdout_str().trim()) {
|
||||
panic!("Stdout matches regex:\n{}", self.stdout_str());
|
||||
}
|
||||
|
@ -469,8 +469,8 @@ pub struct AtPath {
|
|||
}
|
||||
|
||||
impl AtPath {
|
||||
pub fn new(subdir: &Path) -> AtPath {
|
||||
AtPath {
|
||||
pub fn new(subdir: &Path) -> Self {
|
||||
Self {
|
||||
subdir: PathBuf::from(subdir),
|
||||
}
|
||||
}
|
||||
|
@ -776,9 +776,9 @@ pub struct TestScenario {
|
|||
}
|
||||
|
||||
impl TestScenario {
|
||||
pub fn new(util_name: &str) -> TestScenario {
|
||||
pub fn new(util_name: &str) -> Self {
|
||||
let tmpd = Rc::new(TempDir::new().unwrap());
|
||||
let ts = TestScenario {
|
||||
let ts = Self {
|
||||
bin_path: {
|
||||
// Instead of hard coding the path relative to the current
|
||||
// directory, use Cargo's OUT_DIR to find path to executable.
|
||||
|
@ -875,11 +875,11 @@ impl UCommand {
|
|||
util_name: &Option<S>,
|
||||
curdir: U,
|
||||
env_clear: bool,
|
||||
) -> UCommand {
|
||||
) -> Self {
|
||||
let bin_path = bin_path.as_ref();
|
||||
let util_name = util_name.as_ref().map(|un| un.as_ref());
|
||||
|
||||
let mut ucmd = UCommand {
|
||||
let mut ucmd = Self {
|
||||
tmpd: None,
|
||||
has_run: false,
|
||||
raw: {
|
||||
|
@ -927,31 +927,31 @@ impl UCommand {
|
|||
util_name: &Option<S>,
|
||||
tmpd: Rc<TempDir>,
|
||||
env_clear: bool,
|
||||
) -> UCommand {
|
||||
) -> Self {
|
||||
let tmpd_path_buf = String::from(&(*tmpd.as_ref().path().to_str().unwrap()));
|
||||
let mut ucmd: UCommand = UCommand::new(bin_path, util_name, tmpd_path_buf, env_clear);
|
||||
let mut ucmd: Self = Self::new(bin_path, util_name, tmpd_path_buf, env_clear);
|
||||
ucmd.tmpd = Some(tmpd);
|
||||
ucmd
|
||||
}
|
||||
|
||||
pub fn set_stdin<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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/// Add a parameter to the invocation. Path arguments are treated relative
|
||||
/// 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);
|
||||
self.comm_string.push(' ');
|
||||
self.comm_string
|
||||
|
@ -962,7 +962,7 @@ impl UCommand {
|
|||
|
||||
/// Add multiple parameters to the invocation. Path arguments are treated relative
|
||||
/// to the test environment directory.
|
||||
pub fn args<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);
|
||||
let strings = args
|
||||
.iter()
|
||||
|
@ -980,7 +980,7 @@ impl UCommand {
|
|||
}
|
||||
|
||||
/// provides standard input to feed in to the command when spawned
|
||||
pub fn pipe_in<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!(
|
||||
self.bytes_into_stdin.is_none(),
|
||||
"{}",
|
||||
|
@ -991,7 +991,7 @@ impl UCommand {
|
|||
}
|
||||
|
||||
/// like pipe_in(...), but uses the contents of the file at the provided relative path as the piped in data
|
||||
pub fn pipe_in_fixture<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);
|
||||
self.pipe_in(contents)
|
||||
}
|
||||
|
@ -999,13 +999,13 @@ impl UCommand {
|
|||
/// Ignores error caused by feeding stdin to the command.
|
||||
/// This is typically useful to test non-standard workflows
|
||||
/// like feeding something to a command that does not read it
|
||||
pub fn ignore_stdin_write_error(&mut self) -> &mut UCommand {
|
||||
pub fn ignore_stdin_write_error(&mut self) -> &mut Self {
|
||||
assert!(self.bytes_into_stdin.is_some(), "{}", NO_STDIN_MEANINGLESS);
|
||||
self.ignore_stdin_write_error = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut UCommand
|
||||
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
|
||||
where
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue