1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::convert::TryFrom;
use std::io;
use std::mem::size_of;
use std::sync::Arc;
use anyhow::ensure;
use anyhow::Context;
use base::SafeDescriptor;
use super::io_driver;
#[derive(Debug)]
pub struct Event {
fd: Arc<SafeDescriptor>,
}
impl Event {
pub fn new() -> anyhow::Result<Event> {
base::Event::new()
.map_err(io::Error::from)
.context("failed to create eventfd")
.and_then(Event::try_from)
}
pub async fn next_val(&self) -> anyhow::Result<u64> {
let mut buf = 0u64.to_ne_bytes();
let count = io_driver::read(&self.fd, &mut buf, None).await?;
ensure!(
count == size_of::<u64>(),
io::Error::from(io::ErrorKind::UnexpectedEof)
);
Ok(u64::from_ne_bytes(buf))
}
pub async fn notify(&self) -> anyhow::Result<()> {
let buf = 1u64.to_ne_bytes();
let count = io_driver::write(&self.fd, &buf, None).await?;
ensure!(
count == size_of::<u64>(),
io::Error::from(io::ErrorKind::WriteZero)
);
Ok(())
}
pub fn try_clone(&self) -> anyhow::Result<Event> {
self.fd
.try_clone()
.map(|fd| Event { fd: Arc::new(fd) })
.map_err(io::Error::from)
.map_err(From::from)
}
}
impl TryFrom<base::Event> for Event {
type Error = anyhow::Error;
fn try_from(evt: base::Event) -> anyhow::Result<Event> {
io_driver::prepare(&evt)?;
Ok(Event {
fd: Arc::new(SafeDescriptor::from(evt)),
})
}
}