From b8f61109f7d22a09458d78681155150f39a12269 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Fri, 25 Feb 2022 20:59:40 -0500 Subject: don't error when sending events during application shutdown --- src/shell/event.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) (limited to 'src/shell/event.rs') diff --git a/src/shell/event.rs b/src/shell/event.rs index ad14705..8f21081 100644 --- a/src/shell/event.rs +++ b/src/shell/event.rs @@ -10,13 +10,47 @@ pub enum Event { ClockTimer, } -pub struct Reader { +pub fn channel() -> (Writer, Reader) { + let (event_w, event_r) = tokio::sync::mpsc::unbounded_channel(); + (Writer::new(event_w), Reader::new(event_r)) +} + +#[derive(Clone)] +pub struct Writer(tokio::sync::mpsc::UnboundedSender); + +impl Writer { + pub fn new(event_w: tokio::sync::mpsc::UnboundedSender) -> Self { + Self(event_w) + } + + pub fn send(&self, event: Event) { + // the only time this should ever error is when the application is + // shutting down, at which point we don't actually care about any + // further dropped messages + #[allow(clippy::let_underscore_drop)] + let _ = self.0.send(event); + } +} + +pub struct Reader(std::sync::Arc); + +impl Reader { + pub fn new(input: tokio::sync::mpsc::UnboundedReceiver) -> Self { + Self(InnerReader::new(input)) + } + + pub async fn recv(&self) -> Option { + self.0.recv().await + } +} + +struct InnerReader { pending: tokio::sync::Mutex, cvar: tokio::sync::Notify, } -impl Reader { - pub fn new( +impl InnerReader { + fn new( mut input: tokio::sync::mpsc::UnboundedReceiver, ) -> std::sync::Arc { let this = Self { @@ -36,7 +70,7 @@ impl Reader { this } - pub async fn recv(&self) -> Option { + async fn recv(&self) -> Option { loop { let mut pending = self.pending.lock().await; if pending.has_event() { -- cgit v1.2.3-54-g00ecf