mount_watcher/callback.rs
1//! Callback helpers.
2
3use std::time::Duration;
4
5use crate::{MountEvent, WatchControl};
6
7/// How to handle the initial event, which contains the list of mount points that
8/// have been detected when the watcher has started.
9pub enum CoalesceInitial {
10 /// Coalesce the initial event like any other event.
11 Coalesce,
12 /// Do not coalesce the initial event, only the subsequent events.
13 PassImmediately,
14}
15
16/// Returns a closure that always coalesce the events with the given delay.
17///
18/// By passing it to [`MountWatcher::new`](crate::MountWatcher::new), you will only
19/// get events at the specified time interval.
20///
21/// # Initial event
22///
23/// The first, initial event is handled according to the value of `initial_event`.
24/// It can be useful to use `PassImmediately` to get a first list of the mount points
25/// as soon as possible.
26///
27/// # Example
28///
29/// ```no_run
30/// use std::time::Duration;
31/// use mount_watcher::MountWatcher;
32/// use mount_watcher::callback::{coalesce, CoalesceInitial};
33///
34/// let watch = MountWatcher::new(
35/// coalesce(
36/// Duration::from_secs(5),
37/// CoalesceInitial::PassImmediately,
38/// |event| {
39/// todo!("handle event")
40/// }
41/// )
42/// );
43/// ```
44pub fn coalesce<F: FnMut(MountEvent) -> WatchControl + Send + 'static>(
45 delay: Duration,
46 initial_event: CoalesceInitial,
47 mut f: F,
48) -> impl FnMut(MountEvent) -> WatchControl + Send + 'static {
49 move |event| {
50 let coalesce = match initial_event {
51 CoalesceInitial::Coalesce => !event.coalesced,
52 CoalesceInitial::PassImmediately => !(event.coalesced || event.initial),
53 };
54 if coalesce {
55 WatchControl::Coalesce { delay }
56 } else {
57 f(event)
58 }
59 }
60}