allow untracking on write guards to support maybe_update

This commit is contained in:
Greg Johnston 2024-06-03 08:05:20 -04:00
parent 0a99a378aa
commit 17f1d25d03
2 changed files with 17 additions and 9 deletions

View File

@ -238,7 +238,7 @@ pub struct WriteGuard<'a, S, G>
where
S: Trigger,
{
pub(crate) triggerable: &'a S,
pub(crate) triggerable: Option<&'a S>,
pub(crate) guard: Option<G>,
}
@ -248,10 +248,14 @@ where
{
pub fn new(triggerable: &'a S, guard: G) -> Self {
Self {
triggerable,
triggerable: Some(triggerable),
guard: Some(guard),
}
}
pub fn untrack(&mut self) {
self.triggerable.take();
}
}
impl<'a, S, G> Deref for WriteGuard<'a, S, G>
@ -322,6 +326,8 @@ where
drop(self.guard.take());
// then, notify about a change
self.triggerable.trigger();
if let Some(triggerable) = self.triggerable {
triggerable.trigger();
}
}
}

View File

@ -365,19 +365,21 @@ pub trait Update {
impl<T> Update for T
where
T: UpdateUntracked + Trigger,
T: Writeable,
{
type Value = <Self as UpdateUntracked>::Value;
type Value = <Self as Writeable>::Value;
#[track_caller]
fn try_maybe_update<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> (bool, U),
) -> Option<U> {
let (did_update, val) = self.try_update_untracked(fun)?;
if did_update {
self.trigger();
let mut lock = self.try_write()?;
let (did_update, val) = fun(&mut *lock);
if !did_update {
lock.untrack();
}
drop(lock);
Some(val)
}
}
@ -398,7 +400,7 @@ where
#[track_caller]
fn set(&self, value: impl Into<Self::Value>) {
self.update(|n| *n = value.into());
self.try_update(|n| *n = value.into());
}
#[track_caller]