#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use crate::error::Error;
use crate::syscall;
use crate::types::{EventFdFlags, RawFd};
use core::mem;
pub struct EventFd {
fd: RawFd,
}
impl EventFd {
pub fn new(initval: u32) -> Result<Self, Error> {
let fd = syscall::eventfd2(initval, EventFdFlags::NONBLOCK.bits())? as RawFd;
Ok(Self { fd })
}
pub fn with_flags(initval: u32, flags: EventFdFlags) -> Result<Self, Error> {
let fd = syscall::eventfd2(initval, flags.bits())? as RawFd;
Ok(Self { fd })
}
#[inline]
#[must_use]
pub const fn fd(&self) -> RawFd {
self.fd
}
#[inline]
#[must_use]
pub const fn into_fd(self) -> RawFd {
let fd = self.fd;
mem::forget(self);
fd
}
pub fn write(&self, value: u64) -> Result<(), Error> {
let buf = value.to_ne_bytes();
syscall::write(self.fd as usize, buf.as_ptr(), 8)?;
Ok(())
}
pub fn read(&self) -> Result<u64, Error> {
let mut buf = [0u8; 8];
syscall::read(self.fd as usize, buf.as_mut_ptr(), 8)?;
Ok(u64::from_ne_bytes(buf))
}
pub fn close(self) -> Result<(), Error> {
let fd = self.fd;
mem::forget(self);
syscall::close(fd as usize)
}
}
impl Drop for EventFd {
fn drop(&mut self) {
let _ = syscall::close(self.fd as usize);
}
}