From faa31d944bbfeef13a7efd1e24ad25a1dbe6e95e Mon Sep 17 00:00:00 2001 From: pantonshire Date: Sun, 30 Apr 2023 14:34:23 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20shut=20down=20debouncer=20on=20drop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7eef0ec..1839dec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,9 @@ use std::{ sync::{Arc, Mutex, Condvar, mpsc}, time::Duration, - thread::{self, JoinHandle}, io, + thread::{self, JoinHandle}, + io, + panic, }; /// A debouncer for deduplicating groups of events which occur at a similar time. Upon receiving an @@ -9,7 +11,7 @@ use std::{ /// during which time any additional events will be considered part of the same group. Once it has /// finished waiting, it will emit a single event via a `mpsc` channel. pub struct Debouncer { - thread: JoinHandle<()>, + thread: Option>, controller: Arc>, } @@ -31,16 +33,28 @@ where move || debounce_thread(debounce_state, tx, debounce_time) })?; - Ok((Self { thread, controller }, rx)) + Ok((Self { thread: Some(thread), controller }, rx)) } +} +impl Debouncer { pub fn controller(&self) -> &Arc> { &self.controller } +} - pub fn close(self) -> thread::Result<()> { +impl Drop for Debouncer { + fn drop(&mut self) { self.controller().notify_shutdown(); - self.thread.join() + + let thread = self.thread + .take() + .expect("debouncer thread has already been shut down"); + + match thread.join() { + Ok(()) => (), + Err(err) => panic::resume_unwind(err), + } } }