#
std/sys/io/io_slice/
iovec.rs

    1#[cfg(target_os = "hermit")]
    2use hermit_abi::iovec;
    3#[cfg(any(target_family = "unix", target_os = "trusty"))]
    4use libc::iovec;
    5
    6use crate::ffi::c_void;
    7use crate::marker::PhantomData;
    8use crate::slice;
    9#[cfg(target_os = "solid_asp3")]
    10use crate::sys::pal::abi::sockets::iovec;
    11
    12#[derive(Copy, Clone)]
    13#[repr(transparent)]
    14pub struct IoSlice<'a> {
    15    vec: iovec,
    16    _p: PhantomData<&'a [u8]>,
    17}
    18
    19impl<'a> IoSlice<'a> {
    20    #[inline]
    21    pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
    22        IoSlice {
    23            vec: iovec { iov_base: buf.as_ptr() as *mut u8 as *mut c_void, iov_len: buf.len() },
    24            _p: PhantomData,
    25        }
    26    }
    27
    28    #[inline]
    29    pub fn advance(&mut self, n: usize) {
    30        if self.vec.iov_len < n {
    31            panic!("advancing IoSlice beyond its length");
    32        }
    33
    34        unsafe {
    35            self.vec.iov_len -= n;
    36            self.vec.iov_base = self.vec.iov_base.add(n);
    37        }
    38    }
    39
    40    #[inline]
    41    pub const fn as_slice(&self) -> &'a [u8] {
    42        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
    43    }
    44}
    45
    46#[repr(transparent)]
    47pub struct IoSliceMut<'a> {
    48    vec: iovec,
    49    _p: PhantomData<&'a mut [u8]>,
    50}
    51
    52impl<'a> IoSliceMut<'a> {
    53    #[inline]
    54    pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
    55        IoSliceMut {
    56            vec: iovec { iov_base: buf.as_mut_ptr() as *mut c_void, iov_len: buf.len() },
    57            _p: PhantomData,
    58        }
    59    }
    60
    61    #[inline]
    62    pub fn advance(&mut self, n: usize) {
    63        if self.vec.iov_len < n {
    64            panic!("advancing IoSliceMut beyond its length");
    65        }
    66
    67        unsafe {
    68            self.vec.iov_len -= n;
    69            self.vec.iov_base = self.vec.iov_base.add(n);
    70        }
    71    }
    72
    73    #[inline]
    74    pub fn as_slice(&self) -> &[u8] {
    75        unsafe { slice::from_raw_parts(self.vec.iov_base as *mut u8, self.vec.iov_len) }
    76    }
    77
    78    #[inline]
    79    pub const fn into_slice(self) -> &'a mut [u8] {
    80        unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
    81    }
    82
    83    #[inline]
    84    pub fn as_mut_slice(&mut self) -> &mut [u8] {
    85        unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
    86    }
    87}