diff --git a/packages/signals/src/comparer.rs b/packages/signals/src/comparer.rs index e8954ee9d..e9ca981d6 100644 --- a/packages/signals/src/comparer.rs +++ b/packages/signals/src/comparer.rs @@ -1,6 +1,7 @@ use crate::write::Writable; use std::hash::Hash; +use crate::read::Readable; use dioxus_core::prelude::*; use generational_box::{Storage, UnsyncStorage}; diff --git a/packages/signals/src/effect.rs b/packages/signals/src/effect.rs index c8fb84258..3c7d9d606 100644 --- a/packages/signals/src/effect.rs +++ b/packages/signals/src/effect.rs @@ -1,3 +1,4 @@ +use crate::write::*; use core::{self, fmt::Debug}; use dioxus_core::prelude::*; use futures_channel::mpsc::UnboundedSender; @@ -92,7 +93,7 @@ pub(crate) struct EffectInner { impl EffectInner { pub(crate) fn new(callback: Box) -> CopyValue { - let copy = CopyValue::invalid(); + let mut copy = CopyValue::invalid(); let inner = EffectInner { callback: Box::new(callback), id: copy.id(), diff --git a/packages/signals/src/global/memo.rs b/packages/signals/src/global/memo.rs index b34eff989..23284f8ec 100644 --- a/packages/signals/src/global/memo.rs +++ b/packages/signals/src/global/memo.rs @@ -51,7 +51,7 @@ impl GlobalMemo { } } -impl Readable for GlobalMemo { +impl crate::ReadableRef for GlobalMemo { type Ref = generational_box::GenerationalRef>; fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref { @@ -64,7 +64,9 @@ impl Readable for GlobalMemo { ) -> Option> { ::try_map(ref_, f) } +} +impl Readable for GlobalMemo { #[track_caller] fn read(&self) -> Self::Ref { self.signal().read() diff --git a/packages/signals/src/global/signal.rs b/packages/signals/src/global/signal.rs index e6896d399..bc3698149 100644 --- a/packages/signals/src/global/signal.rs +++ b/packages/signals/src/global/signal.rs @@ -1,5 +1,7 @@ use crate::read::Readable; use crate::write::Writable; +use crate::WritableRef; +use crate::Write; use dioxus_core::prelude::{IntoAttributeValue, ScopeId}; use generational_box::{AnyStorage, GenerationalRef, UnsyncStorage}; use std::{cell::Ref, mem::MaybeUninit, ops::Deref}; @@ -68,7 +70,7 @@ impl GlobalSignal { } } -impl Readable for GlobalSignal { +impl crate::ReadableRef for GlobalSignal { type Ref = generational_box::GenerationalRef>; fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref { @@ -81,7 +83,9 @@ impl Readable for GlobalSignal { ) -> Option> { ::try_map(ref_, f) } +} +impl Readable for GlobalSignal { #[track_caller] fn read(&self) -> Self::Ref { self.signal().read() @@ -93,6 +97,31 @@ impl Readable for GlobalSignal { } } +impl WritableRef for GlobalSignal { + type Mut = Write; + + fn map_mut &mut U>( + ref_: Self::Mut, + f: F, + ) -> Self::Mut { + Write::map(ref_, f) + } + + fn try_map_mut Option<&mut U>>( + ref_: Self::Mut, + f: F, + ) -> Option> { + Write::filter_map(ref_, f) + } +} + +impl Writable for GlobalSignal { + #[track_caller] + fn try_write(&self) -> Result, generational_box::BorrowMutError> { + self.signal().try_write() + } +} + impl IntoAttributeValue for GlobalSignal where T: Clone + IntoAttributeValue, diff --git a/packages/signals/src/impls.rs b/packages/signals/src/impls.rs index cf2069814..12d11d21e 100644 --- a/packages/signals/src/impls.rs +++ b/packages/signals/src/impls.rs @@ -1,8 +1,9 @@ use crate::read::Readable; +use crate::read::ReadableVecExt; use crate::rt::CopyValue; use crate::signal::{Signal, Write}; use crate::write::Writable; -use crate::{GlobalMemo, GlobalSignal, ReadOnlySignal, SignalData}; +use crate::{GlobalMemo, GlobalSignal, ReadOnlySignal, ReadableValueIterator, SignalData}; use generational_box::{AnyStorage, Storage}; use generational_box::{GenerationalRef, UnsyncStorage}; @@ -134,194 +135,15 @@ macro_rules! write_impls { self.with(|v| *v / rhs) } } - - write_vec_impls!($ty, S: $vec_bound); - }; -} - -macro_rules! write_vec_impls { - ($ty:ident $(, $vec_bound_ty:ident: $vec_bound:path)?) => { - impl $ty $(, $vec_bound_ty)?> { - /// Pushes a new value to the end of the vector. - #[track_caller] - pub fn push(&mut self, value: T) { - self.with_mut(|v| v.push(value)) - } - - /// Pops the last value from the vector. - #[track_caller] - pub fn pop(&mut self) -> Option { - self.with_mut(|v| v.pop()) - } - - /// Inserts a new value at the given index. - #[track_caller] - pub fn insert(&mut self, index: usize, value: T) { - self.with_mut(|v| v.insert(index, value)) - } - - /// Removes the value at the given index. - #[track_caller] - pub fn remove(&mut self, index: usize) -> T { - self.with_mut(|v| v.remove(index)) - } - - /// Clears the vector, removing all values. - #[track_caller] - pub fn clear(&mut self) { - self.with_mut(|v| v.clear()) - } - - /// Extends the vector with the given iterator. - #[track_caller] - pub fn extend(&mut self, iter: impl IntoIterator) { - self.with_mut(|v| v.extend(iter)) - } - - /// Truncates the vector to the given length. - #[track_caller] - pub fn truncate(&mut self, len: usize) { - self.with_mut(|v| v.truncate(len)) - } - - /// Swaps two values in the vector. - #[track_caller] - pub fn swap_remove(&mut self, index: usize) -> T { - self.with_mut(|v| v.swap_remove(index)) - } - - /// Retains only the values that match the given predicate. - #[track_caller] - pub fn retain(&mut self, f: impl FnMut(&T) -> bool) { - self.with_mut(|v| v.retain(f)) - } - - /// Splits the vector into two at the given index. - #[track_caller] - pub fn split_off(&mut self, at: usize) -> Vec { - self.with_mut(|v| v.split_off(at)) - } - } }; } read_impls!(CopyValue, S: Storage, S: Storage>); - -impl>> CopyValue, S> { - /// Read a value from the inner vector. - #[track_caller] - pub fn get(&self, index: usize) -> Option> { - S::try_map(self.read(), move |v| v.get(index)) - } -} - -impl>> CopyValue, S> { - /// Unwraps the inner value and clones it. - #[track_caller] - pub fn unwrap(&self) -> T - where - T: Clone, - { - self.with(|v| v.clone()).unwrap() - } - - /// Attempts to read the inner value of the Option. - #[track_caller] - pub fn as_ref(&self) -> Option> { - S::try_map(self.read(), |v| v.as_ref()) - } -} - write_impls!(CopyValue, Storage, Storage>); -impl>> CopyValue, S> { - /// Takes the value out of the Option. - #[track_caller] - pub fn take(&self) -> Option { - self.with_mut(|v| v.take()) - } - - /// Replace the value in the Option. - #[track_caller] - pub fn replace(&self, value: T) -> Option { - self.with_mut(|v| v.replace(value)) - } - - /// Gets the value out of the Option, or inserts the given value if the Option is empty. - #[track_caller] - pub fn get_or_insert(&self, default: T) -> S::Ref { - self.get_or_insert_with(|| default) - } - - /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. - #[track_caller] - pub fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> S::Ref { - let borrow = self.read(); - if borrow.is_none() { - drop(borrow); - self.with_mut(|v| *v = Some(default())); - S::map(self.read(), |v| v.as_ref().unwrap()) - } else { - S::map(borrow, |v| v.as_ref().unwrap()) - } - } -} - read_impls!(Signal, S: Storage>, S: Storage>>); - -impl>>> Signal, S> { - /// Read a value from the inner vector. - pub fn get(&self, index: usize) -> Option> { - S::try_map(self.read(), move |v| v.get(index)) - } -} - -impl>>> Signal, S> { - /// Unwraps the inner value and clones it. - pub fn unwrap(&self) -> T - where - T: Clone, - { - self.with(|v| v.clone()).unwrap() - } - - /// Attempts to read the inner value of the Option. - pub fn as_ref(&self) -> Option> { - S::try_map(self.read(), |v| v.as_ref()) - } -} - write_impls!(Signal, Storage>, Storage>>); -impl>>> Signal, S> { - /// Takes the value out of the Option. - pub fn take(&mut self) -> Option { - self.with_mut(|v| v.take()) - } - - /// Replace the value in the Option. - pub fn replace(&mut self, value: T) -> Option { - self.with_mut(|v| v.replace(value)) - } - - /// Gets the value out of the Option, or inserts the given value if the Option is empty. - pub fn get_or_insert(&mut self, default: T) -> S::Ref { - self.get_or_insert_with(|| default) - } - - /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. - pub fn get_or_insert_with(&mut self, default: impl FnOnce() -> T) -> S::Ref { - let borrow = self.read(); - if borrow.is_none() { - drop(borrow); - self.with_mut(|v| *v = Some(default())); - S::map(self.read(), |v| v.as_ref().unwrap()) - } else { - S::map(borrow, |v| v.as_ref().unwrap()) - } - } -} - read_impls!( ReadOnlySignal, S: Storage>, @@ -329,63 +151,6 @@ read_impls!( ); read_impls!(GlobalSignal); - -impl GlobalSignal> { - /// Read a value from the inner vector. - pub fn get(&'static self, index: usize) -> Option>> { - ::try_map(self.read(), move |v| v.get(index)) - } -} - -impl GlobalSignal> { - /// Unwraps the inner value and clones it. - pub fn unwrap(&'static self) -> T - where - T: Clone, - { - self.with(|v| v.clone()).unwrap() - } - - /// Attempts to read the inner value of the Option. - pub fn as_ref(&'static self) -> Option>> { - ::try_map(self.read(), |v| v.as_ref()) - } -} - -write_vec_impls!(GlobalSignal); - -impl GlobalSignal> { - /// Takes the value out of the Option. - pub fn take(&self) -> Option { - self.with_mut(|v| v.take()) - } - - /// Replace the value in the Option. - pub fn replace(&self, value: T) -> Option { - self.with_mut(|v| v.replace(value)) - } - - /// Gets the value out of the Option, or inserts the given value if the Option is empty. - pub fn get_or_insert(&self, default: T) -> GenerationalRef> { - self.get_or_insert_with(|| default) - } - - /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. - pub fn get_or_insert_with( - &self, - default: impl FnOnce() -> T, - ) -> GenerationalRef> { - let borrow = self.read(); - if borrow.is_none() { - drop(borrow); - self.with_mut(|v| *v = Some(default())); - ::map(self.read(), |v| v.as_ref().unwrap()) - } else { - ::map(borrow, |v| v.as_ref().unwrap()) - } - } -} - read_impls!(GlobalMemo: PartialEq); impl GlobalMemo> { @@ -395,54 +160,13 @@ impl GlobalMemo> { } } -impl GlobalMemo> { - /// Unwraps the inner value and clones it. - pub fn unwrap(&'static self) -> T - where - T: Clone, - { - self.with(|v| v.clone()).unwrap() - } - - /// Attempts to read the inner value of the Option. - pub fn as_ref(&'static self) -> Option>> { - ::try_map(self.read(), |v| v.as_ref()) - } -} - -/// An iterator over the values of a `CopyValue>`. -pub struct CopyValueIterator>> { - index: usize, - value: CopyValue, S>, -} - -impl>> Iterator for CopyValueIterator { - type Item = S::Ref; - - fn next(&mut self) -> Option { - let index = self.index; - self.index += 1; - self.value.get(index) - } -} - impl>> IntoIterator for CopyValue, S> { - type IntoIter = CopyValueIterator; + type IntoIter = ReadableValueIterator; type Item = S::Ref; fn into_iter(self) -> Self::IntoIter { - CopyValueIterator { - index: 0, - value: self, - } - } -} - -impl>> CopyValue, S> { - /// Write to an element in the inner vector. - pub fn get_mut(&self, index: usize) -> Option> { - S::try_map_mut(self.write(), |v: &mut Vec| v.get_mut(index)) + self.iter() } } @@ -453,39 +177,13 @@ impl>> CopyValue, S> { } } -/// An iterator over items in a `Signal>`. -pub struct SignalIterator>>> { - index: usize, - value: Signal, S>, -} - -impl>>> Iterator for SignalIterator { - type Item = S::Ref; - - fn next(&mut self) -> Option { - let index = self.index; - self.index += 1; - self.value.get(index) - } -} - impl>>> IntoIterator for Signal, S> { - type IntoIter = SignalIterator; + type IntoIter = ReadableValueIterator; type Item = S::Ref; fn into_iter(self) -> Self::IntoIter { - SignalIterator { - index: 0, - value: self, - } - } -} - -impl>>> Signal, S> { - /// Returns a reference to an element or `None` if out of bounds. - pub fn get_mut(&mut self, index: usize) -> Option> { - Write::filter_map(self.write(), |v| v.get_mut(index)) + self.iter() } } diff --git a/packages/signals/src/read.rs b/packages/signals/src/read.rs index 604a5efac..1fc4dfaa3 100644 --- a/packages/signals/src/read.rs +++ b/packages/signals/src/read.rs @@ -1,19 +1,33 @@ use std::ops::Deref; -pub trait Readable { +/// A trait for utilities around a mutable reference +pub trait ReadableRef { + /// The type of the reference. type Ref: Deref; - fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref; + /// Map the reference to a new type. + fn map_ref &U>( + ref_: Self::Ref, + f: F, + ) -> Self::Ref; - fn try_map_ref Option<&U>>( + /// Try to map the reference to a new type. + fn try_map_ref Option<&U>>( ref_: Self::Ref, f: F, ) -> Option>; +} +/// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadOnlySignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type. +pub trait Readable: ReadableRef { + /// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal. If the value has been dropped, this will panic. fn read(&self) -> Self::Ref; + /// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic. fn peek(&self) -> Self::Ref; + /// Clone the inner value and return it. If the value has been dropped, this will panic. + #[track_caller] fn cloned(&self) -> T where T: Clone, @@ -21,15 +35,19 @@ pub trait Readable { self.read().clone() } + /// Run a function with a reference to the value. If the value has been dropped, this will panic. + #[track_caller] fn with(&self, f: impl FnOnce(&T) -> O) -> O { f(&*self.read()) } + /// Run a function with a reference to the value. If the value has been dropped, this will panic. + #[track_caller] fn with_peek(&self, f: impl FnOnce(&T) -> O) -> O { f(&*self.peek()) } - /// Index into the inner value and return a reference to the result. + /// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic. #[track_caller] fn index(&self, index: I) -> Self::Ref where @@ -39,6 +57,7 @@ pub trait Readable { } } +/// An extension trait for Readable> that provides some convenience methods. pub trait ReadableVecExt: Readable> { /// Returns the length of the inner vector. #[track_caller] @@ -69,4 +88,66 @@ pub trait ReadableVecExt: Readable> { fn get(&self, index: usize) -> Option> { Self::try_map_ref(self.read(), |v| v.get(index)) } + + /// Get an iterator over the values of the inner vector. + #[track_caller] + fn iter(&self) -> ReadableValueIterator + where + Self: Sized + Clone, + { + ReadableValueIterator { + index: 0, + value: self.clone(), + phantom: std::marker::PhantomData, + } + } +} + +/// An iterator over the values of a `Readable>`. +pub struct ReadableValueIterator { + index: usize, + value: R, + phantom: std::marker::PhantomData, +} + +impl>> Iterator for ReadableValueIterator { + type Item = R::Ref; + + fn next(&mut self) -> Option { + let index = self.index; + self.index += 1; + self.value.get(index) + } +} + +impl ReadableVecExt for R +where + T: 'static, + R: Readable>, +{ +} + +/// An extension trait for Readable> that provides some convenience methods. +pub trait ReadableOptionExt: Readable> { + /// Unwraps the inner value and clones it. + #[track_caller] + fn unwrap(&self) -> T + where + T: Clone, + { + self.as_ref().unwrap().clone() + } + + /// Attempts to read the inner value of the Option. + #[track_caller] + fn as_ref(&self) -> Option> { + Self::try_map_ref(self.read(), |v| v.as_ref()) + } +} + +impl ReadableOptionExt for R +where + T: 'static, + R: Readable>, +{ } diff --git a/packages/signals/src/read_only_signal.rs b/packages/signals/src/read_only_signal.rs index f27e238a3..1f827efe4 100644 --- a/packages/signals/src/read_only_signal.rs +++ b/packages/signals/src/read_only_signal.rs @@ -1,4 +1,4 @@ -use crate::{read::Readable, Signal, SignalData}; +use crate::{read::Readable, ReadableRef, Signal, SignalData}; use std::{mem::MaybeUninit, ops::Deref}; use dioxus_core::{prelude::IntoAttributeValue, ScopeId}; @@ -41,7 +41,7 @@ impl>> ReadOnlySignal { } } -impl>> Readable for ReadOnlySignal { +impl>> ReadableRef for ReadOnlySignal { type Ref = S::Ref; fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref { @@ -54,7 +54,9 @@ impl>> Readable for ReadOnlySignal { ) -> Option> { S::try_map(ref_, f) } +} +impl>> Readable for ReadOnlySignal { /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peek`] instead. /// /// If the signal has been dropped, this will panic. diff --git a/packages/signals/src/rt.rs b/packages/signals/src/rt.rs index 53ae8b8aa..b96e9ec64 100644 --- a/packages/signals/src/rt.rs +++ b/packages/signals/src/rt.rs @@ -10,6 +10,10 @@ use dioxus_core::ScopeId; use generational_box::{GenerationalBox, Owner, Storage}; use crate::Effect; +use crate::Readable; +use crate::ReadableRef; +use crate::Writable; +use crate::WritableRef; fn current_owner, T>() -> Rc> { match Effect::current() { @@ -140,62 +144,62 @@ impl> CopyValue { self.origin_scope } - /// Try to read the value. If the value has been dropped, this will return None. - #[track_caller] - pub fn try_read(&self) -> Result, generational_box::BorrowError> { - self.value.try_read() - } - - /// Read the value. If the value has been dropped, this will panic. - #[track_caller] - pub fn read(&self) -> S::Ref { - self.value.read() - } - - /// Try to write the value. If the value has been dropped, this will return None. - #[track_caller] - pub fn try_write(&mut self) -> Result, generational_box::BorrowMutError> { - self.value.try_write() - } - - /// Write the value without any lifetime hints. If the value has been dropped, this will panic. - /// - /// Note: This is completely safe because the value is stored in a generational box. The lifetime that normally is passed to the returned reference is only used as a hint to user to prevent runtime overlapping borrow panics. - #[track_caller] - pub fn write(&self) -> S::Mut { - self.value.write() - } - - /// Set the value. If the value has been dropped, this will panic. - #[track_caller] - pub fn set(&self, value: T) { - self.value.set(value); - } - - /// Run a function with a reference to the value. If the value has been dropped, this will panic. - #[track_caller] - pub fn with(&self, f: impl FnOnce(&T) -> O) -> O { - let write = self.read(); - f(&*write) - } - - /// Run a function with a mutable reference to the value. If the value has been dropped, this will panic. - #[track_caller] - pub fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { - let mut write = self.write(); - f(&mut *write) - } - /// Get the generational id of the value. pub fn id(&self) -> GenerationalBoxId { self.value.id() } } -impl> CopyValue { - /// Get the value. If the value has been dropped, this will panic. - pub fn value(&self) -> T { - self.read().clone() +impl> ReadableRef for CopyValue { + type Ref = S::Ref; + + fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref { + S::map(ref_, f) + } + + fn try_map_ref Option<&U>>( + ref_: Self::Ref, + f: F, + ) -> Option> { + S::try_map(ref_, f) + } +} + +impl> Readable for CopyValue { + fn read(&self) -> Self::Ref { + self.value.read() + } + + fn peek(&self) -> Self::Ref { + self.value.read() + } +} + +impl> WritableRef for CopyValue { + type Mut = S::Mut; + + fn map_mut &mut U>( + mut_: Self::Mut, + f: F, + ) -> Self::Mut { + S::map_mut(mut_, f) + } + + fn try_map_mut Option<&mut U>>( + mut_: Self::Mut, + f: F, + ) -> Option> { + S::try_map_mut(mut_, f) + } +} + +impl> Writable for CopyValue { + fn try_write(&self) -> Result, generational_box::BorrowMutError> { + self.value.try_write() + } + + fn write(&self) -> Self::Mut { + self.value.write() } } diff --git a/packages/signals/src/signal.rs b/packages/signals/src/signal.rs index 309b31f95..d1f58662d 100644 --- a/packages/signals/src/signal.rs +++ b/packages/signals/src/signal.rs @@ -1,6 +1,6 @@ use crate::{ read::Readable, write::Writable, Effect, EffectInner, GlobalMemo, GlobalSignal, MappedSignal, - ReadOnlySignal, + ReadOnlySignal, ReadableRef, WritableRef, }; use std::{ any::Any, @@ -397,7 +397,7 @@ impl>> Signal { } } -impl>> Readable for Signal { +impl>> ReadableRef for Signal { type Ref = S::Ref; fn map_ref &U>(ref_: Self::Ref, f: F) -> Self::Ref { @@ -410,7 +410,9 @@ impl>> Readable for Signal { ) -> Option> { S::try_map(ref_, f) } +} +impl>> Readable for Signal { /// Get the current value of the signal. This will subscribe the current scope to the signal. If you would like to read the signal without subscribing to it, you can use [`Self::peek`] instead. /// /// If the signal has been dropped, this will panic. @@ -454,7 +456,7 @@ impl>> Readable for Signal { } } -impl>> Writable for Signal { +impl>> WritableRef for Signal { type Mut = Write; fn map_mut &mut U>( @@ -470,18 +472,18 @@ impl>> Writable for Signal { ) -> Option> { Write::filter_map(ref_, f) } +} - /// Get a mutable reference to the signal's value. - /// - /// If the signal has been dropped, this will panic. +impl>> Writable for Signal { #[track_caller] - fn write(&self) -> Self::Mut { - let inner = self.inner.write(); - let borrow = S::map_mut(inner, |v| &mut v.value); - Write { - write: borrow, - drop_signal: Box::new(SignalSubscriberDrop { signal: *self }), - } + fn try_write(&self) -> Result, generational_box::BorrowMutError> { + self.inner.try_write().map(|inner| { + let borrow = S::map_mut(inner, |v| &mut v.value); + Write { + write: borrow, + drop_signal: Box::new(SignalSubscriberDrop { signal: *self }), + } + }) } } diff --git a/packages/signals/src/write.rs b/packages/signals/src/write.rs index 7a04ab713..bfd19e17f 100644 --- a/packages/signals/src/write.rs +++ b/packages/signals/src/write.rs @@ -2,21 +2,36 @@ use std::ops::DerefMut; use crate::read::Readable; -pub trait Writable: Readable { +/// A trait for utilities around a mutable reference +pub trait WritableRef { + /// The type of the reference. type Mut: DerefMut; + /// Map the reference to a new type. fn map_mut &mut U>( ref_: Self::Mut, f: F, ) -> Self::Mut; + /// Try to map the reference to a new type. fn try_map_mut Option<&mut U>>( ref_: Self::Mut, f: F, ) -> Option>; +} - fn write(&self) -> Self::Mut; +/// A trait for states that can be read from like [`crate::Signal`], or [`crate::GlobalSignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Writable`] type. +pub trait Writable: WritableRef + Readable { + /// Get a mutable reference to the value. If the value has been dropped, this will panic. + #[track_caller] + fn write(&self) -> Self::Mut { + self.try_write().unwrap() + } + /// Try to get a mutable reference to the value. If the value has been dropped, this will panic. + fn try_write(&self) -> Result, generational_box::BorrowMutError>; + + /// Run a function with a mutable reference to the value. If the value has been dropped, this will panic. #[track_caller] fn with_mut(&self, f: impl FnOnce(&mut T) -> O) -> O { f(&mut *self.write()) @@ -29,6 +44,7 @@ pub trait Writable: Readable { } /// Invert the boolean value of the signal. This will trigger an update on all subscribers. + #[track_caller] fn toggle(&mut self) where T: std::ops::Not + Clone, @@ -44,4 +60,158 @@ pub trait Writable: Readable { { Self::map_mut(self.write(), |v| v.index_mut(index)) } + + /// Takes the value out of the Signal, leaving a Default in its place. + #[track_caller] + fn take(&self) -> T + where + T: Default, + { + self.with_mut(|v| std::mem::take(v)) + } + + /// Replace the value in the Signal, returning the old value. + #[track_caller] + fn replace(&self, value: T) -> T { + self.with_mut(|v| std::mem::replace(v, value)) + } +} + +/// An extension trait for Writable> that provides some convenience methods. +pub trait WritableOptionExt: Writable> { + /// Gets the value out of the Option, or inserts the given value if the Option is empty. + fn get_or_insert(&self, default: T) -> Self::Mut { + self.get_or_insert_with(|| default) + } + + /// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty. + fn get_or_insert_with(&self, default: impl FnOnce() -> T) -> Self::Mut { + let borrow = self.read(); + if borrow.is_none() { + drop(borrow); + self.with_mut(|v| *v = Some(default())); + Self::map_mut(self.write(), |v| v.as_mut().unwrap()) + } else { + Self::map_mut(self.write(), |v| v.as_mut().unwrap()) + } + } + + /// Attempts to write the inner value of the Option. + #[track_caller] + fn as_mut(&self) -> Option> { + Self::try_map_mut(self.write(), |v: &mut Option| v.as_mut()) + } +} + +impl WritableOptionExt for W +where + T: 'static, + W: Writable>, +{ +} + +/// An extension trait for Writable> that provides some convenience methods. +pub trait WritableVecExt: Writable> { + /// Pushes a new value to the end of the vector. + #[track_caller] + fn push(&mut self, value: T) { + self.with_mut(|v| v.push(value)) + } + + /// Pops the last value from the vector. + #[track_caller] + fn pop(&mut self) -> Option { + self.with_mut(|v| v.pop()) + } + + /// Inserts a new value at the given index. + #[track_caller] + fn insert(&mut self, index: usize, value: T) { + self.with_mut(|v| v.insert(index, value)) + } + + /// Removes the value at the given index. + #[track_caller] + fn remove(&mut self, index: usize) -> T { + self.with_mut(|v| v.remove(index)) + } + + /// Clears the vector, removing all values. + #[track_caller] + fn clear(&mut self) { + self.with_mut(|v| v.clear()) + } + + /// Extends the vector with the given iterator. + #[track_caller] + fn extend(&mut self, iter: impl IntoIterator) { + self.with_mut(|v| v.extend(iter)) + } + + /// Truncates the vector to the given length. + #[track_caller] + fn truncate(&mut self, len: usize) { + self.with_mut(|v| v.truncate(len)) + } + + /// Swaps two values in the vector. + #[track_caller] + fn swap_remove(&mut self, index: usize) -> T { + self.with_mut(|v| v.swap_remove(index)) + } + + /// Retains only the values that match the given predicate. + #[track_caller] + fn retain(&mut self, f: impl FnMut(&T) -> bool) { + self.with_mut(|v| v.retain(f)) + } + + /// Splits the vector into two at the given index. + #[track_caller] + fn split_off(&mut self, at: usize) -> Vec { + self.with_mut(|v| v.split_off(at)) + } + + /// Try to mutably get an element from the vector. + #[track_caller] + fn get_mut(&self, index: usize) -> Option> { + Self::try_map_mut(self.write(), |v: &mut Vec| v.get_mut(index)) + } + + /// Gets an iterator over the values of the vector. + #[track_caller] + fn iter(&self) -> WritableValueIterator + where + Self: Sized + Clone, + { + WritableValueIterator { + index: 0, + value: self.clone(), + phantom: std::marker::PhantomData, + } + } +} + +/// An iterator over the values of a `Writable>`. +pub struct WritableValueIterator { + index: usize, + value: R, + phantom: std::marker::PhantomData, +} + +impl>> Iterator for WritableValueIterator { + type Item = R::Mut; + + fn next(&mut self) -> Option { + let index = self.index; + self.index += 1; + self.value.get_mut(index) + } +} + +impl WritableVecExt for W +where + T: 'static, + W: Writable>, +{ }