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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#![deny(missing_docs)]
#![deny(warnings)]
pub use ipnet::IpNet;
use std::io::Result;
#[cfg(not(any(unix, windows)))]
compile_error!("Only Unix and Windows are supported");
#[cfg(not(any(target_os = "linux", windows)))]
mod fallback;
#[cfg(target_os = "linux")]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(not(any(target_os = "linux", windows)))]
use fallback as platform_impl;
#[cfg(target_os = "linux")]
use unix as platform_impl;
#[cfg(windows)]
use windows as platform_impl;
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum IfEvent {
Up(IpNet),
Down(IpNet),
}
#[derive(Debug)]
pub struct IfWatcher(platform_impl::IfWatcher);
impl IfWatcher {
pub async fn new() -> Result<Self> {
Ok(Self(platform_impl::IfWatcher::new().await?))
}
pub fn iter(&self) -> impl Iterator<Item = &IpNet> {
self.0.iter()
}
pub async fn next(&mut self) -> Result<IfEvent> {
self.0.next().await
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures_lite::future::poll_fn;
use std::{future::Future, pin::Pin, task::Poll};
#[test]
fn test_ip_watch() {
futures_lite::future::block_on(async {
let mut set = IfWatcher::new().await.unwrap();
poll_fn(|cx| loop {
let next = set.next();
futures_lite::pin!(next);
if let Poll::Ready(Ok(ev)) = Pin::new(&mut next).poll(cx) {
println!("Got event {:?}", ev);
continue;
}
return Poll::Ready(());
})
.await;
});
}
#[test]
fn test_is_send() {
futures_lite::future::block_on(async {
fn is_send<T: Send>(_: T) {}
is_send(IfWatcher::new());
is_send(IfWatcher::new().await.unwrap());
is_send(IfWatcher::new().await.unwrap().next());
});
}
}