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

fix a low-count lints in all crates

Running this command showed a list of all lints across all crates:

```shell
cargo clippy --all-targets --workspace --message-format=json --quiet | jq -r '.message.code.code | select(. != null and startswith("clippy::"))' | sort | uniq -c | sort -h -r
```

This resulted in a list that I added to the `[workspace.lints.clippy]` in the root Cargo.toml. Afterwards, I commented out a few simpler lints. Subsequentely, I will go through this list, trying to address items in smaller batches.
This commit is contained in:
Yuri Astrakhan 2025-04-09 14:21:06 -04:00
parent d37f500bd3
commit 6e22b69e9c
31 changed files with 145 additions and 85 deletions

View file

@ -1,7 +1,7 @@
# coreutils (uutils)
# * see the repository LICENSE, README, and CONTRIBUTING files for more information
# spell-checker:ignore (libs) bigdecimal datetime serde bincode fundu gethostid kqueue libselinux mangen memmap procfs uuhelp
# spell-checker:ignore (libs) bigdecimal datetime serde bincode fundu gethostid kqueue libselinux mangen memmap procfs uuhelp startswith constness expl
[package]
name = "coreutils"
@ -599,13 +599,74 @@ pedantic = { level = "deny", priority = -1 }
unused_qualifications = "warn"
[workspace.lints.clippy]
all = { level = "deny", priority = -1 }
#cargo = { level = "warn", priority = -1 }
cognitive_complexity = "warn"
default_trait_access = "warn"
implicit_clone = "warn"
manual_string_new = "warn"
match_bool = "warn"
range-plus-one = "warn"
redundant-clone = "warn"
ref_option = "warn"
# The counts were generated with this command:
# cargo clippy --all-targets --workspace --message-format=json --quiet \
# | jq -r '.message.code.code | select(. != null and startswith("clippy::"))' \
# | sort | uniq -c | sort -h -r
#
# TODO:
# remove large_stack_arrays when https://github.com/rust-lang/rust-clippy/issues/13774 is fixed
#
all = { level = "warn", priority = -1 }
cargo = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }
cargo_common_metadata = "allow" # 3240
multiple_crate_versions = "allow" # 2314
missing_errors_doc = "allow" # 1504
missing_panics_doc = "allow" # 946
must_use_candidate = "allow" # 322
doc_markdown = "allow" # 267
match_same_arms = "allow" # 212
unnecessary_semicolon = "allow" # 156
redundant_closure_for_method_calls = "allow" # 133
cast_possible_truncation = "allow" # 118
too_many_lines = "allow" # 81
cast_possible_wrap = "allow" # 76
trivially_copy_pass_by_ref = "allow" # 74
cast_sign_loss = "allow" # 70
struct_excessive_bools = "allow" # 68
single_match_else = "allow" # 66
redundant_else = "allow" # 58
map_unwrap_or = "allow" # 54
cast_precision_loss = "allow" # 52
unnested_or_patterns = "allow" # 40
inefficient_to_string = "allow" # 38
unnecessary_wraps = "allow" # 37
cast_lossless = "allow" # 33
ignored_unit_patterns = "allow" # 29
needless_continue = "allow" # 28
items_after_statements = "allow" # 22
similar_names = "allow" # 20
wildcard_imports = "allow" # 18
used_underscore_binding = "allow" # 16
large_stack_arrays = "allow" # 14
float_cmp = "allow" # 12
# semicolon_if_nothing_returned = "allow" # 9
used_underscore_items = "allow" # 8
return_self_not_must_use = "allow" # 8
needless_pass_by_value = "allow" # 8
# manual_let_else = "allow" # 8
# needless_raw_string_hashes = "allow" # 7
match_on_vec_items = "allow" # 6
inline_always = "allow" # 6
# format_push_string = "allow" # 6
fn_params_excessive_bools = "allow" # 6
# single_char_pattern = "allow" # 4
# ptr_cast_constness = "allow" # 4
# match_wildcard_for_single_variants = "allow" # 4
# manual_is_variant_and = "allow" # 4
# explicit_deref_methods = "allow" # 4
# enum_glob_use = "allow" # 3
# unnecessary_literal_bound = "allow" # 2
# stable_sort_primitive = "allow" # 2
should_panic_without_expect = "allow" # 2
# ptr_as_ptr = "allow" # 2
# needless_for_each = "allow" # 2
if_not_else = "allow" # 2
expl_impl_clone_on_copy = "allow" # 2
# cloned_instead_of_copied = "allow" # 2
# borrow_as_ptr = "allow" # 2
bool_to_int_with_if = "allow" # 2
# ref_as_ptr = "allow" # 2
# unreadable_literal = "allow" # 1
uninlined_format_args = "allow" # ?

View file

@ -378,9 +378,8 @@ fn cat_handle<R: FdReadable>(
#[cfg(unix)]
fn is_appending() -> bool {
let stdout = io::stdout();
let flags = match fcntl(stdout.as_raw_fd(), FcntlArg::F_GETFL) {
Ok(flags) => flags,
Err(_) => return false,
let Ok(flags) = fcntl(stdout.as_raw_fd(), FcntlArg::F_GETFL) else {
return false;
};
// TODO Replace `1 << 10` with `nix::fcntl::Oflag::O_APPEND`.
let o_append = 1 << 10;
@ -814,7 +813,7 @@ mod tests {
}
assert_eq!(b" 100\t", incrementing_string.buf.as_slice());
// Run through until we overflow the original size.
for _ in 101..=1000000 {
for _ in 101..=1_000_000 {
incrementing_string.increment();
}
// Confirm that the buffer expands when we overflow the original size.

View file

@ -74,7 +74,7 @@ fn parse_userspec(spec: &str) -> UResult<UserSpec> {
// Pre-condition: `list_str` is non-empty.
fn parse_group_list(list_str: &str) -> Result<Vec<String>, ChrootError> {
let split: Vec<&str> = list_str.split(",").collect();
let split: Vec<&str> = list_str.split(',').collect();
if split.len() == 1 {
let name = split[0].trim();
if name.is_empty() {
@ -444,7 +444,8 @@ fn enter_chroot(root: &Path, skip_chdir: bool) -> UResult<()> {
CString::new(root.as_os_str().as_bytes().to_vec())
.unwrap()
.as_bytes_with_nul()
.as_ptr() as *const libc::c_char,
.as_ptr()
.cast::<libc::c_char>(),
)
};

View file

@ -42,8 +42,9 @@ fn adjust_canonicalization(p: &Path) -> Cow<Path> {
.components()
.next()
.and_then(|comp| comp.as_os_str().to_str())
.map(|p_str| p_str.starts_with(VERBATIM_PREFIX) || p_str.starts_with(DEVICE_NS_PREFIX))
.unwrap_or_default();
.is_some_and(|p_str| {
p_str.starts_with(VERBATIM_PREFIX) || p_str.starts_with(DEVICE_NS_PREFIX)
});
if has_prefix {
p.into()

View file

@ -223,6 +223,7 @@ impl Source {
///
/// If it cannot be determined, then this function returns 0.
fn len(&self) -> io::Result<i64> {
#[allow(clippy::match_wildcard_for_single_variants)]
match self {
Self::File(f) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
_ => Ok(0),
@ -274,6 +275,7 @@ impl Source {
/// then this function returns an error.
#[cfg(target_os = "linux")]
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) -> nix::Result<()> {
#[allow(clippy::match_wildcard_for_single_variants)]
match self {
Self::File(f) => {
let advice = PosixFadviseAdvice::POSIX_FADV_DONTNEED;
@ -451,7 +453,7 @@ impl Input<'_> {
/// the input file is no longer needed. If not possible, then this
/// function prints an error message to stderr and sets the exit
/// status code to 1.
#[allow(unused_variables)]
#[cfg_attr(not(target_os = "linux"), allow(clippy::unused_self, unused_variables))]
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) {
#[cfg(target_os = "linux")]
{
@ -626,6 +628,7 @@ impl Dest {
/// Truncate the underlying file to the current stream position, if possible.
fn truncate(&mut self) -> io::Result<()> {
#[allow(clippy::match_wildcard_for_single_variants)]
match self {
Self::File(f, _) => {
let pos = f.stream_position()?;
@ -656,6 +659,7 @@ impl Dest {
///
/// If it cannot be determined, then this function returns 0.
fn len(&self) -> io::Result<i64> {
#[allow(clippy::match_wildcard_for_single_variants)]
match self {
Self::File(f, _) => Ok(f.metadata()?.len().try_into().unwrap_or(i64::MAX)),
_ => Ok(0),
@ -824,7 +828,7 @@ impl<'a> Output<'a> {
/// the output file is no longer needed. If not possible, then
/// this function prints an error message to stderr and sets the
/// exit status code to 1.
#[allow(unused_variables)]
#[cfg_attr(not(target_os = "linux"), allow(clippy::unused_self, unused_variables))]
fn discard_cache(&self, offset: libc::off_t, len: libc::off_t) {
#[cfg(target_os = "linux")]
{
@ -832,7 +836,7 @@ impl<'a> Output<'a> {
"failed to discard cache for: 'standard output'".to_string()
}));
}
#[cfg(target_os = "linux")]
#[cfg(not(target_os = "linux"))]
{
// TODO Is there a way to discard filesystem cache on
// these other operating systems?

View file

@ -7,6 +7,7 @@
use std::borrow::Borrow;
use std::env;
use std::fmt::Write as _;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
@ -506,7 +507,7 @@ pub fn generate_dircolors_config() -> String {
);
config.push_str("COLORTERM ?*\n");
for term in TERMS {
config.push_str(&format!("TERM {term}\n"));
let _ = writeln!(config, "TERM {term}");
}
config.push_str(
@ -527,14 +528,14 @@ pub fn generate_dircolors_config() -> String {
);
for (name, _, code) in FILE_TYPES {
config.push_str(&format!("{name} {code}\n"));
let _ = writeln!(config, "{name} {code}");
}
config.push_str("# List any file extensions like '.gz' or '.tar' that you would like ls\n");
config.push_str("# to color below. Put the extension, a space, and the color init string.\n");
for (ext, color) in FILE_COLORS {
config.push_str(&format!("{ext} {color}\n"));
let _ = writeln!(config, "{ext} {color}");
}
config.push_str("# Subsequent TERM or COLORTERM entries, can be used to add / override\n");
config.push_str("# config specific to those matching environment variables.");

View file

@ -227,9 +227,8 @@ fn get_size_on_disk(path: &Path) -> u64 {
// bind file so it stays in scope until end of function
// if it goes out of scope the handle below becomes invalid
let file = match File::open(path) {
Ok(file) => file,
Err(_) => return size_on_disk, // opening directories will fail
let Ok(file) = File::open(path) else {
return size_on_disk; // opening directories will fail
};
unsafe {
@ -239,7 +238,7 @@ fn get_size_on_disk(path: &Path) -> u64 {
let success = GetFileInformationByHandleEx(
file.as_raw_handle() as HANDLE,
FileStandardInfo,
file_info_ptr as _,
file_info_ptr.cast(),
size_of::<FILE_STANDARD_INFO>() as u32,
);
@ -255,9 +254,8 @@ fn get_size_on_disk(path: &Path) -> u64 {
fn get_file_info(path: &Path) -> Option<FileInfo> {
let mut result = None;
let file = match File::open(path) {
Ok(file) => file,
Err(_) => return result,
let Ok(file) = File::open(path) else {
return result;
};
unsafe {
@ -267,7 +265,7 @@ fn get_file_info(path: &Path) -> Option<FileInfo> {
let success = GetFileInformationByHandleEx(
file.as_raw_handle() as HANDLE,
FileIdInfo,
file_info_ptr as _,
file_info_ptr.cast(),
size_of::<FILE_ID_INFO>() as u32,
);

21
src/uu/env/src/env.rs vendored
View file

@ -25,7 +25,6 @@ use std::borrow::Cow;
use std::env;
use std::ffi::{OsStr, OsString};
use std::io::{self, Write};
use std::ops::Deref;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
@ -159,11 +158,11 @@ fn parse_signal_opt<'a>(opts: &mut Options<'a>, opt: &'a OsStr) -> UResult<()> {
.collect();
let mut sig_vec = Vec::with_capacity(signals.len());
signals.into_iter().for_each(|sig| {
for sig in signals {
if !sig.is_empty() {
sig_vec.push(sig);
}
});
}
for sig in sig_vec {
let Some(sig_str) = sig.to_str() else {
return Err(USimpleError::new(
@ -584,7 +583,7 @@ impl EnvAppData {
Err(ref err) => {
return match err.kind() {
io::ErrorKind::NotFound | io::ErrorKind::InvalidInput => {
Err(self.make_error_no_such_file_or_dir(prog.deref()))
Err(self.make_error_no_such_file_or_dir(&prog))
}
io::ErrorKind::PermissionDenied => {
uucore::show_error!("{}: Permission denied", prog.quote());
@ -804,16 +803,16 @@ mod tests {
);
assert_eq!(
NCvt::convert(vec!["A=B", "FOO=AR", "sh", "-c", "echo $A$FOO"]),
parse_args_from_str(&NCvt::convert(r#"A=B FOO=AR sh -c 'echo $A$FOO'"#)).unwrap()
parse_args_from_str(&NCvt::convert(r"A=B FOO=AR sh -c 'echo $A$FOO'")).unwrap()
);
assert_eq!(
NCvt::convert(vec!["A=B", "FOO=AR", "sh", "-c", "echo $A$FOO"]),
parse_args_from_str(&NCvt::convert(r#"A=B FOO=AR sh -c 'echo $A$FOO'"#)).unwrap()
parse_args_from_str(&NCvt::convert(r"A=B FOO=AR sh -c 'echo $A$FOO'")).unwrap()
);
assert_eq!(
NCvt::convert(vec!["-i", "A=B ' C"]),
parse_args_from_str(&NCvt::convert(r#"-i A='B \' C'"#)).unwrap()
parse_args_from_str(&NCvt::convert(r"-i A='B \' C'")).unwrap()
);
}
@ -854,7 +853,7 @@ mod tests {
);
// Test variable-related errors
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO"#));
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO"));
assert!(result.is_err());
assert!(
result
@ -863,7 +862,7 @@ mod tests {
.contains("variable name issue (at 10): Missing closing brace")
);
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO:-value"#));
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO:-value"));
assert!(result.is_err());
assert!(
result
@ -872,11 +871,11 @@ mod tests {
.contains("variable name issue (at 17): Missing closing brace after default value")
);
let result = parse_args_from_str(&NCvt::convert(r#"echo ${1FOO}"#));
let result = parse_args_from_str(&NCvt::convert(r"echo ${1FOO}"));
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("variable name issue (at 7): Unexpected character: '1', expected variable name must not start with 0..9"));
let result = parse_args_from_str(&NCvt::convert(r#"echo ${FOO?}"#));
let result = parse_args_from_str(&NCvt::convert(r"echo ${FOO?}"));
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("variable name issue (at 10): Unexpected character: '?', expected a closing brace ('}') or colon (':')"));
}

View file

@ -6,7 +6,6 @@
use std::{
ffi::{OsStr, OsString},
mem,
ops::Deref,
};
use crate::{
@ -79,7 +78,7 @@ impl<'a> StringExpander<'a> {
pub fn put_string<S: AsRef<OsStr>>(&mut self, os_str: S) {
let native = to_native_int_representation(os_str.as_ref());
self.output.extend(native.deref());
self.output.extend(&*native);
}
pub fn put_native_string(&mut self, n_str: &NativeIntStr) {

View file

@ -356,7 +356,7 @@ fn expand_line(
tabstops: &[usize],
options: &Options,
) -> std::io::Result<()> {
use self::CharType::*;
use self::CharType::{Backspace, Other, Tab};
let mut col = 0;
let mut byte = 0;

View file

@ -102,7 +102,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if args.len() == 1 && args[0] == "--help" {
let _ = uu_app().print_help();
} else if args.len() == 1 && args[0] == "--version" {
println!("{} {}", uucore::util_name(), uucore::crate_version!())
println!("{} {}", uucore::util_name(), uucore::crate_version!());
} else {
// The first argument may be "--" and should be be ignored.
let args = if !args.is_empty() && args[0] == "--" {

View file

@ -908,7 +908,7 @@ mod test {
assert_eq!(
check_posix_regex_errors("ab\\{\\}"),
Err(InvalidBracketContent)
)
);
}
#[test]

View file

@ -56,9 +56,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
.unwrap_or_default();
if users.is_empty() {
let gids = match get_groups_gnu(None) {
Ok(v) => v,
Err(_) => return Err(GroupsError::GetGroupsFailed.into()),
let Ok(gids) = get_groups_gnu(None) else {
return Err(GroupsError::GetGroupsFailed.into());
};
let groups: Vec<String> = gids.iter().map(infallible_gid2grp).collect();
println!("{}", groups.join(" "));

View file

@ -448,7 +448,7 @@ fn pretty(possible_pw: Option<Passwd>) {
.join(" ")
);
} else {
let login = cstr2cow!(getlogin() as *const _);
let login = cstr2cow!(getlogin().cast_const());
let rid = getuid();
if let Ok(p) = Passwd::locate(rid) {
if login == p.name {
@ -647,6 +647,7 @@ mod audit {
pub type au_tid_addr_t = au_tid_addr;
#[repr(C)]
#[expect(clippy::struct_field_names)]
pub struct c_auditinfo_addr {
pub ai_auid: au_id_t, // Audit user ID
pub ai_mask: au_mask_t, // Audit masks.

View file

@ -938,16 +938,14 @@ fn copy(from: &Path, to: &Path, b: &Behavior) -> UResult<()> {
fn need_copy(from: &Path, to: &Path, b: &Behavior) -> UResult<bool> {
// Attempt to retrieve metadata for the source file.
// If this fails, assume the file needs to be copied.
let from_meta = match metadata(from) {
Ok(meta) => meta,
Err(_) => return Ok(true),
let Ok(from_meta) = metadata(from) else {
return Ok(true);
};
// Attempt to retrieve metadata for the destination file.
// If this fails, assume the file needs to be copied.
let to_meta = match metadata(to) {
Ok(meta) => meta,
Err(_) => return Ok(true),
let Ok(to_meta) = metadata(to) else {
return Ok(true);
};
// Define special file mode bits (setuid, setgid, sticky).

View file

@ -80,7 +80,7 @@ impl<'a> StyleManager<'a> {
/// Resets the current style and returns the default ANSI reset code to
/// reset all text formatting attributes. If `force` is true, the reset is
/// done even if the reset has been applied before.
pub(crate) fn reset(&mut self, force: bool) -> &str {
pub(crate) fn reset(&mut self, force: bool) -> &'static str {
// todo:
// We need to use style from `Indicator::Reset` but as of now ls colors
// uses a fallback mechanism and because of that if `Indicator::Reset`

View file

@ -3066,7 +3066,7 @@ fn get_system_time(md: &Metadata, config: &Config) -> Option<SystemTime> {
Time::Modification => md.modified().ok(),
Time::Access => md.accessed().ok(),
Time::Birth => md.created().ok(),
_ => None,
Time::Change => None,
}
}
@ -3151,7 +3151,7 @@ fn classify_file(path: &PathData, out: &mut BufWriter<Stdout>) -> Option<char> {
} else if file_type.is_file()
// Safe unwrapping if the file was removed between listing and display
// See https://github.com/uutils/coreutils/issues/5371
&& path.get_metadata(out).map(file_is_executable).unwrap_or_default()
&& path.get_metadata(out).is_some_and(file_is_executable)
{
Some('*')
} else {

View file

@ -107,7 +107,9 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let exit_code = match file_type {
FileType::Block => _mknod(file_name, S_IFBLK | mode, dev),
FileType::Character => _mknod(file_name, S_IFCHR | mode, dev),
_ => unreachable!("file_type was validated to be only block or character"),
FileType::Fifo => {
unreachable!("file_type was validated to be only block or character")
}
};
set_exit_code(exit_code);
Ok(())

View file

@ -438,7 +438,7 @@ fn assert_not_same_file(
let mut path = target
.display()
.to_string()
.trim_end_matches("/")
.trim_end_matches('/')
.to_owned();
path.push('/');

View file

@ -71,8 +71,7 @@ fn standardize_nice_args(mut args: impl uucore::Args) -> impl uucore::Args {
saw_n = false;
} else if s.to_str() == Some("-n")
|| s.to_str()
.map(|s| is_prefix_of(s, "--adjustment", "--a".len()))
.unwrap_or_default()
.is_some_and(|s| is_prefix_of(s, "--adjustment", "--a".len()))
{
saw_n = true;
} else if let Ok(s) = s.clone().into_string() {

View file

@ -210,7 +210,7 @@ fn consider_suffix(
round_method: RoundMethod,
precision: usize,
) -> Result<(f64, Option<Suffix>)> {
use crate::units::RawSuffix::*;
use crate::units::RawSuffix::{E, G, K, M, P, T, Y, Z};
let abs_n = n.abs();
let suffixes = [K, M, G, T, P, E, Z, Y];

View file

@ -115,7 +115,7 @@ fn check_path(mode: &Mode, path: &[String]) -> bool {
Mode::Basic => check_basic(path),
Mode::Extra => check_default(path) && check_extra(path),
Mode::Both => check_basic(path) && check_extra(path),
_ => check_default(path),
Mode::Default => check_default(path),
}
}

View file

@ -49,8 +49,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// leading to an infinite loop. Thus, we exit early.
if !format_seen {
if let Some(arg) = args.next() {
use FormatArgument::*;
let Unparsed(arg_str) = arg else {
let FormatArgument::Unparsed(arg_str) = arg else {
unreachable!("All args are transformed to Unparsed")
};
show_warning!("ignoring excess arguments, starting with '{arg_str}'");

View file

@ -496,7 +496,7 @@ fn handle_dir(path: &Path, options: &Options) -> bool {
let is_root = path.has_root() && path.parent().is_none();
if options.recursive && (!is_root || !options.preserve_root) {
had_err = remove_dir_recursive(path, options)
had_err = remove_dir_recursive(path, options);
} else if options.dir && (!is_root || !options.preserve_root) {
had_err = remove_dir(path, options).bitor(had_err);
} else if options.recursive {

View file

@ -87,7 +87,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
head_count: matches
.get_many::<usize>(options::HEAD_COUNT)
.unwrap_or_default()
.cloned()
.copied()
.min()
.unwrap_or(usize::MAX),
output: matches.get_one(options::OUTPUT).cloned(),

View file

@ -375,7 +375,7 @@ fn get_quoted_file_name(
}
}
fn process_token_filesystem(t: &Token, meta: StatFs, display_name: &str) {
fn process_token_filesystem(t: &Token, meta: &StatFs, display_name: &str) {
match *t {
Token::Byte(byte) => write_raw_byte(byte),
Token::Char(c) => print!("{c}"),
@ -504,7 +504,7 @@ fn print_float(num: f64, flags: &Flags, width: usize, precision: Precision, padd
};
let num_str = precision_trunc(num, precision);
let extended = format!("{prefix}{num_str}");
pad_and_print(&extended, flags.left, width, padding_char)
pad_and_print(&extended, flags.left, width, padding_char);
}
/// Prints an unsigned integer value based on the provided flags, width, and precision.
@ -1033,7 +1033,7 @@ impl Stater {
// Usage
for t in tokens {
process_token_filesystem(t, meta, &display_name);
process_token_filesystem(t, &meta, &display_name);
}
}
Err(e) => {

View file

@ -256,7 +256,7 @@ fn print_terminal_size(termios: &Termios, opts: &Options) -> nix::Result<()> {
if opts.all {
let mut size = TermSize::default();
unsafe { tiocgwinsz(opts.file.as_raw_fd(), &mut size as *mut _)? };
unsafe { tiocgwinsz(opts.file.as_raw_fd(), &raw mut size)? };
print!("rows {}; columns {}; ", size.rows, size.columns);
}

View file

@ -45,8 +45,8 @@ mod platform {
libc::syscall(libc::SYS_sync);
unsafe {
#[cfg(not(target_os = "android"))]
libc::sync()
};
libc::sync();
}
Ok(())
}
@ -177,8 +177,8 @@ mod platform {
.as_os_str()
.to_str()
.unwrap(),
)?
};
)?;
}
}
Ok(())
}

View file

@ -320,9 +320,8 @@ fn path(path: &OsStr, condition: &PathCondition) -> bool {
fn path(path: &OsStr, condition: &PathCondition) -> bool {
use std::fs::metadata;
let stat = match metadata(path) {
Ok(s) => s,
_ => return false,
let Ok(stat) = metadata(path) else {
return false;
};
match condition {

View file

@ -271,7 +271,7 @@ impl Sequence {
// Calculate the set of unique characters in set2
let mut set2_uniques = set2_solved.clone();
set2_uniques.sort();
set2_uniques.sort_unstable();
set2_uniques.dedup();
// If the complement flag is used in translate mode, only one unique

View file

@ -178,7 +178,7 @@ fn current_tty() -> String {
if res.is_null() {
String::new()
} else {
CStr::from_ptr(res as *const _)
CStr::from_ptr(res.cast_const())
.to_string_lossy()
.trim_start_matches("/dev/")
.to_owned()