extern crate libc;
use std::num::NonZeroUsize;
use self::libc::{kern_return_t, mach_msg_type_number_t, mach_port_t, thread_t};
const THREAD_STATE_MAX: i32 = 1296;
#[allow(non_camel_case_types)]
type task_inspect_t = mach_port_t;
#[allow(non_camel_case_types)]
type thread_array_t = [thread_t; THREAD_STATE_MAX as usize];
extern "C" {
fn task_threads(
target_task: task_inspect_t,
act_list: *mut thread_array_t,
act_listCnt: *mut mach_msg_type_number_t,
) -> kern_return_t;
}
pub(crate) fn num_threads() -> Option<NonZeroUsize> {
let mut thread_state = [0u32; THREAD_STATE_MAX as usize];
let mut thread_count = 0;
let result =
unsafe { task_threads(libc::mach_task_self(), &mut thread_state, &mut thread_count) };
if result == libc::KERN_SUCCESS {
NonZeroUsize::new(thread_count as usize)
} else {
None
}
}