use fibers::sync::mpsc;
use futures::{Async, Poll, Stream};
use {Error, EventMask, InotifyEvent, InotifyServiceHandle, Result};
pub type WatcherId = usize;
#[derive(Debug)]
pub struct Watcher {
id: WatcherId,
service: InotifyServiceHandle,
event_rx: mpsc::Receiver<Result<WatcherEvent>>,
eos: bool,
}
impl Watcher {
pub(crate) fn new(
id: WatcherId,
service: InotifyServiceHandle,
event_rx: mpsc::Receiver<Result<WatcherEvent>>,
) -> Self {
Watcher {
id,
service,
event_rx,
eos: false,
}
}
}
impl Stream for Watcher {
type Item = WatcherEvent;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if self.eos {
return Ok(Async::Ready(None));
}
match self.event_rx.poll().expect("Never fails") {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(None) => Ok(Async::Ready(None)),
Async::Ready(Some(result)) => {
let event = track!(result)?;
if let WatcherEvent::Notified(ref e) = event {
self.eos = e.mask.contains(EventMask::IGNORED);
}
Ok(Async::Ready(Some(event)))
}
}
}
}
impl Drop for Watcher {
fn drop(&mut self) {
self.service.deregister_watcher(self.id);
}
}
#[derive(Debug, Clone)]
pub enum WatcherEvent {
StartWatching,
RestartWatching,
Notified(InotifyEvent),
}