Skip to content

Commit

Permalink
Remove most as casts
Browse files Browse the repository at this point in the history
  • Loading branch information
kotauskas committed Apr 26, 2024
1 parent 4c20040 commit db798c0
Show file tree
Hide file tree
Showing 32 changed files with 234 additions and 108 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,14 @@ missing_docs = "warn"

[lints.clippy]
exit = "forbid"
ptr_as_ptr = "forbid"
get_unwrap = "deny"
as_conversions = "deny"
dbg_macro = "warn"
arithmetic_side_effects = "warn"
indexing_slicing = "warn"
missing_assert_message = "warn"
panic_in_result_fn = "warn"
unwrap_used = "warn"
unwrap_in_result = "warn"
tabs_in_doc_comments = "allow"

[package.metadata.docs.rs]
Expand Down
1 change: 1 addition & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ impl<S, E: Display> Display for ConversionError<S, E> {
}
impl<S: Debug, E: Error + 'static> Error for ConversionError<S, E> {
#[inline]
#[allow(clippy::as_conversions)]
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.cause.as_ref().map(|r| r as &_)
}
Expand Down
10 changes: 5 additions & 5 deletions src/macros/derive_mut_iorw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ macro_rules! derive_sync_mut_read {
impl $(<$($lt)*>)? ::std::io::Read for $ty {
#[inline(always)]
fn read(&mut self, buf: &mut [u8]) -> ::std::io::Result<usize> {
(self as &Self).read(buf)
(&*self).read(buf)
}
#[inline(always)]
fn read_vectored(
&mut self,
bufs: &mut [::std::io::IoSliceMut<'_>],
) -> ::std::io::Result<usize> { (self as &Self).read_vectored(bufs) }
) -> ::std::io::Result<usize> { (&*self).read_vectored(bufs) }
// read_to_end isn't here because this macro isn't supposed to be used on Chain-like
// adapters
// FUTURE is_read_vectored
Expand All @@ -25,17 +25,17 @@ macro_rules! derive_sync_mut_write {
impl $(<$($lt)*>)? ::std::io::Write for $ty {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {
(self as &Self).write(buf)
(&*self).write(buf)
}
#[inline(always)]
fn flush(&mut self) -> ::std::io::Result<()> {
(self as &Self).flush()
(&*self).flush()
}
#[inline(always)]
fn write_vectored(
&mut self,
bufs: &[::std::io::IoSlice<'_>],
) -> ::std::io::Result<usize> { (self as &Self).write_vectored(bufs) }
) -> ::std::io::Result<usize> { (&*self).write_vectored(bufs) }
// FUTURE is_write_vectored
}
};
Expand Down
87 changes: 86 additions & 1 deletion src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,36 @@ impl ToBool for i32 {
}
}

// TODO(2.0.1) add a helper for casting references to pointers and then forbid all as casts
pub(crate) trait BoolExt {
fn to_i32(self) -> i32;
fn to_usize(self) -> usize;
}
impl BoolExt for bool {
#[inline(always)] #[rustfmt::skip] // oh come on now
fn to_i32(self) -> i32 {
if self { 1 } else { 0 }
}
#[inline(always)] #[rustfmt::skip]
fn to_usize(self) -> usize {
if self { 1 } else { 0 }
}
}

pub(crate) trait AsPtr {
#[inline(always)]
fn as_ptr(&self) -> *const Self {
self
}
}
impl<T: ?Sized> AsPtr for T {}

pub(crate) trait AsMutPtr {
#[inline(always)]
fn as_mut_ptr(&mut self) -> *mut Self {
self
}
}
impl<T: ?Sized> AsMutPtr for T {}

impl<T, E: std::fmt::Debug> DebugExpectExt for Result<T, E> {
#[inline]
Expand Down Expand Up @@ -125,6 +154,62 @@ pub(crate) trait NumExt: Sized {
}
impl<T> NumExt for T {}

pub(crate) trait SubUsizeExt: TryInto<usize> + Sized {
fn to_usize(self) -> usize;
}
pub(crate) trait SubIsizeExt: TryInto<usize> + Sized {
fn to_isize(self) -> isize;
}
macro_rules! impl_subsize {
($src:ident to usize) => {
impl SubUsizeExt for $src {
#[inline(always)]
#[allow(clippy::as_conversions)]
fn to_usize(self) -> usize {
self as usize
}
}
};
($src:ident to isize) => {
impl SubIsizeExt for $src {
#[inline(always)]
#[allow(clippy::as_conversions)]
fn to_isize(self) -> isize {
self as isize
}
}
};
($($src:ident to $dst:ident)+) => {$(
impl_subsize!($src to $dst);
)+};
}
// See platform_check.rs.
impl_subsize! {
u8 to usize
u16 to usize
u32 to usize
i8 to isize
i16 to isize
i32 to isize
u8 to isize
u16 to isize
}

// TODO(2.3.0) find a more elegant way
pub(crate) trait RawOsErrorExt {
fn eeq(self, other: u32) -> bool;
}
impl RawOsErrorExt for Option<i32> {
#[inline(always)]
#[allow(clippy::as_conversions)]
fn eeq(self, other: u32) -> bool {
match self {
Some(n) => n as u32 == other,
None => false,
}
}
}

#[inline(always)]
pub(crate) fn weaken_buf_init<T>(r: &[T]) -> &[MaybeUninit<T>] {
unsafe {
Expand Down
10 changes: 8 additions & 2 deletions src/os/unix/c_wrappers.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::unixprelude::*;
use crate::AsPtr;
#[allow(unused_imports)]
use crate::{FdOrErrno, OrErrno};
use libc::{sockaddr_un, AF_UNIX};
Expand Down Expand Up @@ -114,6 +115,7 @@ fn addr_to_slice(addr: &SocketAddr) -> (&[u8], usize) {
}
}

#[allow(clippy::as_conversions)]
const SUN_PATH_OFFSET: usize = unsafe {
// This code may or may not have been copied from the standard library
let addr = zeroed::<sockaddr_un>();
Expand All @@ -122,7 +124,11 @@ const SUN_PATH_OFFSET: usize = unsafe {
path.byte_offset_from(base) as usize
};

#[allow(clippy::indexing_slicing, clippy::arithmetic_side_effects)]
#[allow(
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
clippy::as_conversions
)]
fn bind(fd: BorrowedFd<'_>, addr: &SocketAddr) -> io::Result<()> {
let (path, extra) = addr_to_slice(addr);
let path = unsafe { transmute::<&[u8], &[i8]>(path) };
Expand All @@ -136,7 +142,7 @@ fn bind(fd: BorrowedFd<'_>, addr: &SocketAddr) -> io::Result<()> {
unsafe {
libc::bind(
fd.as_raw_fd(),
(&addr as *const sockaddr_un).cast(),
addr.as_ptr().cast(),
// It's impossible for this to exceed socklen_t::MAX, since it came from a valid
// SocketAddr
len as _,
Expand Down
13 changes: 9 additions & 4 deletions src/os/unix/fdops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ use super::{c_wrappers, unixprelude::*};
use crate::{OrErrno, TryClone};
use std::io::{self, prelude::*, IoSlice, IoSliceMut};

#[allow(clippy::as_conversions)]
fn i2u(i: isize) -> usize {
i as usize
}

#[repr(transparent)]
pub(super) struct FdOps(pub(super) OwnedFd);
impl Read for &FdOps {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let length_to_read = buf.len();
let bytes_read =
unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), length_to_read) };
(bytes_read >= 0).true_val_or_errno(bytes_read as usize)
(bytes_read >= 0).true_val_or_errno(i2u(bytes_read))
}
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
let num_bufs = c_int::try_from(bufs.len()).unwrap_or(c_int::MAX);
let bytes_read = unsafe { libc::readv(self.0.as_raw_fd(), bufs.as_ptr().cast(), num_bufs) };
(bytes_read >= 0).true_val_or_errno(bytes_read as usize)
(bytes_read >= 0).true_val_or_errno(i2u(bytes_read))
}
// FUTURE can_vector
}
Expand All @@ -23,13 +28,13 @@ impl Write for &FdOps {
let length_to_write = buf.len();
let bytes_written =
unsafe { libc::write(self.0.as_raw_fd(), buf.as_ptr().cast(), length_to_write) };
(bytes_written >= 0).true_val_or_errno(bytes_written as usize)
(bytes_written >= 0).true_val_or_errno(i2u(bytes_written))
}
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
let num_bufs = c_int::try_from(bufs.len()).unwrap_or(c_int::MAX);
let bytes_written =
unsafe { libc::writev(self.0.as_raw_fd(), bufs.as_ptr().cast(), num_bufs) };
(bytes_written >= 0).true_val_or_errno(bytes_written as usize)
(bytes_written >= 0).true_val_or_errno(i2u(bytes_written))
}
// FUTURE can_vector
fn flush(&mut self) -> io::Result<()> {
Expand Down
2 changes: 1 addition & 1 deletion src/os/unix/fifo_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@ pub fn create_fifo<P: AsRef<Path>>(path: P, mode: mode_t) -> io::Result<()> {
}
fn _create_fifo(path: &Path, mode: mode_t) -> io::Result<()> {
let path = CString::new(path.as_os_str().as_bytes())?;
unsafe { libc::mkfifo(path.as_bytes_with_nul().as_ptr() as *const _, mode) != -1 }
unsafe { libc::mkfifo(path.as_bytes_with_nul().as_ptr().cast(), mode) != -1 }
.true_val_or_errno(())
}
8 changes: 4 additions & 4 deletions src/os/windows/c_wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ use windows_sys::Win32::{

pub fn duplicate_handle(handle: BorrowedHandle<'_>) -> io::Result<OwnedHandle> {
let raw = duplicate_handle_inner(handle, None)?;
unsafe { Ok(OwnedHandle::from_raw_handle(raw as RawHandle)) }
unsafe { Ok(OwnedHandle::from_raw_handle(raw.to_std())) }
}
pub fn duplicate_handle_to_foreign(
handle: BorrowedHandle<'_>,
other_process: BorrowedHandle<'_>,
) -> io::Result<RawHandle> {
) -> io::Result<HANDLE> {
duplicate_handle_inner(handle, Some(other_process))
}

fn duplicate_handle_inner(
handle: BorrowedHandle<'_>,
other_process: Option<BorrowedHandle<'_>>,
) -> io::Result<RawHandle> {
) -> io::Result<HANDLE> {
let mut new_handle = INVALID_HANDLE_VALUE;
unsafe {
let proc = GetCurrentProcess();
Expand All @@ -34,5 +34,5 @@ fn duplicate_handle_inner(
DUPLICATE_SAME_ACCESS,
)
}
.true_val_or_errno(new_handle as _)
.true_val_or_errno(new_handle)
}
16 changes: 8 additions & 8 deletions src/os/windows/file_handle.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{c_wrappers, downgrade_eof, winprelude::*};
use crate::{OrErrno, TryClone};
use crate::{AsMutPtr, OrErrno, SubUsizeExt, TryClone};
use std::{io, mem::MaybeUninit, ptr};
use windows_sys::Win32::{
Foundation::MAX_PATH,
Expand All @@ -19,11 +19,11 @@ impl FileHandle {
self.as_int_handle(),
buf.as_mut_ptr().cast(),
len,
&mut bytes_read as *mut _,
bytes_read.as_mut_ptr(),
ptr::null_mut(),
)
}
.true_val_or_errno(bytes_read as usize)
.true_val_or_errno(bytes_read.to_usize())
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let len = u32::try_from(buf.len()).unwrap_or(u32::MAX);
Expand All @@ -34,11 +34,11 @@ impl FileHandle {
self.as_int_handle(),
buf.as_ptr().cast(),
len,
&mut bytes_written as *mut _,
bytes_written.as_mut_ptr(),
ptr::null_mut(),
)
}
.true_val_or_errno(bytes_written as usize)
.true_val_or_errno(bytes_written.to_usize())
}
#[inline(always)]
pub fn flush(&self) -> io::Result<()> {
Expand All @@ -52,7 +52,7 @@ impl FileHandle {
// The second arm is unreachable if cap > len.
#[allow(dead_code, clippy::arithmetic_side_effects)]
pub fn path(handle: BorrowedHandle<'_>) -> io::Result<Vec<u16>> {
let mut buf = Vec::with_capacity((MAX_PATH + 1) as usize);
let mut buf = Vec::with_capacity((MAX_PATH + 1).to_usize());
match Self::_path(handle.as_int_handle(), &mut buf) {
(_, Ok(true)) => Ok(buf),
(len, Ok(false)) => {
Expand All @@ -71,14 +71,14 @@ impl FileHandle {
buf.clear();
let buflen = buf.capacity().try_into().unwrap_or(u32::MAX);
let rslt = unsafe { GetFinalPathNameByHandleW(handle, buf.as_mut_ptr(), buflen, 0) };
let len = rslt as usize;
let len = rslt.to_usize();
let e = if rslt >= buflen {
Ok(false)
} else if rslt == 0 {
Err(io::Error::last_os_error())
} else {
// +1 to include the nul terminator in the size.
unsafe { buf.set_len(rslt as usize + 1) }
unsafe { buf.set_len(rslt.to_usize() + 1) }
Ok(true)
};
(len, e)
Expand Down
18 changes: 16 additions & 2 deletions src/os/windows/misc.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
pub(super) mod winprelude {
pub(crate) use super::AsRawHandleExt;
pub(crate) use super::{AsRawHandleExt as _, HANDLEExt as _};
pub(crate) use std::os::windows::prelude::*;
pub(crate) use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
}

use std::io::{self, ErrorKind::BrokenPipe};
use winprelude::*;

use crate::RawOsErrorExt as _;

pub(crate) trait AsRawHandleExt: AsRawHandle {
#[inline(always)]
#[allow(clippy::as_conversions)]
fn as_int_handle(&self) -> HANDLE {
self.as_raw_handle() as HANDLE
}
}
impl<T: AsRawHandle + ?Sized> AsRawHandleExt for T {}

pub(crate) trait HANDLEExt {
fn to_std(self) -> RawHandle;
}
impl HANDLEExt for HANDLE {
#[inline(always)]
#[allow(clippy::as_conversions)]
fn to_std(self) -> RawHandle {
self as RawHandle
}
}

pub(super) fn decode_eof<T>(r: io::Result<T>) -> io::Result<T> {
use windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED;
match r {
Err(e) if e.raw_os_error() == Some(ERROR_PIPE_NOT_CONNECTED as _) => {
Err(e) if e.raw_os_error().eeq(ERROR_PIPE_NOT_CONNECTED) => {
Err(io::Error::from(BrokenPipe))
}
els => els,
Expand Down
Loading

0 comments on commit db798c0

Please sign in to comment.