use std::num::NonZeroU8;
use std::{fmt, ops};
#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)]
pub struct Interest(NonZeroU8);
const READABLE: u8 = 0b0001;
const WRITABLE: u8 = 0b0010;
const AIO: u8 = 0b0100;
const LIO: u8 = 0b1000;
const PRIORITY: u8 = 0b10000;
impl Interest {
pub const READABLE: Interest = Interest(unsafe { NonZeroU8::new_unchecked(READABLE) });
pub const WRITABLE: Interest = Interest(unsafe { NonZeroU8::new_unchecked(WRITABLE) });
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "visionos",
target_os = "watchos",
))]
pub const AIO: Interest = Interest(unsafe { NonZeroU8::new_unchecked(AIO) });
#[cfg(target_os = "freebsd")]
pub const LIO: Interest = Interest(unsafe { NonZeroU8::new_unchecked(LIO) });
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const PRIORITY: Interest = Interest(unsafe { NonZeroU8::new_unchecked(PRIORITY) });
#[allow(clippy::should_implement_trait)]
#[must_use = "this returns the result of the operation, without modifying the original"]
pub const fn add(self, other: Interest) -> Interest {
Interest(unsafe { NonZeroU8::new_unchecked(self.0.get() | other.0.get()) })
}
#[must_use = "this returns the result of the operation, without modifying the original"]
pub fn remove(self, other: Interest) -> Option<Interest> {
NonZeroU8::new(self.0.get() & !other.0.get()).map(Interest)
}
#[must_use]
pub const fn is_readable(self) -> bool {
(self.0.get() & READABLE) != 0
}
#[must_use]
pub const fn is_writable(self) -> bool {
(self.0.get() & WRITABLE) != 0
}
#[must_use]
pub const fn is_aio(self) -> bool {
(self.0.get() & AIO) != 0
}
#[must_use]
pub const fn is_lio(self) -> bool {
(self.0.get() & LIO) != 0
}
#[must_use]
pub const fn is_priority(self) -> bool {
(self.0.get() & PRIORITY) != 0
}
}
impl ops::BitOr for Interest {
type Output = Self;
#[inline]
fn bitor(self, other: Self) -> Self {
self.add(other)
}
}
impl ops::BitOrAssign for Interest {
#[inline]
fn bitor_assign(&mut self, other: Self) {
self.0 = (*self | other).0;
}
}
impl fmt::Debug for Interest {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut one = false;
if self.is_readable() {
if one {
write!(fmt, " | ")?
}
write!(fmt, "READABLE")?;
one = true
}
if self.is_writable() {
if one {
write!(fmt, " | ")?
}
write!(fmt, "WRITABLE")?;
one = true
}
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "visionos",
target_os = "watchos",
))]
{
if self.is_aio() {
if one {
write!(fmt, " | ")?
}
write!(fmt, "AIO")?;
one = true
}
}
#[cfg(target_os = "freebsd")]
{
if self.is_lio() {
if one {
write!(fmt, " | ")?
}
write!(fmt, "LIO")?;
one = true
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
if self.is_priority() {
if one {
write!(fmt, " | ")?
}
write!(fmt, "PRIORITY")?;
one = true
}
}
debug_assert!(one, "printing empty interests");
Ok(())
}
}