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
//! Handles to operating system objects.

use core::fmt;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;

use crate::sys;

/// The operating system's own handle type: a file descriptor (`i32`) on
/// Linux, macOS and WASI, a `HANDLE` (`*mut c_void`) on Windows.
///
/// Sockets are not handles on Windows: see [`net`](crate::net).
pub type RawHandle = sys::RawHandle;

/// An owned handle to an operating system object: an open file, a pipe, a
/// directory, a process... It is closed when dropped.
#[repr(transparent)]
pub struct OwnedHandle(RawHandle);

/// A handle borrowed from its owner.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BorrowedHandle<'a>(RawHandle, PhantomData<&'a OwnedHandle>);

// SAFETY: a handle names a kernel object, which any thread may use. (Windows
// handles are pointers in name only.)
unsafe impl Send for OwnedHandle {}
// SAFETY: as above.
unsafe impl Sync for OwnedHandle {}
// SAFETY: as above.
unsafe impl Send for BorrowedHandle<'_> {}
// SAFETY: as above.
unsafe impl Sync for BorrowedHandle<'_> {}

impl OwnedHandle {
    /// Takes ownership of a raw handle.
    ///
    /// # Safety
    ///
    /// `raw` must be an open handle that nothing else will close.
    #[inline]
    pub const unsafe fn from_raw(raw: RawHandle) -> Self {
        Self(raw)
    }

    /// The raw handle, still owned by `self`.
    #[inline]
    pub const fn as_raw(&self) -> RawHandle {
        self.0
    }

    /// Releases ownership: the caller is now responsible for closing it.
    #[inline]
    pub fn into_raw(self) -> RawHandle {
        ManuallyDrop::new(self).0
    }
}

impl Drop for OwnedHandle {
    fn drop(&mut self) {
        // SAFETY: the handle is open and owned by `self`. Like `std`, a
        // failure to close is ignored: there is nothing to do about it.
        unsafe { sys::close(self.0) };
    }
}

impl<'a> BorrowedHandle<'a> {
    /// Borrows a raw handle.
    ///
    /// # Safety
    ///
    /// `raw` must stay open for the lifetime `'a`.
    #[inline]
    pub const unsafe fn borrow_raw(raw: RawHandle) -> Self {
        Self(raw, PhantomData)
    }

    /// The raw handle.
    #[inline]
    pub const fn as_raw(self) -> RawHandle {
        self.0
    }
}

/// Types that hold a handle.
pub trait AsHandle {
    /// Borrows the handle.
    fn as_handle(&self) -> BorrowedHandle<'_>;
}

impl AsHandle for OwnedHandle {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        BorrowedHandle(self.0, PhantomData)
    }
}

impl AsHandle for BorrowedHandle<'_> {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        *self
    }
}

impl<T: AsHandle + ?Sized> AsHandle for &T {
    #[inline]
    fn as_handle(&self) -> BorrowedHandle<'_> {
        T::as_handle(self)
    }
}

impl fmt::Debug for OwnedHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("OwnedHandle").field(&self.0).finish()
    }
}

impl fmt::Debug for BorrowedHandle<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("BorrowedHandle").field(&self.0).finish()
    }
}

// Conversions with std's own handle types. fullrust is not `cfg(unix)` but
// has `std::os::fd` like Linux.
#[cfg(all(feature = "std", any(unix, target_os = "fullrust", target_os = "wasi")))]
mod std_impls {
    use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};

    use super::*;

    impl From<OwnedFd> for OwnedHandle {
        fn from(fd: OwnedFd) -> Self {
            Self(fd.into_raw_fd())
        }
    }

    impl From<OwnedHandle> for OwnedFd {
        fn from(handle: OwnedHandle) -> Self {
            // SAFETY: the handle is an open descriptor whose ownership moves.
            unsafe { Self::from_raw_fd(handle.into_raw()) }
        }
    }

    impl<'a> From<BorrowedFd<'a>> for BorrowedHandle<'a> {
        fn from(fd: BorrowedFd<'a>) -> Self {
            Self(fd.as_raw_fd(), PhantomData)
        }
    }

    impl<'a> From<BorrowedHandle<'a>> for BorrowedFd<'a> {
        fn from(handle: BorrowedHandle<'a>) -> Self {
            // SAFETY: the descriptor stays open for 'a.
            unsafe { Self::borrow_raw(handle.0) }
        }
    }

    impl AsFd for OwnedHandle {
        fn as_fd(&self) -> BorrowedFd<'_> {
            self.as_handle().into()
        }
    }

    impl AsFd for BorrowedHandle<'_> {
        fn as_fd(&self) -> BorrowedFd<'_> {
            (*self).into()
        }
    }
}

#[cfg(all(feature = "std", windows))]
mod std_impls {
    use std::os::windows::io as stdio;
    use std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle};

    use super::*;

    impl From<stdio::OwnedHandle> for OwnedHandle {
        fn from(handle: stdio::OwnedHandle) -> Self {
            Self(handle.into_raw_handle())
        }
    }

    impl From<OwnedHandle> for stdio::OwnedHandle {
        fn from(handle: OwnedHandle) -> Self {
            // SAFETY: the handle is open and its ownership moves.
            unsafe { Self::from_raw_handle(handle.into_raw()) }
        }
    }

    impl<'a> From<stdio::BorrowedHandle<'a>> for BorrowedHandle<'a> {
        fn from(handle: stdio::BorrowedHandle<'a>) -> Self {
            Self(handle.as_raw_handle(), PhantomData)
        }
    }

    impl<'a> From<BorrowedHandle<'a>> for stdio::BorrowedHandle<'a> {
        fn from(handle: BorrowedHandle<'a>) -> Self {
            // SAFETY: the handle stays open for 'a.
            unsafe { Self::borrow_raw(handle.0) }
        }
    }

    impl stdio::AsHandle for OwnedHandle {
        fn as_handle(&self) -> stdio::BorrowedHandle<'_> {
            AsHandle::as_handle(self).into()
        }
    }

    impl stdio::AsHandle for BorrowedHandle<'_> {
        fn as_handle(&self) -> stdio::BorrowedHandle<'_> {
            (*self).into()
        }
    }
}