use crate::pid::Pid;
use crate::{backend, io};
use core::{fmt, hash};
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct CpuSet {
cpu_set: backend::thread::types::RawCpuSet,
}
impl CpuSet {
pub const MAX_CPU: usize = backend::thread::types::CPU_SETSIZE;
#[inline]
pub fn new() -> Self {
Self {
cpu_set: backend::thread::types::raw_cpu_set_new(),
}
}
#[inline]
pub fn is_set(&self, field: usize) -> bool {
backend::thread::cpu_set::CPU_ISSET(field, &self.cpu_set)
}
#[inline]
pub fn set(&mut self, field: usize) {
backend::thread::cpu_set::CPU_SET(field, &mut self.cpu_set)
}
#[inline]
pub fn unset(&mut self, field: usize) {
backend::thread::cpu_set::CPU_CLR(field, &mut self.cpu_set)
}
#[cfg(linux_kernel)]
#[inline]
pub fn count(&self) -> u32 {
backend::thread::cpu_set::CPU_COUNT(&self.cpu_set)
}
#[inline]
pub fn clear(&mut self) {
backend::thread::cpu_set::CPU_ZERO(&mut self.cpu_set)
}
}
impl Default for CpuSet {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for CpuSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CpuSet {{")?;
let mut first = true;
for i in 0..Self::MAX_CPU {
if self.is_set(i) {
if first {
write!(f, " ")?;
first = false;
} else {
write!(f, ", ")?;
}
write!(f, "cpu{}", i)?;
}
}
write!(f, " }}")
}
}
impl hash::Hash for CpuSet {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
for i in 0..Self::MAX_CPU {
self.is_set(i).hash(state);
}
}
}
impl Eq for CpuSet {}
impl PartialEq for CpuSet {
fn eq(&self, other: &Self) -> bool {
backend::thread::cpu_set::CPU_EQUAL(&self.cpu_set, &other.cpu_set)
}
}
#[inline]
pub fn sched_setaffinity(pid: Option<Pid>, cpuset: &CpuSet) -> io::Result<()> {
backend::thread::syscalls::sched_setaffinity(pid, &cpuset.cpu_set)
}
#[inline]
pub fn sched_getaffinity(pid: Option<Pid>) -> io::Result<CpuSet> {
let mut cpuset = CpuSet::new();
backend::thread::syscalls::sched_getaffinity(pid, &mut cpuset.cpu_set).and(Ok(cpuset))
}
#[cfg(any(linux_kernel, target_os = "dragonfly"))]
#[inline]
pub fn sched_getcpu() -> usize {
backend::thread::syscalls::sched_getcpu()
}