Skip to content

chore: fix clippy::cast_lossless #7728

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 11 additions & 30 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,6 @@ 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
Expand All @@ -641,32 +640,14 @@ 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" # ?
used_underscore_items = "allow" # 8
return_self_not_must_use = "allow" # 8
needless_pass_by_value = "allow" # 8
match_on_vec_items = "allow" # 6
inline_always = "allow" # 6
fn_params_excessive_bools = "allow" # 6
should_panic_without_expect = "allow" # 2
if_not_else = "allow" # 2
expl_impl_clone_on_copy = "allow" # 2
bool_to_int_with_if = "allow" # 2
uninlined_format_args = "allow" # ?
20 changes: 11 additions & 9 deletions src/uu/cp/src/copydir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,16 +561,18 @@ fn build_dir(
use crate::Preserve;
use std::os::unix::fs::PermissionsExt;

// we need to allow trivial casts here because some systems like linux have u32 constants in
// we need to allow trivial casts here because some systems like linux have u32 constants
// in libc while others don't.
#[allow(clippy::unnecessary_cast)]
let mut excluded_perms = if matches!(options.attributes.ownership, Preserve::Yes { .. }) {
libc::S_IRWXG | libc::S_IRWXO // exclude rwx for group and other
} else if matches!(options.attributes.mode, Preserve::Yes { .. }) {
libc::S_IWGRP | libc::S_IWOTH //exclude w for group and other
} else {
0
} as u32;
#[allow(clippy::useless_conversion)]
let mut excluded_perms = u32::from(
if matches!(options.attributes.ownership, Preserve::Yes { .. }) {
libc::S_IRWXG | libc::S_IRWXO // exclude rwx for group and other
} else if matches!(options.attributes.mode, Preserve::Yes { .. }) {
libc::S_IWGRP | libc::S_IWOTH // exclude w for group and other
} else {
0
},
);

let umask = if copy_attributes_from.is_some()
&& matches!(options.attributes.mode, Preserve::Yes { .. })
Expand Down
1 change: 1 addition & 0 deletions src/uu/date/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ fn set_system_datetime(_date: DateTime<Utc>) -> UResult<()> {
fn set_system_datetime(date: DateTime<Utc>) -> UResult<()> {
let timespec = timespec {
tv_sec: date.timestamp() as _,
#[allow(clippy::cast_lossless)] // This may be u32->i32 or u32->i64 cast
tv_nsec: date.timestamp_subsec_nanos() as _,
};

Expand Down
4 changes: 2 additions & 2 deletions src/uu/df/src/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,9 @@ impl fmt::Display for BlockSize {
match self {
Self::Bytes(n) => {
let s = if n % 1024 == 0 && n % 1000 != 0 {
to_magnitude_and_suffix(*n as u128, SuffixType::Iec)
to_magnitude_and_suffix(u128::from(*n), SuffixType::Iec)
} else {
to_magnitude_and_suffix(*n as u128, SuffixType::Si)
to_magnitude_and_suffix(u128::from(*n), SuffixType::Si)
};

write!(f, "{s}")
Expand Down
8 changes: 4 additions & 4 deletions src/uu/df/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ impl From<Filesystem> for Row {
} else {
Some(bavail as f64 / ((bused + bavail) as f64))
},
inodes: files as u128,
inodes_used: fused as u128,
inodes_free: ffree as u128,
inodes: u128::from(files),
inodes_used: u128::from(fused),
inodes_free: u128::from(ffree),
inodes_usage: if files == 0 {
None
} else {
Expand Down Expand Up @@ -915,7 +915,7 @@ mod tests {

#[test]
fn test_row_accumulation_u64_overflow() {
let total = u64::MAX as u128;
let total = u128::from(u64::MAX);
let used1 = 3000u128;
let used2 = 50000u128;

Expand Down
2 changes: 1 addition & 1 deletion src/uu/du/src/du.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl Stat {
#[cfg(not(windows))]
{
let file_info = FileInfo {
file_id: metadata.ino() as u128,
file_id: u128::from(metadata.ino()),
dev_id: metadata.dev(),
};

Expand Down
4 changes: 2 additions & 2 deletions src/uu/ls/src/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3124,14 +3124,14 @@ fn display_size(size: u64, config: &Config) -> String {
}

#[cfg(unix)]
#[allow(clippy::useless_conversion)]
fn file_is_executable(md: &Metadata) -> bool {
// Mode always returns u32, but the flags might not be, based on the platform
// e.g. linux has u32, mac has u16.
// S_IXUSR -> user has execute permission
// S_IXGRP -> group has execute permission
// S_IXOTH -> other users have execute permission
#[allow(clippy::unnecessary_cast)]
return md.mode() & ((S_IXUSR | S_IXGRP | S_IXOTH) as u32) != 0;
(md.mode() & u32::from(S_IXUSR | S_IXGRP | S_IXOTH)) != 0
}

fn classify_file(path: &PathData, out: &mut BufWriter<Stdout>) -> Option<char> {
Expand Down
4 changes: 2 additions & 2 deletions src/uu/pinky/src/platform/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@ impl Pinky {
let last_change;

match pts_path.metadata() {
#[allow(clippy::unnecessary_cast)]
#[allow(clippy::useless_conversion)]
Ok(meta) => {
mesg = if meta.mode() & S_IWGRP as u32 == 0 {
mesg = if (meta.mode() & u32::from(S_IWGRP)) == 0 {
'*'
} else {
' '
Expand Down
4 changes: 3 additions & 1 deletion src/uu/seq/src/numberparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ fn compute_num_digits(input: &str, ebd: ExtendedBigDecimal) -> PreciseNumber {
};
frac_digits = if exp < frac_digits as i64 {
// Subtract from i128 to avoid any overflow
(frac_digits as i128 - exp as i128).try_into().unwrap_or(0)
(frac_digits as i128 - i128::from(exp))
.try_into()
.unwrap_or(0)
} else {
0
}
Expand Down
2 changes: 1 addition & 1 deletion src/uu/split/src/filenames.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ impl Suffix {
if let Strategy::Number(number_type) = strategy {
let chunks = number_type.num_chunks();
let required_length = ((start as u64 + chunks) as f64)
.log(stype.radix() as f64)
.log(f64::from(stype.radix()))
.ceil() as usize;

if (start as u64) < chunks && !(is_length_cmd_opt && length > 0) {
Expand Down
6 changes: 3 additions & 3 deletions src/uu/split/src/split.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1136,7 +1136,7 @@ where
}

for i in 1_u64..=num_chunks {
let chunk_size = chunk_size_base + (chunk_size_reminder > i - 1) as u64;
let chunk_size = chunk_size_base + u64::from(chunk_size_reminder > i - 1);
let buf = &mut Vec::new();
if num_bytes > 0 {
// Read `chunk_size` bytes from the reader into `buf`
Expand Down Expand Up @@ -1266,7 +1266,7 @@ where

let mut chunk_number = 1;
let sep = settings.separator;
let mut num_bytes_should_be_written = chunk_size_base + (chunk_size_reminder > 0) as u64;
let mut num_bytes_should_be_written = chunk_size_base + u64::from(chunk_size_reminder > 0);
let mut num_bytes_written = 0;

for line_result in reader.split(sep) {
Expand Down Expand Up @@ -1303,7 +1303,7 @@ where
let mut skipped = -1;
while num_bytes_should_be_written <= num_bytes_written {
num_bytes_should_be_written +=
chunk_size_base + (chunk_size_reminder > chunk_number) as u64;
chunk_size_base + u64::from(chunk_size_reminder > chunk_number);
chunk_number += 1;
skipped += 1;
}
Expand Down
8 changes: 4 additions & 4 deletions src/uu/stat/src/stat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -908,11 +908,11 @@ impl Stater {
// device number in hex
'D' => OutputType::UnsignedHex(meta.dev()),
// raw mode in hex
'f' => OutputType::UnsignedHex(meta.mode() as u64),
'f' => OutputType::UnsignedHex(u64::from(meta.mode())),
// file type
'F' => OutputType::Str(pretty_filetype(meta.mode() as mode_t, meta.len())),
// group ID of owner
'g' => OutputType::Unsigned(meta.gid() as u64),
'g' => OutputType::Unsigned(u64::from(meta.gid())),
// group name of owner
'G' => {
let group_name =
Expand Down Expand Up @@ -944,7 +944,7 @@ impl Stater {
// files
'T' => OutputType::UnsignedHex(meta.rdev() & 0xff),
// user ID of owner
'u' => OutputType::Unsigned(meta.uid() as u64),
'u' => OutputType::Unsigned(u64::from(meta.uid())),
// user name of owner
'U' => {
let user_name =
Expand All @@ -955,7 +955,7 @@ impl Stater {
// time of file birth, human-readable; - if unknown
'w' => OutputType::Str(
meta.birth()
.map(|(sec, nsec)| pretty_time(sec as i64, nsec as i64))
.map(|(sec, nsec)| pretty_time(sec as i64, i64::from(nsec)))
.unwrap_or(String::from("-")),
),

Expand Down
2 changes: 1 addition & 1 deletion src/uu/tr/src/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ impl Sequence {
if result.is_none() {
let origin_octal: &str = std::str::from_utf8(input).unwrap();
let actual_octal_tail: &str = std::str::from_utf8(&input[0..2]).unwrap();
let outstand_char: char = char::from_u32(input[2] as u32).unwrap();
let outstand_char: char = char::from_u32(u32::from(input[2])).unwrap();
show_warning!("the ambiguous octal escape \\{origin_octal} is being\n interpreted as the 2-byte sequence \\0{actual_octal_tail}, {outstand_char}");
}
result
Expand Down
8 changes: 5 additions & 3 deletions src/uu/wc/src/count_fast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,11 @@ pub(crate) fn count_bytes_fast<T: WordCountable>(handle: &mut T) -> (usize, Opti
// Debian Linux on ARM (aarch64-unknown-linux-gnu),
// 32bit i686 targets, etc.
// While on the others they are of the same type.
#[allow(clippy::unnecessary_cast)]
let offset =
stat.st_size as i64 - stat.st_size as i64 % (stat.st_blksize as i64 + 1);
#[allow(clippy::useless_conversion)]
let size = i64::from(stat.st_size);
#[allow(clippy::useless_conversion)]
let block = i64::from(stat.st_blksize);
let offset = size - size % (block + 1);

if let Ok(n) = file.seek(SeekFrom::Start(offset as u64)) {
byte_count = n as usize;
Expand Down
2 changes: 1 addition & 1 deletion src/uucore/src/lib/features/format/num_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub struct SignedInt {
impl Formatter<i64> for SignedInt {
fn fmt(&self, writer: impl Write, x: i64) -> std::io::Result<()> {
// -i64::MIN is actually 1 larger than i64::MAX, so we need to cast to i128 first.
let abs = (x as i128).abs();
let abs = i128::from(x).abs();
let s = if self.precision > 0 {
format!("{abs:0>width$}", width = self.precision)
} else {
Expand Down
12 changes: 6 additions & 6 deletions src/uucore/src/lib/features/parser/num_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,11 +618,11 @@ mod tests {
Err(ExtendedParserError::PartialMatch(-123, "e10"))
));
assert!(matches!(
i64::extended_parse(&format!("{}", -(u64::MAX as i128))),
i64::extended_parse(&format!("{}", -i128::from(u64::MAX))),
Err(ExtendedParserError::Overflow(i64::MIN))
));
assert!(matches!(
i64::extended_parse(&format!("{}", i64::MIN as i128 - 1)),
i64::extended_parse(&format!("{}", i128::from(i64::MIN) - 1)),
Err(ExtendedParserError::Overflow(i64::MIN))
));
}
Expand Down Expand Up @@ -868,21 +868,21 @@ mod tests {

// ExtendedBigDecimal overflow/underflow
assert!(matches!(
ExtendedBigDecimal::extended_parse(&format!("0x1p{}", u32::MAX as u64 + 1)),
ExtendedBigDecimal::extended_parse(&format!("0x1p{}", u64::from(u32::MAX) + 1)),
Err(ExtendedParserError::Overflow(ExtendedBigDecimal::Infinity))
));
assert!(matches!(
ExtendedBigDecimal::extended_parse(&format!("-0x100P{}", u32::MAX as u64 + 1)),
ExtendedBigDecimal::extended_parse(&format!("-0x100P{}", u64::from(u32::MAX) + 1)),
Err(ExtendedParserError::Overflow(
ExtendedBigDecimal::MinusInfinity
))
));
assert!(matches!(
ExtendedBigDecimal::extended_parse(&format!("0x1p-{}", u32::MAX as u64 + 1)),
ExtendedBigDecimal::extended_parse(&format!("0x1p-{}", u64::from(u32::MAX) + 1)),
Err(ExtendedParserError::Underflow(ebd)) if ebd == ExtendedBigDecimal::zero()
));
assert!(matches!(
ExtendedBigDecimal::extended_parse(&format!("-0x0.100p-{}", u32::MAX as u64 + 1)),
ExtendedBigDecimal::extended_parse(&format!("-0x0.100p-{}", u64::from(u32::MAX) + 1)),
Err(ExtendedParserError::Underflow(
ExtendedBigDecimal::MinusZero
))
Expand Down
4 changes: 2 additions & 2 deletions src/uucore/src/lib/features/sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl Crc {
table
}
fn crc_entry(input: u8) -> u32 {
let mut crc = (input as u32) << 24;
let mut crc = u32::from(input) << 24;

let mut i = 0;
while i < 8 {
Expand All @@ -153,7 +153,7 @@ impl Crc {
// ops
let condition_table = [else_body, if_body];

crc = condition_table[(if_condition != 0) as usize];
crc = condition_table[usize::from(if_condition != 0)];
i += 1;
}

Expand Down
8 changes: 4 additions & 4 deletions src/uucore/src/lib/features/utmpx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,10 @@ impl Utmpx {
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> time::OffsetDateTime {
#[allow(clippy::unnecessary_cast)]
let ts_nanos: i128 = (1_000_000_000_i64 * self.inner.ut_tv.tv_sec as i64
+ 1_000_i64 * self.inner.ut_tv.tv_usec as i64)
.into();
#[allow(clippy::useless_conversion)]
let ts_nanos: i128 = (1_000_000_000_i64 * i64::from(self.inner.ut_tv.tv_sec)
+ 1_000_i64 * i64::from(self.inner.ut_tv.tv_usec))
.into();
let local_offset =
time::OffsetDateTime::now_local().map_or_else(|_| time::UtcOffset::UTC, |v| v.offset());
time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
Expand Down
Loading