use core::ffi::{c_char, c_int, c_void};
use crate::sys::cvt;
use crate::{Error, ErrorKind, Result};
const NAME_SIZE: usize = 64;
pub(crate) const NAME_MAX: usize = NAME_SIZE - 1;
unsafe extern "C" {
fn pthread_threadid_np(thread: *mut c_void, id: *mut u64) -> c_int;
fn pthread_self() -> *mut c_void;
fn pthread_setname_np(name: *const c_char) -> c_int;
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;
unsafe { pthread_threadid_np(core::ptr::null_mut(), &raw mut id) };
id
}
pub(crate) fn yield_now() {
unsafe { sched_yield() };
}
pub(crate) fn available_parallelism() -> Result<usize> {
let mut count: c_int = 0;
let mut len = size_of::<c_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<()> {
let mut buf = [0u8; NAME_SIZE];
buf[..NAME_MAX]
.get_mut(..name.len())
.ok_or(ErrorKind::InvalidInput)?
.copy_from_slice(name.as_bytes());
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];
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)
}