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

Merge pull request #2963 from danieleades/refactor/code-quality

Refactor/code quality
This commit is contained in:
Sylvestre Ledru 2022-01-30 18:26:16 +01:00 committed by GitHub
commit de07df5992
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
150 changed files with 941 additions and 972 deletions

View file

@ -67,7 +67,7 @@ pub fn main() {
)
.as_bytes(),
)
.unwrap()
.unwrap();
}
k if k.starts_with(OVERRIDE_PREFIX) => {
phf_map.entry(&k[OVERRIDE_PREFIX.len()..], &map_value);
@ -79,7 +79,7 @@ pub fn main() {
)
.as_bytes(),
)
.unwrap()
.unwrap();
}
"false" | "true" => {
phf_map.entry(
@ -94,7 +94,7 @@ pub fn main() {
)
.as_bytes(),
)
.unwrap()
.unwrap();
}
"hashsum" => {
phf_map.entry(
@ -124,7 +124,7 @@ pub fn main() {
)
.as_bytes(),
)
.unwrap()
.unwrap();
}
_ => {
phf_map.entry(krate, &map_value);
@ -136,7 +136,7 @@ pub fn main() {
)
.as_bytes(),
)
.unwrap()
.unwrap();
}
}
}

View file

@ -63,7 +63,7 @@ fn main() {
// * prefix/stem may be any string ending in a non-alphanumeric character
let util_name = if let Some(util) = utils.keys().find(|util| {
binary_as_util.ends_with(*util)
&& !(&binary_as_util[..binary_as_util.len() - (*util).len()])
&& !binary_as_util[..binary_as_util.len() - (*util).len()]
.ends_with(char::is_alphanumeric)
}) {
// prefixed util => replace 0th (aka, executable name) argument

View file

@ -44,7 +44,7 @@ fn main() -> io::Result<()> {
} else {
println!("Error writing to {}", p);
}
writeln!(summary, "* [{0}](utils/{0}.md)", name)?
writeln!(summary, "* [{0}](utils/{0}.md)", name)?;
}
Ok(())
}

View file

@ -38,7 +38,7 @@ pub mod options {
}
impl Config {
pub fn from(options: &clap::ArgMatches) -> UResult<Config> {
pub fn from(options: &clap::ArgMatches) -> UResult<Self> {
let file: Option<String> = match options.values_of(options::FILE) {
Some(mut values) => {
let name = values.next().unwrap();
@ -76,7 +76,7 @@ impl Config {
})
.transpose()?;
Ok(Config {
Ok(Self {
decode: options.is_present(options::DECODE),
ignore_garbage: options.is_present(options::IGNORE_GARBAGE),
wrap_cols: cols,
@ -153,7 +153,7 @@ pub fn handle_input<R: Read>(
if !decode {
match data.encode() {
Ok(s) => {
wrap_print(&data, s);
wrap_print(&data, &s);
Ok(())
}
Err(_) => Err(USimpleError::new(

View file

@ -236,7 +236,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
show_tabs,
squeeze_blank,
};
cat_files(files, &options)
cat_files(&files, &options)
}
pub fn uu_app<'a>() -> App<'a> {
@ -365,7 +365,7 @@ fn cat_path(
}
}
fn cat_files(files: Vec<String>, options: &OutputOptions) -> UResult<()> {
fn cat_files(files: &[String], options: &OutputOptions) -> UResult<()> {
let out_info = FileInformation::from_file(&std::io::stdout());
let mut state = OutputState {
@ -376,7 +376,7 @@ fn cat_files(files: Vec<String>, options: &OutputOptions) -> UResult<()> {
};
let mut error_messages: Vec<String> = Vec::new();
for path in &files {
for path in files {
if let Err(err) = cat_path(path, options, &mut state, out_info.as_ref()) {
error_messages.push(format!("{}: {}", path.maybe_quote(), err));
}
@ -479,7 +479,7 @@ fn write_lines<R: FdReadable>(
if !state.at_line_start || !options.squeeze_blank || !state.one_blank_kept {
state.one_blank_kept = true;
if state.at_line_start && options.number == NumberingMode::All {
write!(&mut writer, "{0:6}\t", state.line_number)?;
write!(writer, "{0:6}\t", state.line_number)?;
state.line_number += 1;
}
writer.write_all(options.end_of_line().as_bytes())?;
@ -498,7 +498,7 @@ fn write_lines<R: FdReadable>(
}
state.one_blank_kept = false;
if state.at_line_start && options.number != NumberingMode::None {
write!(&mut writer, "{0:6}\t", state.line_number)?;
write!(writer, "{0:6}\t", state.line_number)?;
state.line_number += 1;
}

View file

@ -743,7 +743,7 @@ This almost certainly means that you have a corrupted file system.\n\
NOTIFY YOUR SYSTEM MANAGER.\n\
The following directory is part of the cycle {}.",
file_name.quote()
)
);
}
#[derive(Debug)]

View file

@ -64,10 +64,10 @@ impl Error {
pub(crate) fn report_full_error(mut err: &dyn std::error::Error) -> String {
let mut desc = String::with_capacity(256);
write!(&mut desc, "{}", err).unwrap();
write!(desc, "{}", err).unwrap();
while let Some(source) = err.source() {
err = source;
write!(&mut desc, ". {}", err).unwrap();
write!(desc, ". {}", err).unwrap();
}
desc
}

View file

@ -118,7 +118,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
cmode,
};
chmoder.chmod(files)
chmoder.chmod(&files)
}
pub fn uu_app<'a>() -> App<'a> {
@ -193,10 +193,10 @@ struct Chmoder {
}
impl Chmoder {
fn chmod(&self, files: Vec<String>) -> UResult<()> {
fn chmod(&self, files: &[String]) -> UResult<()> {
let mut r = Ok(());
for filename in &files {
for filename in files {
let filename = &filename[..];
let file = Path::new(filename);
if !file.exists() {

View file

@ -495,43 +495,43 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
impl ClobberMode {
fn from_matches(matches: &ArgMatches) -> ClobberMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::FORCE) {
ClobberMode::Force
Self::Force
} else if matches.is_present(options::REMOVE_DESTINATION) {
ClobberMode::RemoveDestination
Self::RemoveDestination
} else {
ClobberMode::Standard
Self::Standard
}
}
}
impl OverwriteMode {
fn from_matches(matches: &ArgMatches) -> OverwriteMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::INTERACTIVE) {
OverwriteMode::Interactive(ClobberMode::from_matches(matches))
Self::Interactive(ClobberMode::from_matches(matches))
} else if matches.is_present(options::NO_CLOBBER) {
OverwriteMode::NoClobber
Self::NoClobber
} else {
OverwriteMode::Clobber(ClobberMode::from_matches(matches))
Self::Clobber(ClobberMode::from_matches(matches))
}
}
}
impl CopyMode {
fn from_matches(matches: &ArgMatches) -> CopyMode {
fn from_matches(matches: &ArgMatches) -> Self {
if matches.is_present(options::LINK) {
CopyMode::Link
Self::Link
} else if matches.is_present(options::SYMBOLIC_LINK) {
CopyMode::SymLink
Self::SymLink
} else if matches.is_present(options::SPARSE) {
CopyMode::Sparse
Self::Sparse
} else if matches.is_present(options::UPDATE) {
CopyMode::Update
Self::Update
} else if matches.is_present(options::ATTRIBUTES_ONLY) {
CopyMode::AttrOnly
Self::AttrOnly
} else {
CopyMode::Copy
Self::Copy
}
}
}
@ -539,16 +539,16 @@ impl CopyMode {
impl FromStr for Attribute {
type Err = Error;
fn from_str(value: &str) -> CopyResult<Attribute> {
fn from_str(value: &str) -> CopyResult<Self> {
Ok(match &*value.to_lowercase() {
"mode" => Attribute::Mode,
"mode" => Self::Mode,
#[cfg(unix)]
"ownership" => Attribute::Ownership,
"timestamps" => Attribute::Timestamps,
"ownership" => Self::Ownership,
"timestamps" => Self::Timestamps,
#[cfg(feature = "feat_selinux")]
"context" => Attribute::Context,
"links" => Attribute::Links,
"xattr" => Attribute::Xattr,
"context" => Self::Context,
"links" => Self::Links,
"xattr" => Self::Xattr,
_ => {
return Err(Error::InvalidArgument(format!(
"invalid attribute {}",
@ -577,7 +577,7 @@ fn add_all_attributes() -> Vec<Attribute> {
}
impl Options {
fn from_matches(matches: &ArgMatches) -> CopyResult<Options> {
fn from_matches(matches: &ArgMatches) -> CopyResult<Self> {
let not_implemented_opts = vec![
options::COPY_CONTENTS,
options::SPARSE,
@ -646,7 +646,7 @@ impl Options {
// if not executed first.
preserve_attributes.sort_unstable();
let options = Options {
let options = Self {
attributes_only: matches.is_present(options::ATTRIBUTES_ONLY),
copy_contents: matches.is_present(options::COPY_CONTENTS),
copy_mode: CopyMode::from_matches(matches),
@ -703,11 +703,11 @@ impl TargetType {
///
/// Treat target as a dir if we have multiple sources or the target
/// exists and already is a directory
fn determine(sources: &[Source], target: &TargetSlice) -> TargetType {
fn determine(sources: &[Source], target: &TargetSlice) -> Self {
if sources.len() > 1 || target.is_dir() {
TargetType::Directory
Self::Directory
} else {
TargetType::File
Self::File
}
}
}
@ -741,8 +741,8 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec<S
};
if options.strip_trailing_slashes {
for source in paths.iter_mut() {
*source = source.components().as_path().to_owned()
for source in &mut paths {
*source = source.components().as_path().to_owned();
}
}
@ -752,7 +752,7 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec<S
fn preserve_hardlinks(
hard_links: &mut Vec<(String, u64)>,
source: &std::path::Path,
dest: std::path::PathBuf,
dest: &std::path::Path,
found_hard_link: &mut bool,
) -> CopyResult<()> {
// Redox does not currently support hard links
@ -805,7 +805,7 @@ fn preserve_hardlinks(
for hard_link in hard_links.iter() {
if hard_link.1 == inode {
std::fs::hard_link(hard_link.0.clone(), dest.clone()).unwrap();
std::fs::hard_link(hard_link.0.clone(), dest).unwrap();
*found_hard_link = true;
}
}
@ -849,7 +849,7 @@ fn copy(sources: &[Source], target: &TargetSlice, options: &Options) -> CopyResu
let mut found_hard_link = false;
if preserve_hard_links {
let dest = construct_dest_path(source, target, &target_type, options)?;
preserve_hardlinks(&mut hard_links, source, dest, &mut found_hard_link)?;
preserve_hardlinks(&mut hard_links, source, &dest, &mut found_hard_link)?;
}
if !found_hard_link {
if let Err(error) =
@ -864,7 +864,7 @@ fn copy(sources: &[Source], target: &TargetSlice, options: &Options) -> CopyResu
}
_ => {
show_error!("{}", error);
non_fatal_errors = true
non_fatal_errors = true;
}
}
}
@ -1031,7 +1031,7 @@ fn copy_directory(
let mut found_hard_link = false;
let source = path.to_path_buf();
let dest = local_to_target.as_path().to_path_buf();
preserve_hardlinks(&mut hard_links, &source, dest, &mut found_hard_link)?;
preserve_hardlinks(&mut hard_links, &source, &dest, &mut found_hard_link)?;
if !found_hard_link {
match copy_file(
path.as_path(),
@ -1580,5 +1580,5 @@ fn test_cp_localize_to_target() {
)
.unwrap()
== Path::new("target/c.txt")
)
);
}

View file

@ -57,13 +57,13 @@ pub struct CsplitOptions {
}
impl CsplitOptions {
fn new(matches: &ArgMatches) -> CsplitOptions {
fn new(matches: &ArgMatches) -> Self {
let keep_files = matches.is_present(options::KEEP_FILES);
let quiet = matches.is_present(options::QUIET);
let elide_empty_files = matches.is_present(options::ELIDE_EMPTY_FILES);
let suppress_matched = matches.is_present(options::SUPPRESS_MATCHED);
CsplitOptions {
Self {
split_name: crash_if_err!(
1,
SplitName::new(
@ -108,9 +108,9 @@ where
input_iter.rewind_buffer();
if let Some((_, line)) = input_iter.next() {
split_writer.new_writer()?;
split_writer.writeln(line?)?;
split_writer.writeln(&line?)?;
for (_, line) in input_iter {
split_writer.writeln(line?)?;
split_writer.writeln(&line?)?;
}
split_writer.finish_split();
}
@ -250,7 +250,7 @@ impl<'a> SplitWriter<'a> {
/// # Errors
///
/// Some [`io::Error`] may occur when attempting to write the line.
fn writeln(&mut self, line: String) -> io::Result<()> {
fn writeln(&mut self, line: &str) -> io::Result<()> {
if !self.dev_null {
match self.current_writer {
Some(ref mut current_writer) => {
@ -343,7 +343,7 @@ impl<'a> SplitWriter<'a> {
}
Ordering::Greater => (),
}
self.writeln(l)?;
self.writeln(&l)?;
}
self.finish_split();
ret
@ -373,7 +373,7 @@ impl<'a> SplitWriter<'a> {
// The offset is zero or positive, no need for a buffer on the lines read.
// NOTE: drain the buffer of input_iter, no match should be done within.
for line in input_iter.drain_buffer() {
self.writeln(line)?;
self.writeln(&line)?;
}
// retain the matching line
input_iter.set_size_of_buffer(1);
@ -390,7 +390,7 @@ impl<'a> SplitWriter<'a> {
);
}
// a positive offset, some more lines need to be added to the current split
(false, _) => self.writeln(l)?,
(false, _) => self.writeln(&l)?,
_ => (),
};
offset -= 1;
@ -399,7 +399,7 @@ impl<'a> SplitWriter<'a> {
while offset > 0 {
match input_iter.next() {
Some((_, line)) => {
self.writeln(line?)?;
self.writeln(&line?)?;
}
None => {
self.finish_split();
@ -413,7 +413,7 @@ impl<'a> SplitWriter<'a> {
self.finish_split();
return Ok(());
}
self.writeln(l)?;
self.writeln(&l)?;
}
} else {
// With a negative offset we use a buffer to keep the lines within the offset.
@ -427,7 +427,7 @@ impl<'a> SplitWriter<'a> {
let l = line?;
if regex.is_match(&l) {
for line in input_iter.shrink_buffer_to_size() {
self.writeln(line)?;
self.writeln(&line)?;
}
if !self.options.suppress_matched {
// add 1 to the buffer size to make place for the matched line
@ -444,12 +444,12 @@ impl<'a> SplitWriter<'a> {
return Ok(());
}
if let Some(line) = input_iter.add_line_to_buffer(ln, l) {
self.writeln(line)?;
self.writeln(&line)?;
}
}
// no match, drain the buffer into the current split
for line in input_iter.drain_buffer() {
self.writeln(line)?;
self.writeln(&line)?;
}
}
@ -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,

View file

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

View file

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

View file

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

View file

@ -340,7 +340,7 @@ fn cut_fields<R: Read>(reader: R, ranges: &[Range], opts: &FieldOptions) -> URes
Ok(())
}
fn cut_files(mut filenames: Vec<String>, mode: Mode) -> UResult<()> {
fn cut_files(mut filenames: Vec<String>, mode: &Mode) -> UResult<()> {
let mut stdin_read = false;
if filenames.is_empty() {
@ -527,7 +527,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.collect();
match mode_parse {
Ok(mode) => cut_files(files, mode),
Ok(mode) => cut_files(files, &mode),
Err(e) => Err(USimpleError::new(1, e)),
}
}

View file

@ -72,7 +72,7 @@ mod tests {
assert_eq!(vec![] as Vec<usize>, items);
}
fn test_multibyte(line: &[u8], expected: Vec<usize>) {
fn test_multibyte(line: &[u8], expected: &[usize]) {
let iter = Searcher::new(line, NEEDLE);
let items: Vec<usize> = iter.collect();
assert_eq!(expected, items);
@ -80,26 +80,26 @@ mod tests {
#[test]
fn test_multibyte_normal() {
test_multibyte("...ab...ab...".as_bytes(), vec![3, 8]);
test_multibyte("...ab...ab...".as_bytes(), &[3, 8]);
}
#[test]
fn test_multibyte_needle_head_at_end() {
test_multibyte("a".as_bytes(), vec![]);
test_multibyte("a".as_bytes(), &[]);
}
#[test]
fn test_multibyte_starting_needle() {
test_multibyte("ab...ab...".as_bytes(), vec![0, 5]);
test_multibyte("ab...ab...".as_bytes(), &[0, 5]);
}
#[test]
fn test_multibyte_trailing_needle() {
test_multibyte("...ab...ab".as_bytes(), vec![3, 8]);
test_multibyte("...ab...ab".as_bytes(), &[3, 8]);
}
#[test]
fn test_multibyte_first_byte_false_match() {
test_multibyte("aA..aCaC..ab..aD".as_bytes(), vec![10]);
test_multibyte("aA..aCaC..ab..aD".as_bytes(), &[10]);
}
}

View file

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

View file

@ -69,7 +69,7 @@ impl Input<io::Stdin> {
let skip = parseargs::parse_skip_amt(&ibs, &iflags, matches)?;
let count = parseargs::parse_count(&iflags, matches)?;
let mut i = Input {
let mut i = Self {
src: io::stdin(),
non_ascii,
ibs,
@ -157,7 +157,7 @@ impl Input<File> {
.map_err_context(|| "failed to seek in input file".to_string())?;
}
let i = Input {
let i = Self {
src,
non_ascii,
ibs,
@ -306,7 +306,7 @@ impl OutputTrait for Output<io::Stdout> {
.map_err_context(|| String::from("write error"))?;
}
Ok(Output { dst, obs, cflags })
Ok(Self { dst, obs, cflags })
}
fn fsync(&mut self) -> io::Result<()> {
@ -322,7 +322,7 @@ impl<W: Write> Output<W>
where
Self: OutputTrait,
{
fn write_blocks(&mut self, buf: Vec<u8>) -> io::Result<WriteStat> {
fn write_blocks(&mut self, buf: &[u8]) -> io::Result<WriteStat> {
let mut writes_complete = 0;
let mut writes_partial = 0;
let mut bytes_total = 0;
@ -381,7 +381,7 @@ where
) => break,
(rstat_update, buf) => {
let wstat_update = self
.write_blocks(buf)
.write_blocks(&buf)
.map_err_context(|| "failed to write output".to_string())?;
rstat += rstat_update;
@ -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
@ -560,7 +560,7 @@ impl Write for Output<io::Stdout> {
/// Splits the content of buf into cbs-length blocks
/// Appends padding as specified by conv=block and cbs=N
/// Expects ascii encoded data
fn block(buf: Vec<u8>, cbs: usize, rstat: &mut ReadStat) -> Vec<Vec<u8>> {
fn block(buf: &[u8], cbs: usize, rstat: &mut ReadStat) -> Vec<Vec<u8>> {
let mut blocks = buf
.split(|&e| e == NEWLINE)
.map(|split| split.to_vec())
@ -586,7 +586,7 @@ fn block(buf: Vec<u8>, cbs: usize, rstat: &mut ReadStat) -> Vec<Vec<u8>> {
/// Trims padding from each cbs-length partition of buf
/// as specified by conv=unblock and cbs=N
/// Expects ascii encoded data
fn unblock(buf: Vec<u8>, cbs: usize) -> Vec<u8> {
fn unblock(buf: &[u8], cbs: usize) -> Vec<u8> {
buf.chunks(cbs).fold(Vec::new(), |mut acc, block| {
if let Some(last_char_idx) = block.iter().rposition(|&e| e != SPACE) {
// Include text up to last space.
@ -643,10 +643,10 @@ fn conv_block_unblock_helper<R: Read>(
// ascii input so perform the block first
let cbs = i.cflags.block.unwrap();
let mut blocks = block(buf, cbs, rstat);
let mut blocks = block(&buf, cbs, rstat);
if let Some(ct) = i.cflags.ctable {
for buf in blocks.iter_mut() {
for buf in &mut blocks {
apply_conversion(buf, ct);
}
}
@ -662,14 +662,14 @@ fn conv_block_unblock_helper<R: Read>(
apply_conversion(&mut buf, ct);
}
let blocks = block(buf, cbs, rstat).into_iter().flatten().collect();
let blocks = block(&buf, cbs, rstat).into_iter().flatten().collect();
Ok(blocks)
} else if should_unblock_then_conv(i) {
// ascii input so perform the unblock first
let cbs = i.cflags.unblock.unwrap();
let mut buf = unblock(buf, cbs);
let mut buf = unblock(&buf, cbs);
if let Some(ct) = i.cflags.ctable {
apply_conversion(&mut buf, ct);
@ -684,7 +684,7 @@ fn conv_block_unblock_helper<R: Read>(
apply_conversion(&mut buf, ct);
}
let buf = unblock(buf, cbs);
let buf = unblock(&buf, cbs);
Ok(buf)
} else {

View file

@ -63,8 +63,8 @@ macro_rules! make_unblock_test (
#[test]
fn block_test_no_nl() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8];
let res = block(buf, 4, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8];
let res = block(&buf, 4, &mut rs);
assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]);
}
@ -72,8 +72,8 @@ fn block_test_no_nl() {
#[test]
fn block_test_no_nl_short_record() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8];
let res = block(buf, 8, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8];
let res = block(&buf, 8, &mut rs);
assert_eq!(
res,
@ -84,8 +84,8 @@ fn block_test_no_nl_short_record() {
#[test]
fn block_test_no_nl_trunc() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8];
let res = block(buf, 4, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8, 4u8];
let res = block(&buf, 4, &mut rs);
// Commented section(s) should be truncated and appear for reference only.
assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8 /*, 4u8*/],]);
@ -95,10 +95,10 @@ fn block_test_no_nl_trunc() {
#[test]
fn block_test_nl_gt_cbs_trunc() {
let mut rs = ReadStat::default();
let buf = vec![
let buf = [
0u8, 1u8, 2u8, 3u8, 4u8, NEWLINE, 0u8, 1u8, 2u8, 3u8, 4u8, NEWLINE, 5u8, 6u8, 7u8, 8u8,
];
let res = block(buf, 4, &mut rs);
let res = block(&buf, 4, &mut rs);
assert_eq!(
res,
@ -117,8 +117,8 @@ fn block_test_nl_gt_cbs_trunc() {
#[test]
fn block_test_surrounded_nl() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8];
let res = block(buf, 8, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8];
let res = block(&buf, 8, &mut rs);
assert_eq!(
res,
@ -132,10 +132,10 @@ fn block_test_surrounded_nl() {
#[test]
fn block_test_multiple_nl_same_cbs_block() {
let mut rs = ReadStat::default();
let buf = vec![
let buf = [
0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, NEWLINE, 5u8, 6u8, 7u8, 8u8, 9u8,
];
let res = block(buf, 8, &mut rs);
let res = block(&buf, 8, &mut rs);
assert_eq!(
res,
@ -150,10 +150,10 @@ fn block_test_multiple_nl_same_cbs_block() {
#[test]
fn block_test_multiple_nl_diff_cbs_block() {
let mut rs = ReadStat::default();
let buf = vec![
let buf = [
0u8, 1u8, 2u8, 3u8, NEWLINE, 4u8, 5u8, 6u8, 7u8, NEWLINE, 8u8, 9u8,
];
let res = block(buf, 8, &mut rs);
let res = block(&buf, 8, &mut rs);
assert_eq!(
res,
@ -168,8 +168,8 @@ fn block_test_multiple_nl_diff_cbs_block() {
#[test]
fn block_test_end_nl_diff_cbs_block() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE];
let res = block(buf, 4, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE];
let res = block(&buf, 4, &mut rs);
assert_eq!(res, vec![vec![0u8, 1u8, 2u8, 3u8],]);
}
@ -177,8 +177,8 @@ fn block_test_end_nl_diff_cbs_block() {
#[test]
fn block_test_end_nl_same_cbs_block() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, NEWLINE];
let res = block(buf, 4, &mut rs);
let buf = [0u8, 1u8, 2u8, NEWLINE];
let res = block(&buf, 4, &mut rs);
assert_eq!(res, vec![vec![0u8, 1u8, 2u8, SPACE]]);
}
@ -186,8 +186,8 @@ fn block_test_end_nl_same_cbs_block() {
#[test]
fn block_test_double_end_nl() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, NEWLINE, NEWLINE];
let res = block(buf, 4, &mut rs);
let buf = [0u8, 1u8, 2u8, NEWLINE, NEWLINE];
let res = block(&buf, 4, &mut rs);
assert_eq!(
res,
@ -198,8 +198,8 @@ fn block_test_double_end_nl() {
#[test]
fn block_test_start_nl() {
let mut rs = ReadStat::default();
let buf = vec![NEWLINE, 0u8, 1u8, 2u8, 3u8];
let res = block(buf, 4, &mut rs);
let buf = [NEWLINE, 0u8, 1u8, 2u8, 3u8];
let res = block(&buf, 4, &mut rs);
assert_eq!(
res,
@ -210,8 +210,8 @@ fn block_test_start_nl() {
#[test]
fn block_test_double_surrounded_nl_no_trunc() {
let mut rs = ReadStat::default();
let buf = vec![0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8];
let res = block(buf, 8, &mut rs);
let buf = [0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8];
let res = block(&buf, 8, &mut rs);
assert_eq!(
res,
@ -226,10 +226,10 @@ fn block_test_double_surrounded_nl_no_trunc() {
#[test]
fn block_test_double_surrounded_nl_double_trunc() {
let mut rs = ReadStat::default();
let buf = vec![
let buf = [
0u8, 1u8, 2u8, 3u8, NEWLINE, NEWLINE, 4u8, 5u8, 6u8, 7u8, 8u8,
];
let res = block(buf, 4, &mut rs);
let res = block(&buf, 4, &mut rs);
assert_eq!(
res,
@ -272,24 +272,24 @@ make_block_test!(
#[test]
fn unblock_test_full_cbs() {
let buf = vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8];
let res = unblock(buf, 8);
let buf = [0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8];
let res = unblock(&buf, 8);
assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, NEWLINE],);
}
#[test]
fn unblock_test_all_space() {
let buf = vec![SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE];
let res = unblock(buf, 8);
let buf = [SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE];
let res = unblock(&buf, 8);
assert_eq!(res, vec![NEWLINE],);
}
#[test]
fn unblock_test_decoy_spaces() {
let buf = vec![0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8];
let res = unblock(buf, 8);
let buf = [0u8, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, 7u8];
let res = unblock(&buf, 8);
assert_eq!(
res,
@ -299,8 +299,8 @@ fn unblock_test_decoy_spaces() {
#[test]
fn unblock_test_strip_single_cbs() {
let buf = vec![0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE];
let res = unblock(buf, 8);
let buf = [0u8, 1u8, 2u8, 3u8, SPACE, SPACE, SPACE, SPACE];
let res = unblock(&buf, 8);
assert_eq!(res, vec![0u8, 1u8, 2u8, 3u8, NEWLINE],);
}
@ -317,7 +317,7 @@ fn unblock_test_strip_multi_cbs() {
.flatten()
.collect::<Vec<_>>();
let res = unblock(buf, 8);
let res = unblock(&buf, 8);
let exp = vec![
vec![0u8, NEWLINE],

View file

@ -296,9 +296,9 @@ impl std::str::FromStr for StatusLevel {
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"none" => Ok(StatusLevel::None),
"noxfer" => Ok(StatusLevel::Noxfer),
"progress" => Ok(StatusLevel::Progress),
"none" => Ok(Self::None),
"noxfer" => Ok(Self::Noxfer),
"progress" => Ok(Self::Progress),
_ => Err(ParseError::StatusLevelNotRecognized(s.to_string())),
}
}
@ -491,14 +491,14 @@ pub fn parse_conv_flag_input(matches: &Matches) -> Result<IConvFlags, ParseError
if case.is_some() {
return Err(ParseError::MultipleUCaseLCase);
} else {
case = Some(flag)
case = Some(flag);
}
}
ConvFlag::LCase => {
if case.is_some() {
return Err(ParseError::MultipleUCaseLCase);
} else {
case = Some(flag)
case = Some(flag);
}
}
ConvFlag::Block => match (cbs, iconvflags.unblock) {

View file

@ -56,10 +56,10 @@ fn unimplemented_flags_should_error() {
let matches = uu_app().try_get_matches_from(args).unwrap();
if parse_iflags(&matches).is_ok() {
succeeded.push(format!("iflag={}", flag))
succeeded.push(format!("iflag={}", flag));
}
if parse_oflags(&matches).is_ok() {
succeeded.push(format!("oflag={}", flag))
succeeded.push(format!("oflag={}", flag));
}
}

View file

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

View file

@ -127,7 +127,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let result;
if files.is_empty() {
result = parse(INTERNAL_DB.lines(), out_format, "")
result = parse(INTERNAL_DB.lines(), &out_format, "");
} else {
if files.len() > 1 {
return Err(UUsageError::new(
@ -138,7 +138,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
match File::open(files[0]) {
Ok(f) => {
let fin = BufReader::new(f);
result = parse(fin.lines().filter_map(Result::ok), out_format, files[0])
result = parse(fin.lines().filter_map(Result::ok), &out_format, files[0]);
}
Err(e) => {
return Err(USimpleError::new(
@ -259,7 +259,7 @@ enum ParseState {
use std::collections::HashMap;
use uucore::InvalidEncodingHandling;
fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String>
fn parse<T>(lines: T, fmt: &OutputFmt, fp: &str) -> Result<String, String>
where
T: IntoIterator,
T::Item: Borrow<str>,

View file

@ -56,12 +56,12 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.collect();
if !dirnames.is_empty() {
for path in dirnames.iter() {
for path in &dirnames {
let p = Path::new(path);
match p.parent() {
Some(d) => {
if d.components().next() == None {
print!(".")
print!(".");
} else {
print_verbatim(d).unwrap();
}

View file

@ -114,7 +114,7 @@ struct Stat {
}
impl Stat {
fn new(path: PathBuf, options: &Options) -> Result<Stat> {
fn new(path: PathBuf, options: &Options) -> Result<Self> {
let metadata = if options.dereference {
fs::metadata(&path)?
} else {
@ -127,7 +127,7 @@ impl Stat {
dev_id: metadata.dev(),
};
#[cfg(not(windows))]
return Ok(Stat {
return Ok(Self {
path,
is_dir: metadata.is_dir(),
size: metadata.len(),
@ -247,7 +247,7 @@ fn get_file_info(path: &Path) -> Option<FileInfo> {
fn read_block_size(s: Option<&str>) -> usize {
if let Some(s) = s {
parse_size(s)
.unwrap_or_else(|e| crash!(1, "{}", format_error_message(e, s, options::BLOCK_SIZE)))
.unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::BLOCK_SIZE)))
} else {
for env_var in &["DU_BLOCK_SIZE", "BLOCK_SIZE", "BLOCKSIZE"] {
if let Ok(env_size) = env::var(env_var) {
@ -335,7 +335,7 @@ fn du(
ErrorKind::PermissionDenied => {
let description = format!("cannot access {}", entry.path().quote());
let error_message = "Permission denied";
show_error_custom_description!(description, "{}", error_message)
show_error_custom_description!(description, "{}", error_message);
}
_ => show_error!("cannot access {}: {}", entry.path().quote(), error),
},
@ -486,14 +486,14 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if options.inodes
&& (matches.is_present(options::APPARENT_SIZE) || matches.is_present(options::BYTES))
{
show_warning!("options --apparent-size and -b are ineffective with --inodes")
show_warning!("options --apparent-size and -b are ineffective with --inodes");
}
let block_size = u64::try_from(read_block_size(matches.value_of(options::BLOCK_SIZE))).unwrap();
let threshold = matches.value_of(options::THRESHOLD).map(|s| {
Threshold::from_str(s)
.unwrap_or_else(|e| crash!(1, "{}", format_error_message(e, s, options::THRESHOLD)))
.unwrap_or_else(|e| crash!(1, "{}", format_error_message(&e, s, options::THRESHOLD)))
});
let multiplier: u64 = if matches.is_present(options::SI) {
@ -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,13 +825,13 @@ 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,
}
}
}
fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String {
fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String {
// NOTE:
// GNU's du echos affected flag, -B or --block-size (-t or --threshold), depending user's selection
// GNU's du does distinguish between "invalid (suffix in) argument"
@ -853,7 +853,7 @@ mod test_du {
(Some("K".to_string()), 1024),
(None, 1024),
];
for it in test_data.iter() {
for it in &test_data {
assert_eq!(read_block_size(it.0.as_deref()), it.1);
}
}

View file

@ -125,7 +125,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
None => vec!["".to_string()],
};
execute(no_newline, escaped, values).map_err_context(|| "could not write to stdout".to_string())
execute(no_newline, escaped, &values)
.map_err_context(|| "could not write to stdout".to_string())
}
pub fn uu_app<'a>() -> App<'a> {
@ -162,7 +163,7 @@ pub fn uu_app<'a>() -> App<'a> {
.arg(Arg::new(options::STRING).multiple_occurrences(true))
}
fn execute(no_newline: bool, escaped: bool, free: Vec<String>) -> io::Result<()> {
fn execute(no_newline: bool, escaped: bool, free: &[String]) -> io::Result<()> {
let stdout = io::stdout();
let mut output = stdout.lock();

View file

@ -67,7 +67,7 @@ fn is_space_or_comma(c: char) -> bool {
/// in the list. This mode defines the strategy to use for computing the
/// number of spaces to use for columns beyond the end of the tab stop
/// list specified here.
fn tabstops_parse(s: String) -> (RemainingMode, Vec<usize>) {
fn tabstops_parse(s: &str) -> (RemainingMode, Vec<usize>) {
// Leading commas and spaces are ignored.
let s = s.trim_start_matches(is_space_or_comma);
@ -133,9 +133,9 @@ 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.to_string()),
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,
@ -176,7 +176,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let usage = usage();
let matches = uu_app().override_usage(&usage[..]).get_matches_from(args);
expand(Options::new(&matches)).map_err_context(|| "failed to write output".to_string())
expand(&Options::new(&matches)).map_err_context(|| "failed to write output".to_string())
}
pub fn uu_app<'a>() -> App<'a> {
@ -212,12 +212,12 @@ pub fn uu_app<'a>() -> App<'a> {
)
}
fn open(path: String) -> BufReader<Box<dyn Read + 'static>> {
fn open(path: &str) -> BufReader<Box<dyn Read + 'static>> {
let file_buf;
if path == "-" {
BufReader::new(Box::new(stdin()) as Box<dyn Read>)
} else {
file_buf = match File::open(&path[..]) {
file_buf = match File::open(path) {
Ok(a) => a,
Err(e) => crash!(1, "{}: {}\n", path.maybe_quote(), e),
};
@ -271,14 +271,14 @@ enum CharType {
Other,
}
fn expand(options: Options) -> std::io::Result<()> {
fn expand(options: &Options) -> std::io::Result<()> {
use self::CharType::*;
let mut output = BufWriter::new(stdout());
let ts = options.tabstops.as_ref();
let mut buf = Vec::new();
for file in options.files.into_iter() {
for file in &options.files {
let mut fh = open(file);
while match fh.read_until(b'\n', &mut buf) {
@ -332,7 +332,7 @@ fn expand(options: Options) -> std::io::Result<()> {
// now dump out either spaces if we're expanding, or a literal tab if we're not
if init || !options.iflag {
if nts <= options.tspaces.len() {
output.write_all(options.tspaces[..nts].as_bytes())?
output.write_all(options.tspaces[..nts].as_bytes())?;
} else {
output.write_all(" ".repeat(nts).as_bytes())?;
};

View file

@ -66,23 +66,23 @@ impl AstNode {
}
}
fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<AstNode> {
Box::new(AstNode::Node {
fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box<Self> {
Box::new(Self::Node {
token_idx,
op_type: op_type.into(),
operands,
})
}
fn new_leaf(token_idx: usize, value: &str) -> Box<AstNode> {
Box::new(AstNode::Leaf {
fn new_leaf(token_idx: usize, value: &str) -> Box<Self> {
Box::new(Self::Leaf {
token_idx,
value: value.into(),
})
}
pub fn evaluate(&self) -> Result<String, String> {
match self {
AstNode::Leaf { value, .. } => Ok(value.clone()),
AstNode::Node { op_type, .. } => match self.operand_values() {
Self::Leaf { value, .. } => Ok(value.clone()),
Self::Node { op_type, .. } => match self.operand_values() {
Err(reason) => Err(reason),
Ok(operand_values) => match op_type.as_ref() {
"+" => {
@ -370,7 +370,7 @@ fn push_op_to_stack(
},
)) => {
if la && prev_prec >= prec || !la && prev_prec > prec {
out_stack.push(op_stack.pop().unwrap())
out_stack.push(op_stack.pop().unwrap());
} else {
op_stack.push((token_idx, token.clone()));
return Ok(());

View file

@ -42,25 +42,25 @@ pub enum Token {
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Token::InfixOp {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Token::Value { value: v.into() }
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Token::InfixOp { value, .. } => value == "+",
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Token::Value { value, .. } => value.parse::<BigInt>().is_ok(),
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
@ -155,8 +155,8 @@ fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, toke
if should_use_as_escaped {
acc.pop();
acc.push((tok_idx, Token::new_value(s)))
acc.push((tok_idx, Token::new_value(s)));
} else {
acc.push((tok_idx, token))
acc.push((tok_idx, token));
}
}

View file

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

View file

@ -14,7 +14,7 @@ use crate::{miller_rabin, rho, table};
type Exponent = u8;
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
// spell-checker:ignore (names) ErdősKac * Erdős Kac
@ -24,8 +24,8 @@ struct Decomposition(SmallVec<[(u64, Exponent); NUM_FACTORS_INLINE]>);
const NUM_FACTORS_INLINE: usize = 5;
impl Decomposition {
fn one() -> Decomposition {
Decomposition(SmallVec::new())
fn one() -> Self {
Self::default()
}
fn add(&mut self, factor: u64, exp: Exponent) {
@ -34,7 +34,7 @@ impl Decomposition {
if let Some((_, e)) = self.0.iter_mut().find(|(f, _)| *f == factor) {
*e += exp;
} else {
self.0.push((factor, exp))
self.0.push((factor, exp));
}
}
@ -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,17 +73,17 @@ 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) {
debug_assert!(miller_rabin::is_prime(prime));
self.0.borrow_mut().add(prime, exp)
self.0.borrow_mut().add(prime, exp);
}
pub fn push(&mut self, prime: u64) {
self.add(prime, 1)
self.add(prime, 1);
}
#[cfg(test)]
@ -99,7 +99,7 @@ impl fmt::Display for Factors {
for (p, exp) in v.iter() {
for _ in 0..*exp {
write!(f, " {}", p)?
write!(f, " {}", p)?;
}
}
@ -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);
}

View file

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

View file

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

View file

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

View file

@ -384,7 +384,7 @@ fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a Wo
None => return breakwords,
Some(prev) => {
breakwords.push((prev, next_best.break_before));
best_idx = next_best.prev
best_idx = next_best.prev;
}
}
}

View file

@ -60,7 +60,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
None => vec!["-".to_owned()],
};
fold(files, bytes, spaces, width)
fold(&files, bytes, spaces, width)
}
pub fn uu_app<'a>() -> App<'a> {
@ -115,8 +115,8 @@ fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
(args.to_vec(), None)
}
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) -> UResult<()> {
for filename in &filenames {
fn fold(filenames: &[String], bytes: bool, spaces: bool, width: usize) -> UResult<()> {
for filename in filenames {
let filename: &str = filename;
let mut stdin_buf;
let mut file_buf;

View file

@ -40,11 +40,11 @@ pub trait Digest {
impl Digest for md5::Context {
fn new() -> Self {
md5::Context::new()
Self::new()
}
fn input(&mut self, input: &[u8]) {
self.consume(input)
self.consume(input);
}
fn result(&mut self, out: &mut [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]) {

View file

@ -173,28 +173,28 @@ fn detect_algo(
};
name = n;
alg = Some(val);
output_bits = bits
output_bits = bits;
};
if matches.is_present("md5") {
set_or_crash("MD5", Box::new(Md5::new()), 128)
set_or_crash("MD5", Box::new(Md5::new()), 128);
}
if matches.is_present("sha1") {
set_or_crash("SHA1", Box::new(Sha1::new()), 160)
set_or_crash("SHA1", Box::new(Sha1::new()), 160);
}
if matches.is_present("sha224") {
set_or_crash("SHA224", Box::new(Sha224::new()), 224)
set_or_crash("SHA224", Box::new(Sha224::new()), 224);
}
if matches.is_present("sha256") {
set_or_crash("SHA256", Box::new(Sha256::new()), 256)
set_or_crash("SHA256", Box::new(Sha256::new()), 256);
}
if matches.is_present("sha384") {
set_or_crash("SHA384", Box::new(Sha384::new()), 384)
set_or_crash("SHA384", Box::new(Sha384::new()), 384);
}
if matches.is_present("sha512") {
set_or_crash("SHA512", Box::new(Sha512::new()), 512)
set_or_crash("SHA512", Box::new(Sha512::new()), 512);
}
if matches.is_present("b2sum") {
set_or_crash("BLAKE2", Box::new(blake2b_simd::State::new()), 512)
set_or_crash("BLAKE2", Box::new(blake2b_simd::State::new()), 512);
}
if matches.is_present("sha3") {
match matches.value_of("bits") {
@ -229,16 +229,16 @@ fn detect_algo(
}
}
if matches.is_present("sha3-224") {
set_or_crash("SHA3-224", Box::new(Sha3_224::new()), 224)
set_or_crash("SHA3-224", Box::new(Sha3_224::new()), 224);
}
if matches.is_present("sha3-256") {
set_or_crash("SHA3-256", Box::new(Sha3_256::new()), 256)
set_or_crash("SHA3-256", Box::new(Sha3_256::new()), 256);
}
if matches.is_present("sha3-384") {
set_or_crash("SHA3-384", Box::new(Sha3_384::new()), 384)
set_or_crash("SHA3-384", Box::new(Sha3_384::new()), 384);
}
if matches.is_present("sha3-512") {
set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512)
set_or_crash("SHA3-512", Box::new(Sha3_512::new()), 512);
}
if matches.is_present("shake128") {
match matches.value_of("bits") {

View file

@ -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);
@ -424,7 +424,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
if !first {
println!();
}
println!("==> standard input <==")
println!("==> standard input <==");
}
let stdin = std::io::stdin();
let mut stdin = stdin.lock();
@ -460,7 +460,7 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
if !first {
println!();
}
println!("==> {} <==", name)
println!("==> {} <==", name);
}
head_file(&mut file, options)
}

View file

@ -43,11 +43,11 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
// this also saves us 1 heap allocation
'q' => {
quiet = true;
verbose = false
verbose = false;
}
'v' => {
verbose = true;
quiet = false
quiet = false;
}
'z' => zero_terminated = true,
'c' => multiplier = Some(1),
@ -58,20 +58,20 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
_ => return Some(Err(ParseError::Syntax)),
}
if let Some((_, next)) = chars.next() {
c = next
c = next;
} else {
break;
}
}
let mut options = Vec::new();
if quiet {
options.push(OsString::from("-q"))
options.push(OsString::from("-q"));
}
if verbose {
options.push(OsString::from("-v"))
options.push(OsString::from("-v"));
}
if zero_terminated {
options.push(OsString::from("-z"))
options.push(OsString::from("-z"));
}
if let Some(n) = multiplier {
options.push(OsString::from("-c"));

View file

@ -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 }
}
}

View file

@ -335,7 +335,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
if default_format {
id_print(&mut state, groups);
id_print(&mut state, &groups);
}
print!("{}", line_ending);
@ -556,7 +556,7 @@ fn auditid() {
println!("asid={}", auditinfo.ai_asid);
}
fn id_print(state: &mut State, groups: Vec<u32>) {
fn id_print(state: &mut State, groups: &[u32]) {
let uid = state.ids.as_ref().unwrap().uid;
let gid = state.ids.as_ref().unwrap().gid;
let euid = state.ids.as_ref().unwrap().euid;

View file

@ -187,8 +187,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let behavior = behavior(&matches)?;
match behavior.main_function {
MainFunction::Directory => directory(paths, behavior),
MainFunction::Standard => standard(paths, behavior),
MainFunction::Directory => directory(&paths, &behavior),
MainFunction::Standard => standard(paths, &behavior),
}
}
@ -391,7 +391,7 @@ fn behavior(matches: &ArgMatches) -> UResult<Behavior> {
///
/// Returns a Result type with the Err variant containing the error message.
///
fn directory(paths: Vec<String>, b: Behavior) -> UResult<()> {
fn directory(paths: &[String], b: &Behavior) -> UResult<()> {
if paths.is_empty() {
Err(InstallError::DirNeedsArg().into())
} else {
@ -444,7 +444,7 @@ fn is_new_file_path(path: &Path) -> bool {
///
/// Returns a Result type with the Err variant containing the error message.
///
fn standard(mut paths: Vec<String>, b: Behavior) -> UResult<()> {
fn standard(mut paths: Vec<String>, b: &Behavior) -> UResult<()> {
let target: PathBuf = b
.target_dir
.clone()
@ -454,7 +454,7 @@ fn standard(mut paths: Vec<String>, b: Behavior) -> UResult<()> {
let sources = &paths.iter().map(PathBuf::from).collect::<Vec<_>>();
if sources.len() > 1 || (target.exists() && target.is_dir()) {
copy_files_into_dir(sources, &target, &b)
copy_files_into_dir(sources, &target, b)
} else {
if let Some(parent) = target.parent() {
if !parent.exists() && b.create_leading {
@ -471,7 +471,7 @@ fn standard(mut paths: Vec<String>, b: Behavior) -> UResult<()> {
}
if target.is_file() || is_new_file_path(&target) {
copy(&sources[0], &target, &b)
copy(&sources[0], &target, b)
} else {
Err(InstallError::InvalidTarget(target).into())
}

View file

@ -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.

View file

@ -308,7 +308,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings)
if is_symlink(target_dir) {
if target_dir.is_file() {
if let Err(e) = fs::remove_file(target_dir) {
show_error!("Could not update {}: {}", target_dir.quote(), e)
show_error!("Could not update {}: {}", target_dir.quote(), e);
};
}
if target_dir.is_dir() {
@ -316,7 +316,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings)
// considered as a dir
// See test_ln::test_symlink_no_deref_dir
if let Err(e) = fs::remove_dir(target_dir) {
show_error!("Could not update {}: {}", target_dir.quote(), e)
show_error!("Could not update {}: {}", target_dir.quote(), e);
};
}
}
@ -402,7 +402,7 @@ fn link(src: &Path, dst: &Path, settings: &Settings) -> Result<()> {
if !read_yes() {
return Ok(());
}
fs::remove_file(dst)?
fs::remove_file(dst)?;
}
OverwriteMode::Force => fs::remove_file(dst)?,
};

View file

@ -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,
@ -710,7 +710,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.map(|v| v.map(Path::new).collect())
.unwrap_or_else(|| vec![Path::new(".")]);
list(locs, config)
list(locs, &config)
}
pub fn uu_app<'a>() -> App<'a> {
@ -1407,14 +1407,14 @@ impl PathData {
}
}
fn list(locs: Vec<&Path>, config: Config) -> UResult<()> {
fn list(locs: Vec<&Path>, config: &Config) -> UResult<()> {
let mut files = Vec::<PathData>::new();
let mut dirs = Vec::<PathData>::new();
let mut out = BufWriter::new(stdout());
let initial_locs_len = locs.len();
for loc in locs {
let path_data = PathData::new(PathBuf::from(loc), None, None, &config, true);
let path_data = PathData::new(PathBuf::from(loc), None, None, config, true);
// Getting metadata here is no big deal as it's just the CWD
// and we really just want to know if the strings exist as files/dirs
@ -1441,10 +1441,10 @@ fn list(locs: Vec<&Path>, config: Config) -> UResult<()> {
}
}
sort_entries(&mut files, &config, &mut out);
sort_entries(&mut dirs, &config, &mut out);
sort_entries(&mut files, config, &mut out);
sort_entries(&mut dirs, config, &mut out);
display_items(&files, &config, &mut out);
display_items(&files, config, &mut out);
for (pos, path_data) in dirs.iter().enumerate() {
// Do read_dir call here to match GNU semantics by printing
@ -1467,13 +1467,13 @@ fn list(locs: Vec<&Path>, config: Config) -> UResult<()> {
let _ = writeln!(out, "\n{}:", path_data.p_buf.display());
}
}
enter_directory(path_data, read_dir, &config, &mut out);
enter_directory(path_data, read_dir, config, &mut out);
}
Ok(())
}
fn sort_entries(entries: &mut Vec<PathData>, config: &Config, out: &mut BufWriter<Stdout>) {
fn sort_entries(entries: &mut [PathData], config: &Config, out: &mut BufWriter<Stdout>) {
match config.sort {
Sort::Time => entries.sort_by_key(|k| {
Reverse(
@ -1749,7 +1749,7 @@ fn display_items(items: &[PathData], config: &Config, out: &mut BufWriter<Stdout
for item in items {
display_item_long(
item,
PaddingCollection {
&PaddingCollection {
#[cfg(unix)]
longest_inode_len,
longest_link_count_len,
@ -1930,7 +1930,7 @@ fn display_grid(
#[allow(clippy::write_literal)]
fn display_item_long(
item: &PathData,
padding: PaddingCollection,
padding: &PaddingCollection,
config: &Config,
out: &mut BufWriter<Stdout>,
) {
@ -2251,7 +2251,7 @@ fn display_date(metadata: &Metadata, config: &Config) -> String {
// 3. The human-readable format uses powers for 1024, but does not display the "i"
// that is commonly used to denote Kibi, Mebi, etc.
// 4. Kibi and Kilo are denoted differently ("k" and "K", respectively)
fn format_prefixed(prefixed: NumberPrefix<f64>) -> String {
fn format_prefixed(prefixed: &NumberPrefix<f64>) -> String {
match prefixed {
NumberPrefix::Standalone(bytes) => bytes.to_string(),
NumberPrefix::Prefixed(prefix, bytes) => {
@ -2304,8 +2304,8 @@ fn display_size(size: u64, config: &Config) -> String {
// NOTE: The human-readable behavior deviates from the GNU ls.
// The GNU ls uses binary prefixes by default.
match config.size_format {
SizeFormat::Binary => format_prefixed(NumberPrefix::binary(size as f64)),
SizeFormat::Decimal => format_prefixed(NumberPrefix::decimal(size as f64)),
SizeFormat::Binary => format_prefixed(&NumberPrefix::binary(size as f64)),
SizeFormat::Decimal => format_prefixed(&NumberPrefix::decimal(size as f64)),
SizeFormat::Bytes => size.to_string(),
}
}

View file

@ -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,
@ -363,7 +363,7 @@ mod tests {
}
}
fn check_names(name: &str, map: Vec<(&str, &str)>) {
fn check_names(name: &str, map: &[(&str, &str)]) {
assert_eq!(
map.iter()
.map(|(_, style)| escape_name(name.as_ref(), &get_style(style)))
@ -378,7 +378,7 @@ mod tests {
fn test_simple_names() {
check_names(
"one_two",
vec![
&[
("one_two", "literal"),
("one_two", "literal-show"),
("one_two", "escape"),
@ -397,7 +397,7 @@ mod tests {
fn test_spaces() {
check_names(
"one two",
vec![
&[
("one two", "literal"),
("one two", "literal-show"),
("one\\ two", "escape"),
@ -413,7 +413,7 @@ mod tests {
check_names(
" one",
vec![
&[
(" one", "literal"),
(" one", "literal-show"),
("\\ one", "escape"),
@ -433,7 +433,7 @@ mod tests {
// One double quote
check_names(
"one\"two",
vec![
&[
("one\"two", "literal"),
("one\"two", "literal-show"),
("one\"two", "escape"),
@ -450,7 +450,7 @@ mod tests {
// One single quote
check_names(
"one\'two",
vec![
&[
("one'two", "literal"),
("one'two", "literal-show"),
("one'two", "escape"),
@ -467,7 +467,7 @@ mod tests {
// One single quote and one double quote
check_names(
"one'two\"three",
vec![
&[
("one'two\"three", "literal"),
("one'two\"three", "literal-show"),
("one'two\"three", "escape"),
@ -484,7 +484,7 @@ mod tests {
// Consecutive quotes
check_names(
"one''two\"\"three",
vec![
&[
("one''two\"\"three", "literal"),
("one''two\"\"three", "literal-show"),
("one''two\"\"three", "escape"),
@ -504,7 +504,7 @@ mod tests {
// A simple newline
check_names(
"one\ntwo",
vec![
&[
("one?two", "literal"),
("one\ntwo", "literal-show"),
("one\\ntwo", "escape"),
@ -521,7 +521,7 @@ mod tests {
// A control character followed by a special shell character
check_names(
"one\n&two",
vec![
&[
("one?&two", "literal"),
("one\n&two", "literal-show"),
("one\\n&two", "escape"),
@ -539,7 +539,7 @@ mod tests {
// no importance for file names.
check_names(
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
vec![
&[
("????????????????", "literal"),
(
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
@ -577,7 +577,7 @@ mod tests {
// The last 16 control characters.
check_names(
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
vec![
&[
("????????????????", "literal"),
(
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
@ -615,7 +615,7 @@ mod tests {
// DEL
check_names(
"\x7F",
vec![
&[
("?", "literal"),
("\x7F", "literal-show"),
("\\177", "escape"),
@ -637,7 +637,7 @@ mod tests {
// in other tests)
check_names(
"one?two",
vec![
&[
("one?two", "literal"),
("one?two", "literal-show"),
("one?two", "escape"),
@ -657,7 +657,7 @@ mod tests {
// Escaped in C-style, but not in Shell-style escaping
check_names(
"one\\two",
vec![
&[
("one\\two", "literal"),
("one\\two", "literal-show"),
("one\\\\two", "escape"),
@ -672,34 +672,34 @@ mod tests {
#[test]
fn test_tilde_and_hash() {
check_names("~", vec![("'~'", "shell"), ("'~'", "shell-escape")]);
check_names("~", &[("'~'", "shell"), ("'~'", "shell-escape")]);
check_names(
"~name",
vec![("'~name'", "shell"), ("'~name'", "shell-escape")],
&[("'~name'", "shell"), ("'~name'", "shell-escape")],
);
check_names(
"some~name",
vec![("some~name", "shell"), ("some~name", "shell-escape")],
&[("some~name", "shell"), ("some~name", "shell-escape")],
);
check_names("name~", vec![("name~", "shell"), ("name~", "shell-escape")]);
check_names("name~", &[("name~", "shell"), ("name~", "shell-escape")]);
check_names("#", vec![("'#'", "shell"), ("'#'", "shell-escape")]);
check_names("#", &[("'#'", "shell"), ("'#'", "shell-escape")]);
check_names(
"#name",
vec![("'#name'", "shell"), ("'#name'", "shell-escape")],
&[("'#name'", "shell"), ("'#name'", "shell-escape")],
);
check_names(
"some#name",
vec![("some#name", "shell"), ("some#name", "shell-escape")],
&[("some#name", "shell"), ("some#name", "shell-escape")],
);
check_names("name#", vec![("name#", "shell"), ("name#", "shell-escape")]);
check_names("name#", &[("name#", "shell"), ("name#", "shell-escape")]);
}
#[test]
fn test_special_chars_in_double_quotes() {
check_names(
"can'$t",
vec![
&[
("'can'\\''$t'", "shell"),
("'can'\\''$t'", "shell-always"),
("'can'\\''$t'", "shell-escape"),
@ -709,7 +709,7 @@ mod tests {
check_names(
"can'`t",
vec![
&[
("'can'\\''`t'", "shell"),
("'can'\\''`t'", "shell-always"),
("'can'\\''`t'", "shell-escape"),
@ -719,7 +719,7 @@ mod tests {
check_names(
"can'\\t",
vec![
&[
("'can'\\''\\t'", "shell"),
("'can'\\''\\t'", "shell-always"),
("'can'\\''\\t'", "shell-escape"),

View file

@ -16,7 +16,7 @@ use std::env;
use std::error::Error;
use std::fmt::Display;
use std::iter;
use std::path::{is_separator, PathBuf};
use std::path::{is_separator, Path, PathBuf};
use rand::Rng;
use tempfile::Builder;
@ -118,13 +118,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
if matches.is_present(OPT_T) {
tmpdir = env::temp_dir()
tmpdir = env::temp_dir();
}
let res = if dry_run {
dry_exec(tmpdir, prefix, rand, suffix)
} else {
exec(tmpdir, prefix, rand, suffix, make_dir)
exec(&tmpdir, prefix, rand, suffix, make_dir)
};
if suppress_file_err {
@ -249,7 +249,7 @@ pub fn dry_exec(mut tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str) ->
println_verbatim(tmpdir).map_err_context(|| "failed to print directory name".to_owned())
}
fn exec(dir: PathBuf, prefix: &str, rand: usize, suffix: &str, make_dir: bool) -> UResult<()> {
fn exec(dir: &Path, prefix: &str, rand: usize, suffix: &str, make_dir: bool) -> UResult<()> {
let context = || {
format!(
"failed to create file via template '{}{}{}'",

View file

@ -116,7 +116,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
strip_slashes: matches.is_present(OPT_STRIP_TRAILING_SLASHES),
};
exec(&files[..], behavior)
exec(&files[..], &behavior)
}
pub fn uu_app<'a>() -> App<'a> {
@ -207,7 +207,7 @@ fn determine_overwrite_mode(matches: &ArgMatches) -> OverwriteMode {
}
}
fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
fn exec(files: &[OsString], b: &Behavior) -> UResult<()> {
let paths: Vec<PathBuf> = {
let paths = files.iter().map(Path::new);
@ -222,7 +222,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
};
if let Some(ref name) = b.target_dir {
return move_files_into_dir(&paths, &PathBuf::from(name), &b);
return move_files_into_dir(&paths, &PathBuf::from(name), b);
}
match paths.len() {
/* case 0/1 are not possible thanks to clap */
@ -256,12 +256,12 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
if !source.is_dir() {
Err(MvError::DirectoryToNonDirectory(target.quote().to_string()).into())
} else {
rename(source, target, &b).map_err_context(|| {
rename(source, target, b).map_err_context(|| {
format!("cannot move {} to {}", source.quote(), target.quote())
})
}
} else {
move_files_into_dir(&[source.clone()], target, &b)
move_files_into_dir(&[source.clone()], target, b)
}
} else if target.exists() && source.is_dir() {
Err(MvError::NonDirectoryToDirectory(
@ -270,7 +270,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
)
.into())
} else {
rename(source, target, &b).map_err(|e| USimpleError::new(1, format!("{}", e)))
rename(source, target, b).map_err(|e| USimpleError::new(1, format!("{}", e)))
}
}
_ => {
@ -281,7 +281,7 @@ fn exec(files: &[OsString], b: Behavior) -> UResult<()> {
));
}
let target_dir = paths.last().unwrap();
move_files_into_dir(&paths[..paths.len() - 1], target_dir, &b)
move_files_into_dir(&paths[..paths.len() - 1], target_dir, b)
}
}
}
@ -305,7 +305,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> UR
sourcepath.quote(),
targetpath.quote()
))
)
);
}
Ok(())
}
@ -340,7 +340,7 @@ fn rename(from: &Path, to: &Path, b: &Behavior) -> io::Result<()> {
// normalize behavior between *nix and windows
if from.is_dir() {
if is_empty_dir(to) {
fs::remove_dir(to)?
fs::remove_dir(to)?;
} else {
return Err(io::Error::new(io::ErrorKind::Other, "Directory not empty"));
}

View file

@ -55,9 +55,9 @@ fn usage() -> String {
format!("{0} [OPTION]... [NUMBER]...", uucore::execution_phrase())
}
fn handle_args<'a>(args: impl Iterator<Item = &'a str>, options: NumfmtOptions) -> UResult<()> {
fn handle_args<'a>(args: impl Iterator<Item = &'a str>, options: &NumfmtOptions) -> UResult<()> {
for l in args {
match format_and_print(l, &options) {
match format_and_print(l, options) {
Ok(_) => Ok(()),
Err(e) => Err(NumfmtError::FormattingError(e.to_string())),
}?;
@ -66,7 +66,7 @@ fn handle_args<'a>(args: impl Iterator<Item = &'a str>, options: NumfmtOptions)
Ok(())
}
fn handle_buffer<R>(input: R, options: NumfmtOptions) -> UResult<()>
fn handle_buffer<R>(input: R, options: &NumfmtOptions) -> UResult<()>
where
R: BufRead,
{
@ -77,7 +77,7 @@ where
println!("{}", l);
Ok(())
}
Ok(l) => match format_and_print(&l, &options) {
Ok(l) => match format_and_print(&l, options) {
Ok(_) => Ok(()),
Err(e) => Err(NumfmtError::FormattingError(e.to_string())),
},
@ -173,11 +173,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let options = parse_options(&matches).map_err(NumfmtError::IllegalArgument)?;
let result = match matches.values_of(options::NUMBER) {
Some(values) => handle_args(values, options),
Some(values) => handle_args(values, &options),
None => {
let stdin = std::io::stdin();
let mut locked_stdin = stdin.lock();
handle_buffer(&mut locked_stdin, options)
handle_buffer(&mut locked_stdin, &options)
}
};
@ -304,7 +304,7 @@ mod tests {
#[test]
fn broken_buffer_returns_io_error() {
let mock_buffer = MockBuffer {};
let result = handle_buffer(BufReader::new(mock_buffer), get_valid_options())
let result = handle_buffer(BufReader::new(mock_buffer), &get_valid_options())
.expect_err("returned Ok after receiving IO error");
let result_debug = format!("{:?}", result);
let result_display = format!("{}", result);
@ -316,7 +316,7 @@ mod tests {
#[test]
fn non_numeric_returns_formatting_error() {
let input_value = b"135\nhello";
let result = handle_buffer(BufReader::new(&input_value[..]), get_valid_options())
let result = handle_buffer(BufReader::new(&input_value[..]), &get_valid_options())
.expect_err("returned Ok after receiving improperly formatted input");
let result_debug = format!("{:?}", result);
let result_display = format!("{}", result);
@ -331,7 +331,7 @@ mod tests {
#[test]
fn valid_input_returns_ok() {
let input_value = b"165\n100\n300\n500";
let result = handle_buffer(BufReader::new(&input_value[..]), get_valid_options());
let result = handle_buffer(BufReader::new(&input_value[..]), &get_valid_options());
assert!(result.is_ok(), "did not return Ok for valid input");
}
}

View file

@ -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) {

View file

@ -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,

View file

@ -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,

View file

@ -60,7 +60,7 @@ impl<'b> MultifileReader<'b> {
// then move on the the next file.
// This matches the behavior of the original `od`
show_error!("{}: {}", fname.maybe_quote(), e);
self.any_err = true
self.any_err = true;
}
}
}

View file

@ -121,7 +121,7 @@ struct OdOptions {
}
impl OdOptions {
fn new(matches: ArgMatches, args: Vec<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,
@ -141,7 +141,7 @@ impl OdOptions {
Err(e) => {
return Err(USimpleError::new(
1,
format_error_message(e, s, options::SKIP_BYTES),
format_error_message(&e, s, options::SKIP_BYTES),
))
}
},
@ -149,7 +149,7 @@ impl OdOptions {
let mut label: Option<usize> = None;
let parsed_input = parse_inputs(&matches)
let parsed_input = parse_inputs(matches)
.map_err(|e| USimpleError::new(1, format!("Invalid inputs: {}", e)))?;
let input_strings = match parsed_input {
CommandLineInputs::FileNames(v) => v,
@ -160,7 +160,7 @@ impl OdOptions {
}
};
let formats = parse_format_flags(&args).map_err(|e| USimpleError::new(1, e))?;
let formats = parse_format_flags(args).map_err(|e| USimpleError::new(1, e))?;
let mut line_bytes = match matches.value_of(options::WIDTH) {
None => 16,
@ -173,7 +173,7 @@ impl OdOptions {
Err(e) => {
return Err(USimpleError::new(
1,
format_error_message(e, s, options::WIDTH),
format_error_message(&e, s, options::WIDTH),
))
}
}
@ -198,7 +198,7 @@ impl OdOptions {
Err(e) => {
return Err(USimpleError::new(
1,
format_error_message(e, s, options::READ_BYTES),
format_error_message(&e, s, options::READ_BYTES),
))
}
},
@ -232,7 +232,7 @@ impl OdOptions {
}
};
Ok(OdOptions {
Ok(Self {
byte_order,
skip_bytes,
read_bytes,
@ -260,7 +260,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.clone() // Clone to reuse clap_opts to print help
.get_matches_from(args.clone());
let od_options = OdOptions::new(clap_matches, args)?;
let od_options = OdOptions::new(&clap_matches, &args)?;
let mut input_offset =
InputOffset::new(od_options.radix, od_options.skip_bytes, od_options.label);
@ -664,7 +664,7 @@ fn open_input_peek_reader(
PeekReader::new(pr)
}
fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String {
fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String {
// NOTE:
// GNU's od echos affected flag, -N or --read-bytes (-j or --skip-bytes, etc.), depending user's selection
// GNU's od does distinguish between "invalid (suffix in) argument"

View file

@ -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()
}

View file

@ -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,
}
@ -138,7 +135,7 @@ pub fn parse_format_flags(args: &[String]) -> Result<Vec<ParsedFormatterItemInfo
} else {
// not every option is a format
if let Some(r) = od_argument_traditional_format(c) {
formats.push(ParsedFormatterItemInfo::new(r, false))
formats.push(ParsedFormatterItemInfo::new(r, false));
}
}
}

View file

@ -46,7 +46,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result<CommandLineInputs,
let mut input_strings = matches.inputs();
if matches.opts_present(&["traditional"]) {
return parse_inputs_traditional(input_strings);
return parse_inputs_traditional(&input_strings);
}
// test if command line contains: [file] <offset>
@ -91,7 +91,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result<CommandLineInputs,
///
/// normally returns CommandLineInputs::FileAndOffset, but if no offset is found,
/// it returns CommandLineInputs::FileNames (also to differentiate from the offset == 0)
pub fn parse_inputs_traditional(input_strings: Vec<&str>) -> Result<CommandLineInputs, String> {
pub fn parse_inputs_traditional(input_strings: &[&str]) -> Result<CommandLineInputs, String> {
match input_strings.len() {
0 => Ok(CommandLineInputs::FileNames(vec!["-".to_string()])),
1 => {

View file

@ -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 }
}
}

View file

@ -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(),
}

View file

@ -39,7 +39,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
let serial = matches.is_present(options::SERIAL);
let delimiters = matches.value_of(options::DELIMITER).unwrap().to_owned();
let delimiters = matches.value_of(options::DELIMITER).unwrap();
let files = matches
.values_of(options::FILE)
.unwrap()
@ -76,7 +76,7 @@ pub fn uu_app<'a>() -> App<'a> {
)
}
fn paste(filenames: Vec<String>, serial: bool, delimiters: String) -> UResult<()> {
fn paste(filenames: Vec<String>, serial: bool, delimiters: &str) -> UResult<()> {
let mut files = vec![];
for name in filenames {
let file = if name == "-" {
@ -146,7 +146,7 @@ fn paste(filenames: Vec<String>, serial: bool, delimiters: String) -> UResult<()
// Unescape all special characters
// TODO: this will need work to conform to GNU implementation
fn unescape(s: String) -> String {
fn unescape(s: &str) -> String {
s.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\\\", "\\")

View file

@ -132,7 +132,7 @@ fn check_basic(path: &[String]) -> bool {
// path length
if total_len > POSIX_PATH_MAX {
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"limit {} exceeded by length {} of file name {}",
POSIX_PATH_MAX,
total_len,
@ -140,7 +140,7 @@ fn check_basic(path: &[String]) -> bool {
);
return false;
} else if total_len == 0 {
writeln!(&mut std::io::stderr(), "empty file name");
writeln!(std::io::stderr(), "empty file name");
return false;
}
// components: character portability and length
@ -148,7 +148,7 @@ fn check_basic(path: &[String]) -> bool {
let component_len = p.len();
if component_len > POSIX_NAME_MAX {
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"limit {} exceeded by length {} of file name component {}",
POSIX_NAME_MAX,
component_len,
@ -170,7 +170,7 @@ fn check_extra(path: &[String]) -> bool {
for p in path {
if p.starts_with('-') {
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"leading hyphen in file name component {}",
p.quote()
);
@ -179,7 +179,7 @@ fn check_extra(path: &[String]) -> bool {
}
// path length
if path.join("/").is_empty() {
writeln!(&mut std::io::stderr(), "empty file name");
writeln!(std::io::stderr(), "empty file name");
return false;
}
true
@ -192,7 +192,7 @@ fn check_default(path: &[String]) -> bool {
// path length
if total_len > libc::PATH_MAX as usize {
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"limit {} exceeded by length {} of file name {}",
libc::PATH_MAX,
total_len,
@ -205,7 +205,7 @@ fn check_default(path: &[String]) -> bool {
let component_len = p.len();
if component_len > libc::FILENAME_MAX as usize {
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"limit {} exceeded by length {} of file name component {}",
libc::FILENAME_MAX,
component_len,
@ -227,7 +227,7 @@ fn check_searchable(path: &str) -> bool {
if e.kind() == ErrorKind::NotFound {
true
} else {
writeln!(&mut std::io::stderr(), "{}", e);
writeln!(std::io::stderr(), "{}", e);
false
}
}
@ -241,7 +241,7 @@ fn check_portable_chars(path_segment: &str) -> bool {
if !VALID_CHARS.contains(ch) {
let invalid = path_segment[i..].chars().next().unwrap();
writeln!(
&mut std::io::stderr(),
std::io::stderr(),
"nonportable character '{}' in file name component {}",
invalid,
path_segment.quote()

View file

@ -210,9 +210,9 @@ impl Capitalize for str {
self.char_indices()
.fold(String::with_capacity(self.len()), |mut acc, x| {
if x.0 != 0 {
acc.push(x.1)
acc.push(x.1);
} else {
acc.push(x.1.to_ascii_uppercase())
acc.push(x.1.to_ascii_uppercase());
}
acc
})
@ -275,7 +275,7 @@ impl Pinky {
if let Some(n) = gecos.find(',') {
gecos.truncate(n + 1);
}
print!(" {:<19.19}", gecos.replace("&", &pw.name.capitalize()));
print!(" {:<19.19}", gecos.replace('&', &pw.name.capitalize()));
} else {
print!(" {:19}", " ???");
}
@ -324,12 +324,10 @@ impl Pinky {
self.print_heading();
}
for ut in Utmpx::iter_all_records() {
if ut.is_user_process() {
if self.names.is_empty() {
self.print_entry(&ut)?
} else if self.names.iter().any(|n| n.as_str() == ut.user()) {
self.print_entry(&ut)?;
}
if ut.is_user_process()
&& (self.names.is_empty() || self.names.iter().any(|n| n.as_str() == ut.user()))
{
self.print_entry(&ut)?;
}
}
Ok(())
@ -339,7 +337,7 @@ impl Pinky {
for u in &self.names {
print!("Login name: {:<28}In real life: ", u);
if let Ok(pw) = Passwd::locate(u.as_str()) {
println!(" {}", pw.user_info.replace("&", &pw.name.capitalize()));
println!(" {}", pw.user_info.replace('&', &pw.name.capitalize()));
if self.include_home_and_shell {
print!("Directory: {:<29}", pw.user_dir);
println!("Shell: {}", pw.user_shell);

View file

@ -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())
}
}
@ -409,11 +409,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
};
for file_group in file_groups {
let result_options = build_options(&matches, &file_group, args.join(" "));
let result_options = build_options(&matches, &file_group, &args.join(" "));
let options = match result_options {
Ok(options) => options,
Err(err) => {
print_error(&matches, err);
print_error(&matches, &err);
return Err(1.into());
}
};
@ -426,7 +426,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let status = match cmd_result {
Err(error) => {
print_error(&matches, error);
print_error(&matches, &error);
1
}
_ => 0,
@ -465,7 +465,7 @@ fn recreate_arguments(args: &[String]) -> Vec<String> {
.collect()
}
fn print_error(matches: &Matches, err: PrError) {
fn print_error(matches: &Matches, err: &PrError) {
if !matches.opt_present(options::SUPPRESS_PRINTING_ERROR) {
eprintln!("{}", err);
}
@ -531,7 +531,7 @@ fn parse_usize(matches: &Matches, opt: &str) -> Option<Result<usize, PrError>> {
fn build_options(
matches: &Matches,
paths: &[String],
free_args: String,
free_args: &str,
) -> Result<OutputOptions, PrError> {
let form_feed_used = matches.opt_present(options::FORM_FEED_OPTION)
|| matches.opt_present(options::FORM_FEED_OPTION_SMALL);
@ -617,7 +617,7 @@ fn build_options(
// +page option is less priority than --pages
let page_plus_re = Regex::new(r"\s*\+(\d+:*\d*)\s*").unwrap();
let start_page_in_plus_option = match page_plus_re.captures(&free_args).map(|i| {
let start_page_in_plus_option = match page_plus_re.captures(free_args).map(|i| {
let unparsed_num = i.get(1).unwrap().as_str().trim();
let x: Vec<_> = unparsed_num.split(':').collect();
x[0].to_string().parse::<usize>().map_err(|_e| {
@ -629,7 +629,7 @@ fn build_options(
};
let end_page_in_plus_option = match page_plus_re
.captures(&free_args)
.captures(free_args)
.map(|i| i.get(1).unwrap().as_str().trim())
.filter(|i| i.contains(':'))
.map(|unparsed_num| {
@ -747,7 +747,7 @@ fn build_options(
let re_col = Regex::new(r"\s*-(\d+)\s*").unwrap();
let start_column_option = match re_col.captures(&free_args).map(|i| {
let start_column_option = match re_col.captures(free_args).map(|i| {
let unparsed_num = i.get(1).unwrap().as_str().trim();
unparsed_num.parse::<usize>().map_err(|_e| {
PrError::EncounteredErrors(format!("invalid {} argument {}", "-", unparsed_num.quote()))
@ -1007,7 +1007,7 @@ fn mpr(paths: &[String], options: &OutputOptions) -> Result<i32, PrError> {
let mut lines = Vec::new();
let mut page_counter = start_page;
for (_key, file_line_group) in file_line_groups.into_iter() {
for (_key, file_line_group) in &file_line_groups {
for file_line in file_line_group {
if let Err(e) = file_line.line_content {
return Err(e.into());

View file

@ -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,
@ -275,7 +275,7 @@ fn read_input(input_files: &[String], config: &Config) -> std::io::Result<FileMa
offset,
},
);
offset += size
offset += size;
}
Ok(file_map)
}

View file

@ -138,7 +138,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
}
if remove(files, options) {
if remove(&files, &options) {
return Err(1.into());
}
}
@ -236,19 +236,19 @@ pub fn uu_app<'a>() -> App<'a> {
}
// TODO: implement one-file-system (this may get partially implemented in walkdir)
fn remove(files: Vec<String>, options: Options) -> bool {
fn remove(files: &[String], options: &Options) -> bool {
let mut had_err = false;
for filename in &files {
for filename in files {
let file = Path::new(filename);
had_err = match file.symlink_metadata() {
Ok(metadata) => {
if metadata.is_dir() {
handle_dir(file, &options)
handle_dir(file, options)
} else if is_symlink_dir(&metadata) {
remove_dir(file, &options)
remove_dir(file, options)
} else {
remove_file(file, &options)
remove_file(file, options)
}
}
Err(_e) => {

View file

@ -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 }
}
}

View file

@ -73,7 +73,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
CommandLineMode::Print => print_current_context().map_err(|e| RunconError::new(e).into()),
CommandLineMode::PlainContext { context, command } => {
get_plain_context(context)
.and_then(set_next_exec_context)
.and_then(|ctx| set_next_exec_context(&ctx))
.map_err(RunconError::new)?;
// On successful execution, the following call never returns,
// and this process image is replaced.
@ -97,7 +97,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
range.as_deref(),
command,
)
.and_then(set_next_exec_context)
.and_then(|ctx| set_next_exec_context(&ctx))
.map_err(RunconError::new)?;
// On successful execution, the following call never returns,
// and this process image is replaced.
@ -277,7 +277,7 @@ fn print_current_context() -> Result<()> {
Ok(())
}
fn set_next_exec_context(context: OpaqueSecurityContext) -> Result<()> {
fn set_next_exec_context(context: &OpaqueSecurityContext) -> Result<()> {
let c_context = context
.to_c_string()
.map_err(|r| Error::from_selinux("Creating new context", r))?;

View file

@ -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 {

View file

@ -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 {

View file

@ -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).

View file

@ -115,8 +115,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let last = last.round_towards(&first);
print_seq_integers(
(first, increment, last),
options.separator,
options.terminator,
&options.separator,
&options.terminator,
options.widths,
padding,
options.format,
@ -129,8 +129,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
last.into_extended_big_decimal(),
),
largest_dec,
options.separator,
options.terminator,
&options.separator,
&options.terminator,
options.widths,
padding,
options.format,
@ -265,8 +265,8 @@ fn write_value_int(
fn print_seq(
range: RangeFloat,
largest_dec: usize,
separator: String,
terminator: String,
separator: &str,
terminator: &str,
pad: bool,
padding: usize,
format: Option<&str>,
@ -336,8 +336,8 @@ fn print_seq(
/// numbers). Only set this to `true` if `first` is actually zero.
fn print_seq_integers(
range: RangeInt,
separator: String,
terminator: String,
separator: &str,
terminator: &str,
pad: bool,
padding: usize,
format: Option<&str>,

View file

@ -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),
@ -96,7 +96,7 @@ impl Iterator for FilenameGenerator {
}
if name_charset_indices[0] == NAME_CHARSET.len() - 1 {
self.exhausted.set(true)
self.exhausted.set(true);
}
// Now increment the least significant index
for i in (0..self.name_len).rev() {
@ -478,7 +478,7 @@ fn wipe_file(
if n_passes <= 3 {
// Only random passes if n_passes <= 3
for _ in 0..n_passes {
pass_sequence.push(PassType::Random)
pass_sequence.push(PassType::Random);
}
}
// First fill it with Patterns, shuffle it, then evenly distribute Random

View file

@ -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 }
}
}
@ -57,7 +57,7 @@ impl<R: Read> RngCore for ReadRng<R> {
panic!(
"reading random bytes from Read implementation failed; error: {}",
err
)
);
});
}

View file

@ -38,8 +38,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().override_usage(&usage[..]).get_matches_from(args);
if let Some(values) = matches.values_of(options::NUMBER) {
let numbers = values.collect();
return sleep(numbers);
let numbers = values.collect::<Vec<_>>();
return sleep(&numbers);
}
Ok(())
@ -61,7 +61,7 @@ pub fn uu_app<'a>() -> App<'a> {
)
}
fn sleep(args: Vec<&str>) -> UResult<()> {
fn sleep(args: &[&str]) -> UResult<()> {
let sleep_dur =
args.iter().try_fold(
Duration::new(0, 0),

View file

@ -40,7 +40,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
let (loaded_sender, loaded_receiver) = sync_channel(2);
thread::spawn({
let settings = settings.clone();
move || reader(file, recycled_receiver, loaded_sender, &settings)
move || reader(file, &recycled_receiver, &loaded_sender, &settings)
});
for _ in 0..2 {
let _ = recycled_sender.send(RecycledChunk::new(if settings.buffer_size < 100 * 1024 {
@ -102,14 +102,14 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> {
/// The function running on the reader thread.
fn reader(
mut file: Box<dyn Read + Send>,
receiver: Receiver<RecycledChunk>,
sender: SyncSender<Chunk>,
receiver: &Receiver<RecycledChunk>,
sender: &SyncSender<Chunk>,
settings: &GlobalSettings,
) -> UResult<()> {
let mut carry_over = vec![];
for recycled_chunk in receiver.iter() {
let should_continue = chunks::read(
&sender,
sender,
recycled_chunk,
None,
&mut carry_over,

View file

@ -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(),

View file

@ -50,13 +50,13 @@ pub fn ext_sort(
let (recycled_sender, recycled_receiver) = std::sync::mpsc::sync_channel(1);
thread::spawn({
let settings = settings.clone();
move || sorter(recycled_receiver, sorted_sender, settings)
move || sorter(&recycled_receiver, &sorted_sender, &settings)
});
if settings.compress_prog.is_some() {
reader_writer::<_, WriteableCompressedTmpFile>(
files,
settings,
sorted_receiver,
&sorted_receiver,
recycled_sender,
output,
tmp_dir,
@ -65,7 +65,7 @@ pub fn ext_sort(
reader_writer::<_, WriteablePlainTmpFile>(
files,
settings,
sorted_receiver,
&sorted_receiver,
recycled_sender,
output,
tmp_dir,
@ -79,7 +79,7 @@ fn reader_writer<
>(
files: F,
settings: &GlobalSettings,
receiver: Receiver<Chunk>,
receiver: &Receiver<Chunk>,
sender: SyncSender<Chunk>,
output: Output,
tmp_dir: &mut TmpDirWrapper,
@ -156,10 +156,10 @@ fn reader_writer<
}
/// The function that is executed on the sorter thread.
fn sorter(receiver: Receiver<Chunk>, sender: SyncSender<Chunk>, settings: GlobalSettings) {
fn sorter(receiver: &Receiver<Chunk>, sender: &SyncSender<Chunk>, settings: &GlobalSettings) {
while let Ok(mut payload) = receiver.recv() {
payload.with_contents_mut(|contents| {
sort_by(&mut contents.lines, &settings, &contents.line_data)
sort_by(&mut contents.lines, settings, &contents.line_data);
});
if sender.send(payload).is_err() {
// The receiver has gone away, likely because the other thread hit an error.
@ -187,7 +187,7 @@ fn read_write_loop<I: WriteableTmpFile>(
separator: u8,
buffer_size: usize,
settings: &GlobalSettings,
receiver: Receiver<Chunk>,
receiver: &Receiver<Chunk>,
sender: SyncSender<Chunk>,
) -> UResult<ReadResult<I>> {
let mut file = files.next().unwrap()?;

View file

@ -50,7 +50,7 @@ fn replace_output_file_in_input_files(
std::fs::copy(file_path, &copy_path)
.map_err(|error| SortError::OpenTmpFileFailed { error })?;
*file = copy_path.clone().into_os_string();
copy = Some(copy_path)
copy = Some(copy_path);
}
}
}
@ -166,7 +166,7 @@ fn merge_without_limit<M: MergeInput + 'static, F: Iterator<Item = UResult<M>>>(
let settings = settings.clone();
move || {
reader(
request_receiver,
&request_receiver,
&mut reader_files,
&settings,
if settings.zero_terminated {
@ -187,7 +187,7 @@ fn merge_without_limit<M: MergeInput + 'static, F: Iterator<Item = UResult<M>>>(
file_number,
line_idx: 0,
receiver,
})
});
}
}
@ -210,7 +210,7 @@ struct ReaderFile<M: MergeInput> {
/// The function running on the reader thread.
fn reader(
recycled_receiver: Receiver<(usize, RecycledChunk)>,
recycled_receiver: &Receiver<(usize, RecycledChunk)>,
files: &mut [Option<ReaderFile<impl MergeInput>>],
settings: &GlobalSettings,
separator: u8,
@ -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,

View file

@ -52,7 +52,7 @@ impl NumInfo {
/// an empty range (idx..idx) is returned so that idx is the char after the last zero.
/// If the input is not a number (which has to be treated as zero), the returned empty range
/// will be 0..0.
pub fn parse(num: &str, parse_settings: NumInfoParseSettings) -> (Self, Range<usize>) {
pub fn parse(num: &str, parse_settings: &NumInfoParseSettings) -> (Self, Range<usize>) {
let mut exponent = -1;
let mut had_decimal_pt = false;
let mut had_digit = false;
@ -80,17 +80,17 @@ impl NumInfo {
continue;
}
if Self::is_invalid_char(char, &mut had_decimal_pt, &parse_settings) {
if Self::is_invalid_char(char, &mut had_decimal_pt, parse_settings) {
return if let Some(start) = start {
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,
},
@ -270,7 +270,7 @@ mod tests {
fn parses_exp() {
let n = "1";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 0,
@ -281,7 +281,7 @@ mod tests {
);
let n = "100";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 2,
@ -294,7 +294,7 @@ mod tests {
assert_eq!(
NumInfo::parse(
n,
NumInfoParseSettings {
&NumInfoParseSettings {
thousands_separator: Some(','),
..Default::default()
}
@ -309,7 +309,7 @@ mod tests {
);
let n = "1,000";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 0,
@ -320,7 +320,7 @@ mod tests {
);
let n = "1000.00";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 3,
@ -334,7 +334,7 @@ mod tests {
fn parses_negative_exp() {
let n = "0.00005";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: -5,
@ -345,7 +345,7 @@ mod tests {
);
let n = "00000.00005";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: -5,
@ -360,7 +360,7 @@ mod tests {
fn parses_sign() {
let n = "5";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 0,
@ -371,7 +371,7 @@ mod tests {
);
let n = "-5";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 0,
@ -382,7 +382,7 @@ mod tests {
);
let n = " -5";
assert_eq!(
NumInfo::parse(n, Default::default()),
NumInfo::parse(n, &Default::default()),
(
NumInfo {
exponent: 0,
@ -394,8 +394,8 @@ mod tests {
}
fn test_helper(a: &str, b: &str, expected: Ordering) {
let (a_info, a_range) = NumInfo::parse(a, Default::default());
let (b_info, b_range) = NumInfo::parse(b, Default::default());
let (a_info, a_range) = NumInfo::parse(a, &Default::default());
let (b_info, b_range) = NumInfo::parse(b, &Default::default());
let ordering = numeric_str_cmp(
(&a[a_range.to_owned()], &a_info),
(&b[b_range.to_owned()], &b_info),
@ -470,7 +470,7 @@ mod tests {
}
#[test]
fn single_minus() {
let info = NumInfo::parse("-", Default::default());
let info = NumInfo::parse("-", &Default::default());
assert_eq!(
info,
(
@ -486,7 +486,7 @@ mod tests {
fn invalid_with_unit() {
let info = NumInfo::parse(
"-K",
NumInfoParseSettings {
&NumInfoParseSettings {
accept_si_units: true,
..Default::default()
},

View file

@ -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(),
}
}
}
@ -535,7 +530,7 @@ impl<'a> Line<'a> {
}
Selection::Str(str) => {
if selector.needs_selection {
line_data.selections.push(str)
line_data.selections.push(str);
}
}
}
@ -571,14 +566,14 @@ impl<'a> Line<'a> {
let mut fields = vec![];
tokenize(self.line, settings.separator, &mut fields);
for selector in settings.selectors.iter() {
for selector in &settings.selectors {
let mut selection = selector.get_range(self.line, Some(&fields));
match selector.settings.mode {
SortMode::Numeric | SortMode::HumanNumeric => {
// find out which range is used for numeric comparisons
let (_, num_range) = NumInfo::parse(
&self.line[selection.clone()],
NumInfoParseSettings {
&NumInfoParseSettings {
accept_si_units: selector.settings.mode == SortMode::HumanNumeric,
..Default::default()
},
@ -701,9 +696,9 @@ impl<'a> Line<'a> {
fn tokenize(line: &str, separator: Option<char>, token_buffer: &mut Vec<Field>) {
assert!(token_buffer.is_empty());
if let Some(separator) = separator {
tokenize_with_separator(line, separator, token_buffer)
tokenize_with_separator(line, separator, token_buffer);
} else {
tokenize_default(line, token_buffer)
tokenize_default(line, token_buffer);
}
}
@ -784,7 +779,7 @@ impl KeyPosition {
impl Default for KeyPosition {
fn default() -> Self {
KeyPosition {
Self {
field: 1,
char: 1,
ignore_blanks: false,
@ -927,7 +922,7 @@ impl FieldSelector {
// Parse NumInfo for this number.
let (info, num_range) = NumInfo::parse(
range,
NumInfoParseSettings {
&NumInfoParseSettings {
accept_si_units: self.settings.mode == SortMode::HumanNumeric,
..Default::default()
},
@ -1156,7 +1151,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.value_of(options::BUF_SIZE)
.map_or(Ok(DEFAULT_BUF_SIZE), |s| {
GlobalSettings::parse_byte_count(s).map_err(|e| {
USimpleError::new(2, format_error_message(e, s, options::BUF_SIZE))
USimpleError::new(2, format_error_message(&e, s, options::BUF_SIZE))
})
})?;
@ -1232,7 +1227,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
),
));
}
settings.separator = Some(separator.chars().next().unwrap())
settings.separator = Some(separator.chars().next().unwrap());
}
if let Some(values) = matches.values_of(options::KEY) {
@ -1524,9 +1519,9 @@ fn exec(
fn sort_by<'a>(unsorted: &mut Vec<Line<'a>>, settings: &GlobalSettings, line_data: &LineData<'a>) {
if settings.stable || settings.unique {
unsorted.par_sort_by(|a, b| compare_by(a, b, settings, line_data, line_data))
unsorted.par_sort_by(|a, b| compare_by(a, b, settings, line_data, line_data));
} else {
unsorted.par_sort_unstable_by(|a, b| compare_by(a, b, settings, line_data, line_data))
unsorted.par_sort_unstable_by(|a, b| compare_by(a, b, settings, line_data, line_data));
}
}
@ -1829,7 +1824,7 @@ fn open(path: impl AsRef<OsStr>) -> UResult<Box<dyn Read + Send>> {
}
}
fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String {
fn format_error_message(error: &ParseSizeError, s: &str, option: &str) -> String {
// NOTE:
// GNU's sort echos affected flag, -S or --buffer-size, depending user's selection
// GNU's sort does distinguish between "invalid (suffix in) argument"

View file

@ -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,
}
@ -55,7 +55,7 @@ impl Drop for WithEnvVarSet {
if let Ok(ref prev_value) = self._previous_var_value {
env::set_var(&self._previous_var_key, &prev_value);
} else {
env::remove_var(&self._previous_var_key)
env::remove_var(&self._previous_var_key);
}
}
}
@ -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 }
}
}

View file

@ -62,7 +62,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.after_help(&long_usage[..])
.get_matches_from(args);
let settings = Settings::from(matches)?;
split(settings)
split(&settings)
}
pub fn uu_app<'a>() -> App<'a> {
@ -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(),
}
}
@ -436,7 +436,7 @@ where
.map_err_context(|| "I/O error".to_string())
}
fn split(settings: Settings) -> UResult<()> {
fn split(settings: &Settings) -> UResult<()> {
let mut reader = BufReader::new(if settings.input == "-" {
Box::new(stdin()) as Box<dyn Read>
} else {
@ -450,7 +450,7 @@ fn split(settings: Settings) -> UResult<()> {
});
if let Strategy::Number(num_chunks) = settings.strategy {
return split_into_n_chunks_by_byte(&settings, &mut reader, num_chunks);
return split_into_n_chunks_by_byte(settings, &mut reader, num_chunks);
}
let mut splitter: Box<dyn Splitter> = match settings.strategy {

View file

@ -219,7 +219,7 @@ pub struct Stater {
}
#[allow(clippy::cognitive_complexity)]
fn print_it(arg: &str, output_type: OutputType, flag: u8, width: usize, precision: i32) {
fn print_it(arg: &str, output_type: &OutputType, flag: u8, width: usize, precision: i32) {
// If the precision is given as just '.', the precision is taken to be zero.
// A negative precision is taken as if the precision were omitted.
// This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions,
@ -250,7 +250,7 @@ fn print_it(arg: &str, output_type: OutputType, flag: u8, width: usize, precisio
// By default, a sign is used only for negative numbers.
// A + overrides a space if both are used.
if output_type == OutputType::Unknown {
if output_type == &OutputType::Unknown {
return print!("?");
}
@ -406,7 +406,7 @@ impl Stater {
flag,
precision,
format: chars[i],
})
});
}
'\\' => {
if !use_printf {
@ -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(),
@ -743,7 +743,7 @@ impl Stater {
output_type = OutputType::Unknown;
}
}
print_it(&arg, output_type, flag, width, precision);
print_it(&arg, &output_type, flag, width, precision);
}
}
}
@ -836,7 +836,7 @@ impl Stater {
}
}
print_it(&arg, output_type, flag, width, precision);
print_it(&arg, &output_type, flag, width, precision);
}
}
}
@ -957,7 +957,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.after_help(&long_usage[..])
.get_matches_from(args);
let stater = Stater::new(matches)?;
let stater = Stater::new(&matches)?;
let exit_status = stater.exec();
if exit_status == 0 {
Ok(())

View file

@ -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)?,
@ -127,7 +127,7 @@ fn check_option(matches: &ArgMatches, name: &str) -> Result<BufferType, ProgramO
}
}
fn set_command_env(command: &mut Command, buffer_name: &str, buffer_type: BufferType) {
fn set_command_env(command: &mut Command, buffer_name: &str, buffer_type: &BufferType) {
match buffer_type {
BufferType::Size(m) => {
command.env(buffer_name, m.to_string());
@ -167,9 +167,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let mut tmp_dir = tempdir().unwrap();
let (preload_env, libstdbuf) = get_preload_env(&mut tmp_dir).map_err_context(String::new)?;
command.env(preload_env, libstdbuf);
set_command_env(&mut command, "_STDBUF_I", options.stdin);
set_command_env(&mut command, "_STDBUF_O", options.stdout);
set_command_env(&mut command, "_STDBUF_E", options.stderr);
set_command_env(&mut command, "_STDBUF_I", &options.stdin);
set_command_env(&mut command, "_STDBUF_O", &options.stdout);
set_command_env(&mut command, "_STDBUF_E", &options.stderr);
command.args(command_params);
let mut process = command

View file

@ -57,7 +57,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
None => vec!["-"],
};
tac(files, before, regex, separator)
tac(&files, before, regex, separator)
}
pub fn uu_app<'a>() -> App<'a> {
@ -223,7 +223,7 @@ fn buffer_tac(data: &[u8], before: bool, separator: &str) -> std::io::Result<()>
Ok(())
}
fn tac(filenames: Vec<&str>, before: bool, regex: bool, separator: &str) -> UResult<()> {
fn tac(filenames: &[&str], before: bool, regex: bool, separator: &str) -> UResult<()> {
// Compile the regular expression pattern if it is provided.
let maybe_pattern = if regex {
match regex::bytes::Regex::new(separator) {
@ -234,7 +234,7 @@ fn tac(filenames: Vec<&str>, before: bool, regex: bool, separator: &str) -> URes
None
};
for &filename in &filenames {
for &filename in filenames {
let mmap;
let buf;

View file

@ -42,11 +42,11 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
// this also saves us 1 heap allocation
'q' => {
quiet = true;
verbose = false
verbose = false;
}
'v' => {
verbose = true;
quiet = false
quiet = false;
}
'z' => zero_terminated = true,
'c' => multiplier = Some(1),
@ -57,20 +57,20 @@ pub fn parse_obsolete(src: &str) -> Option<Result<impl Iterator<Item = OsString>
_ => return Some(Err(ParseError::Syntax)),
}
if let Some((_, next)) = chars.next() {
c = next
c = next;
} else {
break;
}
}
let mut options = Vec::new();
if quiet {
options.push(OsString::from("-q"))
options.push(OsString::from("-q"));
}
if verbose {
options.push(OsString::from("-v"))
options.push(OsString::from("-v"));
}
if zero_terminated {
options.push(OsString::from("-z"))
options.push(OsString::from("-z"));
}
if let Some(n) = multiplier {
options.push(OsString::from("-c"));

View file

@ -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

View file

@ -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()
@ -102,7 +102,7 @@ impl Settings {
if let Some(n) = matches.value_of(options::SLEEP_INT) {
let parsed: Option<u32> = n.parse().ok();
if let Some(m) = parsed {
settings.sleep_msec = m * 1000
settings.sleep_msec = m * 1000;
}
}
}

View file

@ -53,7 +53,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.unwrap_or_default(),
};
match tee(options) {
match tee(&options) {
Ok(_) => Ok(()),
Err(_) => Err(1.into()),
}
@ -95,9 +95,9 @@ fn ignore_interrupts() -> Result<()> {
Ok(())
}
fn tee(options: Options) -> Result<()> {
fn tee(options: &Options) -> Result<()> {
if options.ignore_interrupts {
ignore_interrupts()?
ignore_interrupts()?;
}
let mut writers: Vec<NamedWriter> = options
.files

View file

@ -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![],
}

View file

@ -188,25 +188,25 @@ fn eval(stack: &mut Vec<Symbol>) -> Result<bool, String> {
let f = pop_literal!();
Ok(match op {
"-b" => path(&f, PathCondition::BlockSpecial),
"-c" => path(&f, PathCondition::CharacterSpecial),
"-d" => path(&f, PathCondition::Directory),
"-e" => path(&f, PathCondition::Exists),
"-f" => path(&f, PathCondition::Regular),
"-g" => path(&f, PathCondition::GroupIdFlag),
"-G" => path(&f, PathCondition::GroupOwns),
"-h" => path(&f, PathCondition::SymLink),
"-k" => path(&f, PathCondition::Sticky),
"-L" => path(&f, PathCondition::SymLink),
"-O" => path(&f, PathCondition::UserOwns),
"-p" => path(&f, PathCondition::Fifo),
"-r" => path(&f, PathCondition::Readable),
"-S" => path(&f, PathCondition::Socket),
"-s" => path(&f, PathCondition::NonEmpty),
"-b" => path(&f, &PathCondition::BlockSpecial),
"-c" => path(&f, &PathCondition::CharacterSpecial),
"-d" => path(&f, &PathCondition::Directory),
"-e" => path(&f, &PathCondition::Exists),
"-f" => path(&f, &PathCondition::Regular),
"-g" => path(&f, &PathCondition::GroupIdFlag),
"-G" => path(&f, &PathCondition::GroupOwns),
"-h" => path(&f, &PathCondition::SymLink),
"-k" => path(&f, &PathCondition::Sticky),
"-L" => path(&f, &PathCondition::SymLink),
"-O" => path(&f, &PathCondition::UserOwns),
"-p" => path(&f, &PathCondition::Fifo),
"-r" => path(&f, &PathCondition::Readable),
"-S" => path(&f, &PathCondition::Socket),
"-s" => path(&f, &PathCondition::NonEmpty),
"-t" => isatty(&f)?,
"-u" => path(&f, PathCondition::UserIdFlag),
"-w" => path(&f, PathCondition::Writable),
"-x" => path(&f, PathCondition::Executable),
"-u" => path(&f, &PathCondition::UserIdFlag),
"-w" => path(&f, &PathCondition::Writable),
"-x" => path(&f, &PathCondition::Executable),
_ => panic!(),
})
}
@ -283,7 +283,7 @@ enum PathCondition {
}
#[cfg(not(windows))]
fn path(path: &OsStr, condition: PathCondition) -> bool {
fn path(path: &OsStr, condition: &PathCondition) -> bool {
use std::fs::{self, Metadata};
use std::os::unix::fs::{FileTypeExt, MetadataExt};
@ -325,7 +325,7 @@ fn path(path: &OsStr, condition: PathCondition) -> bool {
}
};
let metadata = if condition == PathCondition::SymLink {
let metadata = if condition == &PathCondition::SymLink {
fs::symlink_metadata(path)
} else {
fs::metadata(path)
@ -362,7 +362,7 @@ fn path(path: &OsStr, condition: PathCondition) -> bool {
}
#[cfg(windows)]
fn path(path: &OsStr, condition: PathCondition) -> bool {
fn path(path: &OsStr, condition: &PathCondition) -> bool {
use std::fs::metadata;
let stat = match metadata(path) {

View file

@ -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,
@ -112,7 +112,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = app.get_matches_from(args);
let config = Config::from(matches);
let config = Config::from(&matches);
timeout(
&config.command,
config.duration,

View file

@ -27,11 +27,10 @@ fn parse_octal(input: &str) -> IResult<&str, char> {
)(input)
}
pub fn reduce_octal_to_char(input: String) -> String {
let result = many0(alt((parse_octal, anychar)))(input.as_str())
pub fn reduce_octal_to_char(input: &str) -> String {
many0(alt((parse_octal, anychar)))(input)
.map(|(_, r)| r)
.unwrap()
.into_iter()
.collect();
result
.collect()
}

View file

@ -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(&current) { 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(&current).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,

View file

@ -64,7 +64,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.values_of(options::SETS)
.map(|v| {
v.map(ToString::to_string)
.map(convert::reduce_octal_to_char)
.map(|input| convert::reduce_octal_to_char(&input))
.collect::<Vec<_>>()
})
.unwrap_or_default();

View file

@ -129,7 +129,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let no_create = matches.is_present(options::NO_CREATE);
let reference = matches.value_of(options::REFERENCE).map(String::from);
let size = matches.value_of(options::SIZE).map(String::from);
truncate(no_create, io_blocks, reference, size, files)
truncate(no_create, io_blocks, reference, size, &files)
}
}
@ -210,7 +210,7 @@ fn file_truncate(filename: &str, create: bool, size: usize) -> std::io::Result<(
fn truncate_reference_and_size(
rfilename: &str,
size_string: &str,
filenames: Vec<String>,
filenames: &[String],
create: bool,
) -> UResult<()> {
let mode = match parse_mode_and_size(size_string) {
@ -238,7 +238,7 @@ fn truncate_reference_and_size(
})?;
let fsize = metadata.len() as usize;
let tsize = mode.to_size(fsize);
for filename in &filenames {
for filename in filenames {
file_truncate(filename, create, tsize)
.map_err_context(|| format!("cannot open {} for writing", filename.quote()))?;
}
@ -258,7 +258,7 @@ fn truncate_reference_and_size(
/// the size of at least one file.
fn truncate_reference_file_only(
rfilename: &str,
filenames: Vec<String>,
filenames: &[String],
create: bool,
) -> UResult<()> {
let metadata = metadata(rfilename).map_err(|e| match e.kind() {
@ -272,7 +272,7 @@ fn truncate_reference_file_only(
_ => e.map_err_context(String::new),
})?;
let tsize = metadata.len() as usize;
for filename in &filenames {
for filename in filenames {
file_truncate(filename, create, tsize)
.map_err_context(|| format!("cannot open {} for writing", filename.quote()))?;
}
@ -294,13 +294,13 @@ fn truncate_reference_file_only(
///
/// If the any file could not be opened, or there was a problem setting
/// the size of at least one file.
fn truncate_size_only(size_string: &str, filenames: Vec<String>, create: bool) -> UResult<()> {
fn truncate_size_only(size_string: &str, filenames: &[String], create: bool) -> UResult<()> {
let mode = parse_mode_and_size(size_string)
.map_err(|e| USimpleError::new(1, format!("Invalid number: {}", e)))?;
if let TruncateMode::RoundDown(0) | TruncateMode::RoundUp(0) = mode {
return Err(USimpleError::new(1, "division by zero"));
}
for filename in &filenames {
for filename in filenames {
let fsize = match metadata(filename) {
Ok(m) => m.len(),
Err(_) => 0,
@ -324,7 +324,7 @@ fn truncate(
_: bool,
reference: Option<String>,
size: Option<String>,
filenames: Vec<String>,
filenames: &[String],
) -> UResult<()> {
let create = !no_create;
// There are four possibilities

View file

@ -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 {

View file

@ -27,7 +27,7 @@ static SUMMARY: &str = "Convert blanks in each FILE to tabs, writing to standard
const DEFAULT_TABSTOP: usize = 8;
fn tabstops_parse(s: String) -> Vec<usize> {
fn tabstops_parse(s: &str) -> Vec<usize> {
let words = s.split(',');
let nums = words
@ -67,10 +67,10 @@ 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.to_string()),
Some(s) => tabstops_parse(s),
};
let aflag = (matches.is_present(options::ALL) || matches.is_present(options::TABS))
@ -82,7 +82,7 @@ impl Options {
None => vec!["-".to_owned()],
};
Options {
Self {
files,
tabstops,
aflag,
@ -99,7 +99,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().get_matches_from(args);
unexpand(Options::new(matches)).map_err_context(String::new)
unexpand(&Options::new(&matches)).map_err_context(String::new)
}
pub fn uu_app<'a>() -> App<'a> {
@ -138,7 +138,7 @@ pub fn uu_app<'a>() -> App<'a> {
.help("interpret input file as 8-bit ASCII rather than UTF-8"))
}
fn open(path: String) -> BufReader<Box<dyn Read + 'static>> {
fn open(path: &str) -> BufReader<Box<dyn Read + 'static>> {
let file_buf;
if path == "-" {
BufReader::new(Box::new(stdin()) as Box<dyn Read>)
@ -243,13 +243,13 @@ fn next_char_info(uflag: bool, buf: &[u8], byte: usize) -> (CharType, usize, usi
(ctype, cwidth, nbytes)
}
fn unexpand(options: Options) -> std::io::Result<()> {
fn unexpand(options: &Options) -> std::io::Result<()> {
let mut output = BufWriter::new(stdout());
let ts = &options.tabstops[..];
let mut buf = Vec::new();
let lastcol = if ts.len() > 1 { *ts.last().unwrap() } else { 0 };
for file in options.files.into_iter() {
for file in &options.files {
let mut fh = open(file);
while match fh.read_until(b'\n', &mut buf) {

View file

@ -294,8 +294,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
zero_terminated: matches.is_present(options::ZERO_TERMINATED),
};
uniq.print_uniq(
&mut open_input_file(in_file_name)?,
&mut open_output_file(out_file_name)?,
&mut open_input_file(&in_file_name)?,
&mut open_output_file(&out_file_name)?,
)
}
@ -409,11 +409,11 @@ fn get_delimiter(matches: &ArgMatches) -> Delimiters {
}
}
fn open_input_file(in_file_name: String) -> UResult<BufReader<Box<dyn Read + 'static>>> {
fn open_input_file(in_file_name: &str) -> UResult<BufReader<Box<dyn Read + 'static>>> {
let in_file = if in_file_name == "-" {
Box::new(stdin()) as Box<dyn Read>
} else {
let path = Path::new(&in_file_name[..]);
let path = Path::new(in_file_name);
let in_file = File::open(&path)
.map_err_context(|| format!("Could not open {}", in_file_name.maybe_quote()))?;
Box::new(in_file) as Box<dyn Read>
@ -421,11 +421,11 @@ fn open_input_file(in_file_name: String) -> UResult<BufReader<Box<dyn Read + 'st
Ok(BufReader::new(in_file))
}
fn open_output_file(out_file_name: String) -> UResult<BufWriter<Box<dyn Write + 'static>>> {
fn open_output_file(out_file_name: &str) -> UResult<BufWriter<Box<dyn Write + 'static>>> {
let out_file = if out_file_name == "-" {
Box::new(stdout()) as Box<dyn Write>
} else {
let path = Path::new(&out_file_name[..]);
let path = Path::new(out_file_name);
let out_file = File::create(&path)
.map_err_context(|| format!("Could not create {}", out_file_name.maybe_quote()))?;
Box::new(out_file) as Box<dyn Write>

View file

@ -178,7 +178,7 @@ fn print_uptime(upsecs: i64) {
match updays.cmp(&1) {
std::cmp::Ordering::Equal => print!("up {:1} day, {:2}:{:02}, ", updays, uphours, upmins),
std::cmp::Ordering::Greater => {
print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins)
print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins);
}
_ => print!("up {:2}:{:02}, ", uphours, upmins),
};

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