oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `thread` on macOS: the `pthread` extensions, `sched_yield` and `sysctl`.

use core::ffi::{c_char, c_int, c_void};

use crate::sys::cvt;
use crate::{Error, ErrorKind, Result};

/// `MAXTHREADNAMESIZE`: the size of a thread's name, with its NUL.
const NAME_SIZE: usize = 64;

pub(crate) const NAME_MAX: usize = NAME_SIZE - 1;

unsafe extern "C" {
    /// `pthread_t` is a pointer; null is the calling thread here.
    fn pthread_threadid_np(thread: *mut c_void, id: *mut u64) -> c_int;
    fn pthread_self() -> *mut c_void;
    /// Names the calling thread. Returns an error number.
    fn pthread_setname_np(name: *const c_char) -> c_int;
    /// Returns an error number.
    fn pthread_getname_np(thread: *mut c_void, name: *mut c_char, len: usize) -> c_int;
    fn sched_yield() -> c_int;
    fn sysctlbyname(
        name: *const c_char,
        old: *mut c_void,
        old_len: *mut usize,
        new: *mut c_void,
        new_len: usize,
    ) -> c_int;
}

pub(crate) fn id() -> u64 {
    let mut id = 0;
    // SAFETY: the function writes one `u64`; it cannot fail for the calling
    // thread.
    unsafe { pthread_threadid_np(core::ptr::null_mut(), &raw mut id) };
    id
}

pub(crate) fn yield_now() {
    // SAFETY: sched_yield takes nothing.
    unsafe { sched_yield() };
}

pub(crate) fn available_parallelism() -> Result<usize> {
    let mut count: c_int = 0;
    let mut len = size_of::<c_int>();
    // SAFETY: the name is NUL-terminated, and the function writes at most
    // `len` bytes to `count`: the value is an `int`.
    cvt(unsafe {
        sysctlbyname(
            c"hw.activecpu".as_ptr(),
            (&raw mut count).cast(),
            &raw mut len,
            core::ptr::null_mut(),
            0,
        )
    })?;
    usize::try_from(count).map_err(|_| ErrorKind::Other.into())
}

pub(crate) fn set_name(name: &str) -> Result<()> {
    // A name of `NAME_MAX` bytes at most, which the caller cut it to: the
    // last byte of the buffer is never written, and is the NUL the function
    // reads up to if nothing else is.
    let mut buf = [0u8; NAME_SIZE];
    buf[..NAME_MAX]
        .get_mut(..name.len())
        .ok_or(ErrorKind::InvalidInput)?
        .copy_from_slice(name.as_bytes());
    // SAFETY: the function reads a NUL-terminated string, and `buf` ends
    // with a NUL whatever the name is.
    match unsafe { pthread_setname_np(buf.as_ptr().cast()) } {
        0 => Ok(()),
        code => Err(Error::from_raw_os_error(code)),
    }
}

pub(crate) fn name(buf: &mut [u8]) -> Result<usize> {
    let mut name = [0u8; NAME_SIZE];
    // SAFETY: the function writes at most `NAME_SIZE` bytes, NUL included,
    // for the calling thread.
    match unsafe { pthread_getname_np(pthread_self(), name.as_mut_ptr().cast(), NAME_SIZE) } {
        0 => {}
        code => return Err(Error::from_raw_os_error(code)),
    }
    let len = name.iter().position(|&b| b == 0).unwrap_or(NAME_SIZE);
    buf.get_mut(..len)
        .ok_or(ErrorKind::BufferTooSmall)?
        .copy_from_slice(&name[..len]);
    Ok(len)
}