oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Reading and writing on any handle, pipes, and the standard handles.
//!
//! The functions take anything that holds a handle ([`AsHandle`]): an
//! [`OwnedHandle`] by reference, or a [`BorrowedHandle`]. They work on
//! files, pipes, terminals and every other object the system reads and
//! writes through a handle. Sockets have their own functions in
//! [`net`](crate::net).
//!
//! Each function is one system call. A read or a write may transfer fewer
//! bytes than asked; a call interrupted by a signal fails with
//! [`ErrorKind::Interrupted`] and may be
//! retried.
//!
//! On Windows a handle may be open for overlapped (asynchronous) operation,
//! when it was not opened by oscall: a file opened with
//! `FILE_FLAG_OVERLAPPED`, the pipe of a child process. The functions here
//! are synchronous on such a handle too: each returns when its operation is
//! complete, as `std`'s do (`NtReadFile`, `NtWriteFile`, and a wait). A
//! file opened that way has no position, so that only [`read_at`] and
//! [`write_at`] work on it; [`read()`] and [`write()`] fail with
//! [`ErrorKind::InvalidInput`].
//!
//! On WebAssembly without WASI every function fails with
//! [`ErrorKind::Unsupported`]. What WASI
//! itself lacks is said in each function.

use core::fmt;
use core::marker::PhantomData;

use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result, sys};

/// Reads from `handle` into `buf`, at the handle's current position for
/// those that have one, and returns the number of bytes read.
///
/// `Ok(0)` means the end of the file, or of a pipe whose write end is
/// closed (or that `buf` is empty).
#[inline]
pub fn read(handle: impl AsHandle, buf: &mut [u8]) -> Result<usize> {
    sys::io::read(handle.as_handle(), buf)
}

/// Writes `buf` to `handle`, at the handle's current position for those that
/// have one (at the end of the file for one opened for appending), and
/// returns the number of bytes written, which may be less than `buf.len()`.
///
/// Writing to a pipe whose read end is closed fails with
/// [`ErrorKind::BrokenPipe`]. On Linux and
/// macOS the system also raises `SIGPIPE`, which kills the process unless
/// it is ignored, as it is in every program with Rust's `main`.
#[inline]
pub fn write(handle: impl AsHandle, buf: &[u8]) -> Result<usize> {
    sys::io::write(handle.as_handle(), buf)
}

/// Reads from `handle` at `offset` bytes from the start of the file, and
/// returns the number of bytes read: `Ok(0)` at or after the end.
///
/// The handle must be seekable. On Linux, macOS and WASI the handle's
/// position is neither used nor changed (`pread`). **On Windows the
/// position moves** to the end of what was read, as there is no way to
/// avoid it on a synchronous handle: do not mix positional and sequential
/// I/O on one handle, nor share a handle between threads that do.
#[inline]
pub fn read_at(handle: impl AsHandle, buf: &mut [u8], offset: u64) -> Result<usize> {
    sys::io::read_at(handle.as_handle(), buf, offset)
}

/// Writes `buf` to `handle` at `offset` bytes from the start of the file,
/// and returns the number of bytes written.
///
/// Writing past the end extends the file, and the gap reads as zeroes.
///
/// The handle must be seekable. As for [`read_at`], the handle's position
/// is left alone, except on Windows where it moves to the end of what was
/// written. On a handle opened for appending, Linux appends the data
/// whatever `offset` is; macOS and Windows honour `offset`. Do not rely on
/// either.
#[inline]
pub fn write_at(handle: impl AsHandle, buf: &[u8], offset: u64) -> Result<usize> {
    sys::io::write_at(handle.as_handle(), buf, offset)
}

/// Reads from `handle` into several buffers, filling each one before using
/// the next, and returns the total number of bytes read.
///
/// One system call (`readv`) on Linux, macOS and WASI, where at most 1024
/// buffers are used. Windows has no such call for files and pipes: only the
/// first buffer that is not empty is read into, which is what a short read
/// looks like. Some WASI hosts (wasmtime) do the same.
#[inline]
pub fn read_vectored(handle: impl AsHandle, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
    sys::io::read_vectored(handle.as_handle(), bufs)
}

/// Writes the content of several buffers to `handle`, in order, and returns
/// the total number of bytes written.
///
/// One system call (`writev`) on Linux, macOS and WASI, where at most 1024
/// buffers are used. Windows has no such call for files and pipes: only the
/// first buffer that is not empty is written, which is what a short write
/// looks like. Some WASI hosts (wasmtime) do the same.
#[inline]
pub fn write_vectored(handle: impl AsHandle, bufs: &[IoSlice<'_>]) -> Result<usize> {
    sys::io::write_vectored(handle.as_handle(), bufs)
}

/// A position to [`seek`] to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SeekFrom {
    /// This many bytes from the start of the file.
    Start(u64),
    /// This many bytes from the current position; negative to go back.
    Current(i64),
    /// This many bytes from the end of the file; negative to go back.
    End(i64),
}

/// Moves the position of `handle` and returns the new position, in bytes
/// from the start of the file.
///
/// `seek(handle, SeekFrom::Current(0))` reads the position. A position
/// after the end is allowed (writing there extends the file); one before
/// the start fails with [`ErrorKind::InvalidInput`]. A pipe or a terminal
/// has no position: Linux, macOS and WASI fail with
/// [`ErrorKind::NotSeekable`]; Windows may succeed and do nothing.
#[inline]
pub fn seek(handle: impl AsHandle, pos: SeekFrom) -> Result<u64> {
    if let SeekFrom::Start(offset) = pos
        && offset > i64::MAX as u64
    {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::io::seek(handle.as_handle(), pos)
}

/// Creates a pipe and returns its read end and its write end, in that order.
///
/// What is written to the second handle can be read from the first. Both
/// are blocking and private to the process (close-on-exec, not
/// inheritable): see [`set_inheritable`] to give one to a child process.
///
/// `pipe2` on Linux, `CreatePipe` on Windows. macOS has no call that
/// creates the pipe close-on-exec at once: the flag is set right after
/// `pipe`, and a process spawned by another thread in between inherits the
/// pipe.
///
/// WASI has no pipes: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    sys::io::pipe()
}

/// Creates a second handle to the object `handle` refers to.
///
/// The two handles share everything: the position in a file, its open mode,
/// its locks. Closing one leaves the other open. The new handle is private
/// to the process, whatever `handle` is.
///
/// `fcntl(F_DUPFD_CLOEXEC)` on Linux and macOS, `DuplicateHandle` on
/// Windows.
///
/// WASI cannot duplicate a descriptor: fails with
/// [`ErrorKind::Unsupported`].
#[inline]
pub fn duplicate(handle: impl AsHandle) -> Result<OwnedHandle> {
    sys::io::duplicate(handle.as_handle())
}

/// The standard input of the process.
///
/// `None` when the process has none, which only Windows can tell (a
/// graphical program, a detached process) and WebAssembly without WASI.
/// Elsewhere it is always descriptor 0, which the parent process may have
/// left closed: using it then fails with [`ErrorKind::BadHandle`].
///
/// The handle is not owned: it is never closed by oscall.
#[inline]
pub fn stdin() -> Option<BorrowedHandle<'static>> {
    sys::io::stdin()
}

/// The standard output of the process. See [`stdin`].
#[inline]
pub fn stdout() -> Option<BorrowedHandle<'static>> {
    sys::io::stdout()
}

/// The standard error output of the process. See [`stdin`].
#[inline]
pub fn stderr() -> Option<BorrowedHandle<'static>> {
    sys::io::stderr()
}

/// Whether `handle` is a terminal (a console on Windows).
///
/// `false` for anything else, including a handle that is not valid. On
/// Windows, the pseudo-terminals of MSYS and Cygwin are pipes and are not
/// recognised.
#[inline]
pub fn is_terminal(handle: impl AsHandle) -> bool {
    sys::io::is_terminal(handle.as_handle())
}

/// Sets whether child processes inherit `handle`.
///
/// Every handle oscall creates starts out private. An inheritable handle
/// stays open across `exec` on Linux and macOS (this clears `FD_CLOEXEC`),
/// and is given to the child processes created with handle inheritance on
/// Windows (`HANDLE_FLAG_INHERIT`).
///
/// WASI has no processes: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn set_inheritable(handle: impl AsHandle, inheritable: bool) -> Result<()> {
    sys::io::set_inheritable(handle.as_handle(), inheritable)
}

/// Whether child processes inherit `handle`. See [`set_inheritable`].
///
/// WASI has no processes: fails with [`ErrorKind::Unsupported`].
#[inline]
pub fn is_inheritable(handle: impl AsHandle) -> Result<bool> {
    sys::io::is_inheritable(handle.as_handle())
}

/// Sets whether [`read`] and [`write()`] on a pipe return at once instead of
/// waiting: for data to read, or for room to write.
///
/// On a non-blocking pipe:
///
/// - reading an empty pipe fails with [`ErrorKind::WouldBlock`], unless
///   its write end is closed, which is the end as ever: `Ok(0)`;
/// - writing transfers what fits and returns that count, and fails with
///   [`ErrorKind::WouldBlock`] when nothing fits.
///
/// The mode belongs to the end of the pipe, not to the handle: its
/// [duplicates](duplicate) share it, and so does a process that inherited
/// the handle. Each end of a [`pipe`] has its own, and both start blocking.
///
/// `fcntl(F_SETFL)` with `O_NONBLOCK` on Linux and macOS, where it works on
/// the other handles that can make a call wait as well: FIFOs, terminals
/// and devices (and has no effect on files). `SetNamedPipeHandleState`
/// with `PIPE_NOWAIT` on Windows, where it only works on pipes, anonymous
/// or named, and fails on anything else. Sockets have
/// [`net::set_nonblocking`](crate::net::set_nonblocking).
///
/// On Windows the system reports a non-blocking read that would wait with
/// the error it uses for a broken pipe: oscall makes it
/// [`ErrorKind::WouldBlock`] (the code of `WSAEWOULDBLOCK`). And a pipe
/// there takes a non-blocking write whole or not at all, which it reports
/// as a write of nothing: oscall then asks how much room the pipe has
/// (`NtQueryInformationFile`) and writes that much, or tries shorter and
/// shorter writes when the system reports none. A write is one system call
/// when the data fits, a few when part of it does, and about as many as
/// the length has bits before it reports a pipe that is full.
///
/// WASI has no pipes of its own, but its standard handles may be some:
/// `fd_fdstat_set_flags`, which hosts honour as they can.
#[inline]
pub fn set_nonblocking(handle: impl AsHandle, nonblocking: bool) -> Result<()> {
    sys::io::set_nonblocking(handle.as_handle(), nonblocking)
}

/// A buffer to write from, for [`write_vectored`].
///
/// It is a `&[u8]` with the layout the system wants for vectored I/O:
/// `struct iovec` on Linux, macOS and WASI, `WSABUF` on Windows. A slice of
/// `IoSlice` can therefore be handed to the system as it is.
///
/// On Windows a buffer cannot be longer than `u32::MAX` bytes: a longer
/// slice is cut to that length, which a write reports as a short write.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct IoSlice<'a>(sys::io::RawIoSlice, PhantomData<&'a [u8]>);

// SAFETY: an `IoSlice` is a `&[u8]`.
unsafe impl Send for IoSlice<'_> {}
// SAFETY: as above.
unsafe impl Sync for IoSlice<'_> {}

impl<'a> IoSlice<'a> {
    /// Wraps a slice.
    #[inline]
    pub fn new(buf: &'a [u8]) -> Self {
        Self(
            sys::io::RawIoSlice::new(buf.as_ptr().cast_mut(), buf.len()),
            PhantomData,
        )
    }

    /// The slice.
    #[inline]
    pub fn as_slice(&self) -> &'a [u8] {
        // SAFETY: the pointer and the length come from a `&'a [u8]`, and the
        // length was only ever reduced.
        unsafe { core::slice::from_raw_parts(self.0.ptr(), self.0.len()) }
    }
}

impl core::ops::Deref for IoSlice<'_> {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl fmt::Debug for IoSlice<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_slice(), f)
    }
}

/// A buffer to read into, for [`read_vectored`].
///
/// It is a `&mut [u8]` with the layout the system wants for vectored I/O:
/// see [`IoSlice`], including the limit on its length on Windows.
#[repr(transparent)]
pub struct IoSliceMut<'a>(sys::io::RawIoSlice, PhantomData<&'a mut [u8]>);

// SAFETY: an `IoSliceMut` is a `&mut [u8]`.
unsafe impl Send for IoSliceMut<'_> {}
// SAFETY: as above.
unsafe impl Sync for IoSliceMut<'_> {}

impl<'a> IoSliceMut<'a> {
    /// Wraps a slice.
    #[inline]
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self(
            sys::io::RawIoSlice::new(buf.as_mut_ptr(), buf.len()),
            PhantomData,
        )
    }

    /// The slice.
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        // SAFETY: the pointer and the length come from a `&'a mut [u8]`
        // that `self` holds, and the length was only ever reduced.
        unsafe { core::slice::from_raw_parts(self.0.ptr(), self.0.len()) }
    }

    /// The slice, mutably.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        // SAFETY: as in `as_slice`, and `self` is borrowed mutably.
        unsafe { core::slice::from_raw_parts_mut(self.0.ptr(), self.0.len()) }
    }
}

impl core::ops::Deref for IoSliceMut<'_> {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl core::ops::DerefMut for IoSliceMut<'_> {
    #[inline]
    fn deref_mut(&mut self) -> &mut [u8] {
        self.as_mut_slice()
    }
}

impl fmt::Debug for IoSliceMut<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_slice(), f)
    }
}