Skip to main content

notify_types/
debouncer_mini.rs

1use std::path::PathBuf;
2
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6/// A debounced event kind.
7#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
8#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9#[non_exhaustive]
10pub enum DebouncedEventKind {
11    /// No precise events
12    Any,
13    /// Event but debounce timed out (for example continuous writes)
14    AnyContinuous,
15}
16
17/// A debounced event.
18///
19/// Does not emit any specific event type on purpose, only distinguishes between an any event and a continuous any event.
20#[derive(Clone, Debug, Eq, Hash, PartialEq)]
21#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
22pub struct DebouncedEvent {
23    /// Event path
24    pub path: PathBuf,
25    /// Event kind
26    pub kind: DebouncedEventKind,
27}
28
29impl DebouncedEvent {
30    #[inline(always)]
31    #[must_use]
32    pub fn new(path: PathBuf, kind: DebouncedEventKind) -> Self {
33        Self { path, kind }
34    }
35}
36
37/// A notification from the mini debouncer.
38///
39/// Handle [`Self::Rescan`] before applying path or event-kind filters to [`Self::Events`].
40#[derive(Clone, Debug, Eq, Hash, PartialEq)]
41#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
42pub enum DebouncedEventBatch {
43    /// A batch of debounced path changes.
44    Events(Vec<DebouncedEvent>),
45    /// Events were missed or can no longer describe the current filesystem state reliably.
46    ///
47    /// Refresh any cached filesystem state for all watched paths. This notification applies
48    /// to the entire watcher, regardless of any paths attached to the original event.
49    /// It is delivered without waiting for the debounce timeout. Pending path changes
50    /// remain queued and are delivered according to their usual debounce deadlines.
51    Rescan,
52}
53
54#[cfg(all(test, feature = "serde"))]
55mod tests {
56    use super::*;
57    use serde_json::json;
58
59    #[test]
60    fn serialize_and_deserialize_batches() {
61        for (batch, json) in [
62            (DebouncedEventBatch::Rescan, json!("Rescan")),
63            (
64                DebouncedEventBatch::Events(vec![
65                    DebouncedEvent::new("file.txt".into(), DebouncedEventKind::Any),
66                    DebouncedEvent::new("active.txt".into(), DebouncedEventKind::AnyContinuous),
67                ]),
68                json!({"Events": [
69                    {"path": "file.txt", "kind": "Any"},
70                    {"path": "active.txt", "kind": "AnyContinuous"},
71                ]}),
72            ),
73        ] {
74            assert_eq!(serde_json::to_value(&batch).unwrap(), json);
75            assert_eq!(
76                serde_json::from_value::<DebouncedEventBatch>(json).unwrap(),
77                batch,
78            );
79        }
80    }
81}