dope-uring 0.76.0

Owned io_uring backend for dope
Documentation
use std::mem;

use dope_sys::{
    Errno, kernel,
    thread::{Thread, affinity},
};
use o3::base::num::bounded;

use crate::{Backend, system};

impl Thread for Backend {
    type Timer = system::Timer;
    type Receiver = system::ffi::Receiver;
    type Cpus = system::ffi::Cpus;

    fn current() -> Result<Self::Cpus, affinity::Error> {
        // SAFETY: zero gives the kernel initialized storage even when the CPU
        // set representation contains padding.
        let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
        // SAFETY: mask points to writable storage of the exact size supplied.
        let result =
            unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut mask) };
        // SAFETY: sched_getaffinity returns zero or -1 with errno.
        unsafe { kernel::raw::Status::new(result).try_zero::<Backend, Errno>() }
            .map_err(affinity::Error::Current)?;
        // SAFETY: the mask was initialized and its native population fits system::ffi::Cpus::LIMIT.
        let count = unsafe { libc::CPU_COUNT(&mask) } as u16;
        Ok(system::ffi::Cpus {
            mask,
            indices: 0..system::ffi::Cpus::LIMIT,
            remaining: count,
        })
    }

    fn bind(cpu: affinity::raw::Cpu) -> Result<(), affinity::Error> {
        const MAX: u32 = system::ffi::Cpus::LIMIT as u32 - 1;
        let index = bounded::raw::U32::<0, MAX>::new(u32::from(cpu.raw())).ok_or(
            affinity::Error::BindingRange {
                cpu,
                maximum: MAX as u16,
            },
        )?;
        // SAFETY: zero is the empty set.
        let mut mask: libc::cpu_set_t = unsafe { mem::zeroed() };
        // SAFETY: index retains this native mask's admitted bound and mask is initialized.
        unsafe { libc::CPU_SET(index.into_usize(), &mut mask) };
        // SAFETY: mask is an initialized cpu_set_t of the exact ABI size.
        let result =
            unsafe { libc::sched_setaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mask) };
        // SAFETY: sched_setaffinity returns zero or -1 with errno.
        unsafe { kernel::raw::Status::new(result).try_zero::<Backend, Errno>() }
            .map_err(|fault| affinity::Error::Bind { cpu, fault })
    }
}