From 0ca5165b7329b67d71b7218c87fcfd72993322c2 Mon Sep 17 00:00:00 2001 From: alemi Date: Thu, 8 Aug 2024 21:55:52 +0200 Subject: [PATCH] feat: improve InternallyMutable --- src/buffer/tools.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/buffer/tools.rs b/src/buffer/tools.rs index f4a8fd8..17249f0 100644 --- a/src/buffer/tools.rs +++ b/src/buffer/tools.rs @@ -51,26 +51,38 @@ pub async fn select_buffer( /// wraps sender and receiver to allow mutable field with immutable ref #[derive(Debug)] -pub struct InternallyMutable { +pub struct InternallyMutable { getter: tokio::sync::watch::Receiver, setter: tokio::sync::watch::Sender, } -impl Default for InternallyMutable { +impl Default for InternallyMutable { fn default() -> Self { - let (tx, rx) = tokio::sync::watch::channel(T::default()); + Self::new(T::default()) + } +} + +impl InternallyMutable { + pub fn new(init: T) -> Self { + let (tx, rx) = tokio::sync::watch::channel(init); InternallyMutable { getter: rx, setter: tx, } } -} -impl InternallyMutable { pub fn set(&self, state: T) -> T { self.setter.send_replace(state) } + pub async fn wait(&self) { + let mut new = self.getter.clone(); + new.changed().await; // first time unlocks immediately + new.changed().await; + } +} + +impl InternallyMutable { pub fn get(&self) -> T { self.getter.borrow().clone() }