Skip to content

Commit 1d4669c

Browse files
Implement MacOS (#4)
1 parent 7c1fc92 commit 1d4669c

File tree

4 files changed

+37
-3
lines changed

4 files changed

+37
-3
lines changed

.github/workflows/build.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ jobs:
3636
# triple: x86_64-pc-windows-gnu
3737
- name: Linux
3838
triple: x86_64-unknown-linux-gnu
39-
# - name: macOS
40-
# triple: x86_64-apple-darwin
39+
- name: macOS
40+
triple: x86_64-apple-darwin
4141
- name: FreeBSD
4242
triple: x86_64-unknown-freebsd
4343

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ targets = ["x86_64-unknown-linux-gnu"]
1414

1515
[dependencies]
1616

17-
[target.'cfg(target_os = "freebsd")'.dependencies]
17+
[target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies]
1818
libc = "0.2.107"

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::num::NonZeroUsize;
44

55
#[cfg_attr(target_os = "linux", path = "linux.rs")]
66
#[cfg_attr(target_os = "freebsd", path = "freebsd.rs")]
7+
#[cfg_attr(target_os = "macos", path = "macos.rs")]
78
mod imp;
89

910
/// Obtain the number of threads currently part of the active process. Returns `None` if the number

src/macos.rs

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
extern crate libc;
2+
3+
use std::mem;
4+
use std::num::NonZeroUsize;
5+
6+
const PROC_TASKINFO_SIZE: usize = mem::size_of::<libc::proc_taskinfo>();
7+
8+
pub(crate) fn num_threads() -> Option<NonZeroUsize> {
9+
let buffer = unsafe { libc::malloc(PROC_TASKINFO_SIZE) };
10+
if buffer.is_null() {
11+
return None;
12+
}
13+
14+
let result = unsafe {
15+
libc::proc_pidinfo(
16+
libc::getpid(),
17+
libc::PROC_PIDTASKINFO,
18+
0,
19+
buffer,
20+
PROC_TASKINFO_SIZE as libc::c_int,
21+
)
22+
};
23+
if result != PROC_TASKINFO_SIZE as libc::c_int {
24+
return None;
25+
}
26+
27+
let pti = buffer as *mut libc::proc_taskinfo;
28+
// Safety: `malloc`ed memory is aligned for repr(C) structs, so dereference is safe.
29+
let num_threads = NonZeroUsize::new(unsafe { pti.as_ref() }?.pti_threadnum as usize);
30+
31+
unsafe { libc::free(pti as *mut libc::c_void) };
32+
num_threads
33+
}

0 commit comments

Comments
 (0)