use core::ffi::{c_int, c_void};
use crate::io::{IoSlice, IoSliceMut, SeekFrom};
use crate::sys::{cvt, cvt_long};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};
const IOV_MAX: usize = 1024;
const MAX_LEN: usize = c_int::MAX as usize - 1;
const F_GETFD: c_int = 1;
const F_GETFL: c_int = 3;
const F_SETFL: c_int = 4;
const O_NONBLOCK: c_int = 0x4;
const F_SETFD: c_int = 2;
const F_DUPFD_CLOEXEC: c_int = 67;
const FD_CLOEXEC: c_int = 1;
unsafe extern "C" {
#[link_name = "read"]
fn c_read(fd: c_int, buf: *mut c_void, len: usize) -> isize;
#[link_name = "write"]
fn c_write(fd: c_int, buf: *const c_void, len: usize) -> isize;
fn pread(fd: c_int, buf: *mut c_void, len: usize, offset: i64) -> isize;
fn pwrite(fd: c_int, buf: *const c_void, len: usize, offset: i64) -> isize;
fn readv(fd: c_int, iov: *const RawIoSlice, count: c_int) -> isize;
fn writev(fd: c_int, iov: *const RawIoSlice, count: c_int) -> isize;
fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64;
#[link_name = "pipe"]
fn c_pipe(fds: *mut c_int) -> c_int;
pub(crate) fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
fn isatty(fd: c_int) -> c_int;
}
#[derive(Clone, Copy)]
#[repr(C)]
pub(crate) struct RawIoSlice {
base: *mut u8,
len: usize,
}
impl RawIoSlice {
#[inline]
pub(crate) fn new(base: *mut u8, len: usize) -> Self {
Self { base, len }
}
#[inline]
pub(crate) fn ptr(&self) -> *mut u8 {
self.base
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.len
}
}
fn cvt_len(ret: isize) -> Result<usize> {
cvt_long(ret as i64).map(|n| n as usize)
}
fn file_offset(offset: u64) -> Result<i64> {
i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput.into())
}
pub(crate) fn read(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
let len = buf.len().min(MAX_LEN);
cvt_len(unsafe { c_read(handle.as_raw(), buf.as_mut_ptr().cast(), len) })
}
pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
let len = buf.len().min(MAX_LEN);
cvt_len(unsafe { c_write(handle.as_raw(), buf.as_ptr().cast(), len) })
}
pub(crate) fn read_at(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: u64) -> Result<usize> {
let len = buf.len().min(MAX_LEN);
let offset = file_offset(offset)?;
cvt_len(unsafe { pread(handle.as_raw(), buf.as_mut_ptr().cast(), len, offset) })
}
pub(crate) fn write_at(handle: BorrowedHandle<'_>, buf: &[u8], offset: u64) -> Result<usize> {
let len = buf.len().min(MAX_LEN);
let offset = file_offset(offset)?;
cvt_len(unsafe { pwrite(handle.as_raw(), buf.as_ptr().cast(), len, offset) })
}
pub(crate) fn read_vectored(
handle: BorrowedHandle<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
if bufs.is_empty() {
return read(handle, &mut []);
}
let count = bufs.len().min(IOV_MAX) as c_int;
cvt_len(unsafe { readv(handle.as_raw(), bufs.as_ptr().cast(), count) })
}
pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
if bufs.is_empty() {
return write(handle, &[]);
}
let count = bufs.len().min(IOV_MAX) as c_int;
cvt_len(unsafe { writev(handle.as_raw(), bufs.as_ptr().cast(), count) })
}
pub(crate) fn seek(handle: BorrowedHandle<'_>, pos: SeekFrom) -> Result<u64> {
let (offset, whence) = match pos {
SeekFrom::Start(offset) => (offset as i64, 0),
SeekFrom::Current(offset) => (offset, 1),
SeekFrom::End(offset) => (offset, 2),
};
cvt_long(unsafe { lseek(handle.as_raw(), offset, whence) }).map(|pos| pos as u64)
}
pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
let mut fds: [c_int; 2] = [0; 2];
cvt(unsafe { c_pipe(fds.as_mut_ptr()) })?;
let pair = unsafe { (OwnedHandle::from_raw(fds[0]), OwnedHandle::from_raw(fds[1])) };
set_inheritable(pair.0.as_handle(), false)?;
set_inheritable(pair.1.as_handle(), false)?;
Ok(pair)
}
pub(crate) fn duplicate(handle: BorrowedHandle<'_>) -> Result<OwnedHandle> {
let min: c_int = 0;
let fd = cvt(unsafe { fcntl(handle.as_raw(), F_DUPFD_CLOEXEC, min) })?;
Ok(unsafe { OwnedHandle::from_raw(fd) })
}
fn std_handle(fd: i32) -> Option<BorrowedHandle<'static>> {
Some(unsafe { BorrowedHandle::borrow_raw(fd) })
}
pub(crate) fn stdin() -> Option<BorrowedHandle<'static>> {
std_handle(0)
}
pub(crate) fn stdout() -> Option<BorrowedHandle<'static>> {
std_handle(1)
}
pub(crate) fn stderr() -> Option<BorrowedHandle<'static>> {
std_handle(2)
}
pub(crate) fn is_terminal(handle: BorrowedHandle<'_>) -> bool {
unsafe { isatty(handle.as_raw()) == 1 }
}
pub(crate) fn set_inheritable(handle: BorrowedHandle<'_>, inheritable: bool) -> Result<()> {
let flags = if inheritable { 0 } else { FD_CLOEXEC };
cvt(unsafe { fcntl(handle.as_raw(), F_SETFD, flags) })?;
Ok(())
}
pub(crate) fn is_inheritable(handle: BorrowedHandle<'_>) -> Result<bool> {
let flags = cvt(unsafe { fcntl(handle.as_raw(), F_GETFD) })?;
Ok(flags & FD_CLOEXEC == 0)
}
pub(crate) fn set_nonblocking(handle: BorrowedHandle<'_>, nonblocking: bool) -> Result<()> {
let flags = cvt(unsafe { fcntl(handle.as_raw(), F_GETFL) })?;
let new = if nonblocking {
flags | O_NONBLOCK
} else {
flags & !O_NONBLOCK
};
if new != flags {
cvt(unsafe { fcntl(handle.as_raw(), F_SETFL, new) })?;
}
Ok(())
}