dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::os::fd::{self, AsRawFd as _};

use crate::{Errno, kernel};

/// Fallible descriptor decoding preserving the standard ownership contract.
pub trait Adopt: fd::FromRawFd + Sized {
    /// # Safety
    /// `raw` is -1 or transfers one live descriptor; failure leaves this thread's
    /// positive errno unchanged for `S` to read.
    unsafe fn try_adopt<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
        raw: fd::RawFd,
    ) -> Result<Self, E> {
        // SAFETY: the caller retains the native return and unchanged failure errno.
        let value = unsafe { kernel::raw::Status::new(raw).try_value::<S, E>() }?;
        // SAFETY: the nonnegative syscall result transfers this descriptor.
        Ok(unsafe { Self::from_raw_fd(value.get()) })
    }
}

impl<T: fd::FromRawFd> Adopt for T {}

pub(crate) fn write(file: fd::BorrowedFd<'_>, input: &[u8]) -> libc::ssize_t {
    // SAFETY: the borrowed descriptor and input remain live through this write.
    unsafe { libc::write(file.as_raw_fd(), input.as_ptr().cast(), input.len()) }
}