From 70b1b2266d9d7ffead9ba764dd9a1c24cb24c191 Mon Sep 17 00:00:00 2001 From: pantonshire Date: Wed, 16 Aug 2023 09:34:13 +0100 Subject: [PATCH] pre-written fold functions for convenience --- src/fold.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 20 ++---------------- 2 files changed, 63 insertions(+), 18 deletions(-) create mode 100644 src/fold.rs diff --git a/src/fold.rs b/src/fold.rs new file mode 100644 index 0000000..2bfc315 --- /dev/null +++ b/src/fold.rs @@ -0,0 +1,61 @@ +//! Pre-written fold functions which can be passed to [`Debouncer::new`](crate::Debouncer::new) to +//! specify how raw events should be combined into a single debounced event. + +/// A fold function which combines events of type `T` into a `Vec` by pushing them. +/// +/// ``` +/// # fn main() -> Result<(), Box> { +/// # use treacle::{Debouncer, fold::fold_vec_push}; +/// use std::{time::Duration, thread}; +/// +/// let (debouncer, rx) = Debouncer::new( +/// Duration::from_millis(100), +/// fold_vec_push:: +/// )?; +/// +/// debouncer.debounce(4); +/// debouncer.debounce(5); +/// +/// thread::sleep(Duration::from_millis(150)); +/// debouncer.debounce(3); +/// debouncer.debounce(2); +/// debouncer.debounce(1); +/// +/// assert_eq!(rx.recv().unwrap(), vec![4, 5]); +/// assert_eq!(rx.recv().unwrap(), vec![3, 2, 1]); +/// # Ok(()) +/// # } +/// ``` +pub fn fold_vec_push(acc: Option>, e: T) -> Vec { + let mut acc = acc.unwrap_or_default(); + acc.push(e); + acc +} + +/// A fold function which discards all raw event data. Useful when you are just interested in the +/// existence of events and not any data associated with them. +/// +/// ``` +/// # fn main() -> Result<(), Box> { +/// # use treacle::{Debouncer, fold::fold_unit}; +/// use std::{time::Duration, thread}; +/// +/// let (debouncer, rx) = Debouncer::new( +/// Duration::from_millis(100), +/// fold_unit:: +/// )?; +/// +/// debouncer.debounce(4); +/// debouncer.debounce(5); +/// +/// thread::sleep(Duration::from_millis(150)); +/// debouncer.debounce(3); +/// debouncer.debounce(2); +/// debouncer.debounce(1); +/// +/// assert_eq!(rx.recv().unwrap(), ()); +/// assert_eq!(rx.recv().unwrap(), ()); +/// # Ok(()) +/// # } +/// ``` +pub fn fold_unit(_acc: Option<()>, _e: T) {} diff --git a/src/lib.rs b/src/lib.rs index c92718b..0e58337 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +pub mod fold; + use std::{ sync::{Arc, Mutex, Condvar, mpsc}, time::Duration, @@ -166,24 +168,6 @@ where } } -// impl Debouncer> { -// #[inline] -// pub fn debounce_push(&self, event_data: T) { -// self.debounce(event_data, |acc, event_data| { -// let mut acc = acc.unwrap_or_default(); -// acc.push(event_data); -// acc -// }); -// } -// } - -// impl Debouncer<()> { -// #[inline] -// pub fn debounce_unit(&self) { -// self.debounce((), |_acc, _event_data| ()); -// } -// } - impl Drop for Debouncer { fn drop(&mut self) { self.controller.notify_shutdown();