Merge pull request #1910 from ealmloff/readable-map

Implement Readable for mapped signal
This commit is contained in:
Jonathan Kelley authored and GitHub committed 2024-02-07 18:10:02 -08:00
commit 53343bfd19
16 files changed
+410 -416

No files matched your search

+7 -4
View File
@@ -228,9 +228,9 @@ pub trait Storage<Data = ()>: AnyStorage + 'static {
/// A trait for any storage backing type.
pub trait AnyStorage: Default {
/// The reference this storage type returns.
type Ref<T: ?Sized + 'static>: Deref<Target = T>;
type Ref<T: ?Sized + 'static>: Deref<Target = T> + 'static;
/// The mutable reference this storage type returns.
type Mut<T: ?Sized + 'static>: DerefMut<Target = T>;
type Mut<T: ?Sized + 'static>: DerefMut<Target = T> + 'static;
/// Try to map the mutable ref.
fn try_map_mut<T: ?Sized, U: ?Sized + 'static>(
@@ -247,13 +247,16 @@ pub trait AnyStorage: Default {
}
/// Try to map the ref.
fn try_map<T, U: ?Sized + 'static>(
fn try_map<T: ?Sized, U: ?Sized + 'static>(
ref_: Self::Ref<T>,
f: impl FnOnce(&T) -> Option<&U>,
) -> Option<Self::Ref<U>>;
/// Map the ref.
fn map<T, U: ?Sized + 'static>(ref_: Self::Ref<T>, f: impl FnOnce(&T) -> &U) -> Self::Ref<U> {
fn map<T: ?Sized, U: ?Sized + 'static>(
ref_: Self::Ref<T>,
f: impl FnOnce(&T) -> &U,
) -> Self::Ref<U> {
Self::try_map(ref_, |v| Some(f(v))).unwrap()
}
+1 -1
View File
@@ -23,7 +23,7 @@ impl AnyStorage for SyncStorage {
type Ref<R: ?Sized + 'static> = GenerationalRef<MappedRwLockReadGuard<'static, R>>;
type Mut<W: ?Sized + 'static> = GenerationalRefMut<MappedRwLockWriteGuard<'static, W>>;
fn try_map<I, U: ?Sized + 'static>(
fn try_map<I: ?Sized, U: ?Sized + 'static>(
ref_: Self::Ref<I>,
f: impl FnOnce(&I) -> Option<&U>,
) -> Option<Self::Ref<U>> {
+1 -1
View File
@@ -92,7 +92,7 @@ impl AnyStorage for UnsyncStorage {
type Ref<R: ?Sized + 'static> = GenerationalRef<Ref<'static, R>>;
type Mut<W: ?Sized + 'static> = GenerationalRefMut<RefMut<'static, W>>;
fn try_map<I, U: ?Sized + 'static>(
fn try_map<I: ?Sized, U: ?Sized + 'static>(
_self: Self::Ref<I>,
f: impl FnOnce(&I) -> Option<&U>,
) -> Option<Self::Ref<U>> {
-1
View File
@@ -26,7 +26,6 @@ flume = { version = "0.11.0", default-features = false, features = ["async"] }
[dev-dependencies]
dioxus = { workspace = true }
# dioxus-desktop = { workspace = true }
tokio = { version = "1", features = ["full"] }
tracing-subscriber = "0.3.17"
simple_logger = "4.2.0"
+50
View File
@@ -0,0 +1,50 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
launch(app);
}
fn app() -> Element {
let mut vec = use_signal(|| vec![0]);
rsx! {
button {
onclick: move |_| {
let mut write = vec.write();
let len = write.len() as i32;
write.push(len);
},
"Create"
}
button {
onclick: move |_| {
vec.write().pop();
},
"Destroy"
}
for i in 0..vec.len() {
Child { count: vec.map(move |v| &v[i]) }
}
}
}
#[component]
fn Child(count: MappedSignal<i32>) -> Element {
use_memo({
to_owned![count];
move || {
let value = count.read();
println!("Child value: {value}");
}
});
rsx! {
div {
"Child: {count}"
}
}
}
+9 -18
View File
@@ -13,6 +13,7 @@ use dioxus_core::ScopeId;
use generational_box::{GenerationalBox, Owner, Storage};
use crate::ReadableRef;
use crate::Writable;
use crate::{ReactiveContext, Readable};
@@ -204,40 +205,30 @@ impl<T: 'static, S: Storage<T>> CopyValue<T, S> {
}
}
impl<T: 'static, S: Storage<T>> Readable<T> for CopyValue<T, S> {
type Ref<R: ?Sized + 'static> = S::Ref<R>;
impl<T: 'static, S: Storage<T>> Readable for CopyValue<T, S> {
type Target = T;
type Storage = S;
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
S::map(ref_, f)
}
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>> {
S::try_map(ref_, f)
}
fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
self.value.try_read()
}
fn peek(&self) -> Self::Ref<T> {
fn peek(&self) -> ReadableRef<Self> {
self.value.read()
}
}
impl<T: 'static, S: Storage<T>> Writable<T> for CopyValue<T, S> {
impl<T: 'static, S: Storage<T>> Writable for CopyValue<T, S> {
type Mut<R: ?Sized + 'static> = S::Mut<R>;
fn map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
fn map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
mut_: Self::Mut<I>,
f: F,
) -> Self::Mut<U> {
S::map_mut(mut_, f)
}
fn try_map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
fn try_map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
mut_: Self::Mut<I>,
f: F,
) -> Option<Self::Mut<U>> {
+7 -17
View File
@@ -1,6 +1,6 @@
use crate::read::Readable;
use crate::{read::Readable, ReadableRef};
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
use generational_box::{AnyStorage, UnsyncStorage};
use generational_box::UnsyncStorage;
use std::{mem::MaybeUninit, ops::Deref};
use crate::{ReadOnlySignal, Signal};
@@ -51,27 +51,17 @@ impl<T: PartialEq + 'static> GlobalMemo<T> {
}
}
impl<T: PartialEq + 'static> Readable<T> for GlobalMemo<T> {
type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
<UnsyncStorage as AnyStorage>::map(ref_, f)
}
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>> {
<UnsyncStorage as AnyStorage>::try_map(ref_, f)
}
impl<T: PartialEq + 'static> Readable for GlobalMemo<T> {
type Target = T;
type Storage = UnsyncStorage;
#[track_caller]
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
self.signal().try_read()
}
#[track_caller]
fn peek(&self) -> Self::Ref<T> {
fn peek(&self) -> ReadableRef<Self> {
self.signal().peek()
}
}
+17 -31
View File
@@ -1,12 +1,12 @@
use crate::read::Readable;
use crate::write::Writable;
use crate::Write;
use crate::{read::Readable, ReadableRef};
use dioxus_core::prelude::{IntoAttributeValue, ScopeId};
use generational_box::{AnyStorage, GenerationalRef, UnsyncStorage};
use std::{cell::Ref, mem::MaybeUninit, ops::Deref};
use generational_box::UnsyncStorage;
use std::{mem::MaybeUninit, ops::Deref};
use super::get_global_context;
use crate::{MappedSignal, Signal};
use crate::Signal;
/// A signal that can be accessed from anywhere in the application and created in a static
pub struct GlobalSignal<T> {
@@ -60,56 +60,42 @@ impl<T: 'static> GlobalSignal<T> {
self.signal().with_mut(f)
}
/// Map the signal to a new type.
pub fn map<O>(
&self,
f: impl Fn(&T) -> &O + 'static,
) -> MappedSignal<GenerationalRef<Ref<'static, O>>> {
MappedSignal::new(self.signal(), f)
}
/// Get the generational id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.signal().id()
}
}
impl<T: 'static> Readable<T> for GlobalSignal<T> {
type Ref<R: ?Sized + 'static> = generational_box::GenerationalRef<std::cell::Ref<'static, R>>;
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
<UnsyncStorage as AnyStorage>::map(ref_, f)
}
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>> {
<UnsyncStorage as AnyStorage>::try_map(ref_, f)
}
impl<T: 'static> Readable for GlobalSignal<T> {
type Target = T;
type Storage = UnsyncStorage;
#[track_caller]
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
self.signal().try_read()
}
#[track_caller]
fn peek(&self) -> Self::Ref<T> {
fn peek(&self) -> ReadableRef<Self> {
self.signal().peek()
}
}
impl<T: 'static> Writable<T> for GlobalSignal<T> {
impl<T: 'static> Writable for GlobalSignal<T> {
type Mut<R: ?Sized + 'static> = Write<R, UnsyncStorage>;
fn map_mut<I, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
ref_: Self::Mut<I>,
f: F,
) -> Self::Mut<U> {
Write::map(ref_, f)
}
fn try_map_mut<I: 'static, U: ?Sized + 'static, F: FnOnce(&mut I) -> Option<&mut U>>(
fn try_map_mut<
I: ?Sized + 'static,
U: ?Sized + 'static,
F: FnOnce(&mut I) -> Option<&mut U>,
>(
ref_: Self::Mut<I>,
f: F,
) -> Option<Self::Mut<U>> {
@@ -151,7 +137,7 @@ impl<T: Clone + 'static> Deref for GlobalSignal<T> {
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
let uninit_closure = move || {
<GlobalSignal<T> as Readable<T>>::read(unsafe { &*uninit_callable.as_ptr() }).clone()
<GlobalSignal<T> as Readable>::read(unsafe { &*uninit_callable.as_ptr() }).clone()
};
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
+17 -3
View File
@@ -2,15 +2,15 @@ use crate::copy_value::CopyValue;
use crate::read::Readable;
use crate::signal::Signal;
use crate::write::Writable;
use crate::{GlobalMemo, GlobalSignal, ReadOnlySignal, SignalData};
use generational_box::Storage;
use crate::{GlobalMemo, GlobalSignal, MappedSignal, ReadOnlySignal, SignalData};
use generational_box::{AnyStorage, Storage};
use std::{
fmt::{Debug, Display},
ops::{Add, Div, Mul, Sub},
};
macro_rules! read_impls {
macro_rules! default_impl {
($ty:ident $(: $extra_bounds:path)? $(, $bound_ty:ident : $bound:path, $vec_bound_ty:ident : $vec_bound:path)?) => {
$(
impl<T: Default + 'static, $bound_ty: $bound> Default for $ty<T, $bound_ty> {
@@ -20,7 +20,11 @@ macro_rules! read_impls {
}
}
)?
}
}
macro_rules! read_impls {
($ty:ident $(: $extra_bounds:path)? $(, $bound_ty:ident : $bound:path, $vec_bound_ty:ident : $vec_bound:path)?) => {
impl<T: $($extra_bounds + )? Display + 'static $(,$bound_ty: $bound)?> Display for $ty<T $(, $bound_ty)?> {
#[track_caller]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -113,6 +117,7 @@ macro_rules! write_impls {
}
read_impls!(CopyValue, S: Storage<T>, S: Storage<Vec<T>>);
default_impl!(CopyValue, S: Storage<T>, S: Storage<Vec<T>>);
write_impls!(CopyValue, Storage<T>, Storage<Vec<T>>);
impl<T: 'static, S: Storage<T>> Clone for CopyValue<T, S> {
@@ -124,6 +129,7 @@ impl<T: 'static, S: Storage<T>> Clone for CopyValue<T, S> {
impl<T: 'static, S: Storage<T>> Copy for CopyValue<T, S> {}
read_impls!(Signal, S: Storage<SignalData<T>>, S: Storage<SignalData<Vec<T>>>);
default_impl!(Signal, S: Storage<SignalData<T>>, S: Storage<SignalData<Vec<T>>>);
write_impls!(Signal, Storage<SignalData<T>>, Storage<SignalData<Vec<T>>>);
impl<T: 'static, S: Storage<SignalData<T>>> Clone for Signal<T, S> {
@@ -139,6 +145,11 @@ read_impls!(
S: Storage<SignalData<T>>,
S: Storage<SignalData<Vec<T>>>
);
default_impl!(
ReadOnlySignal,
S: Storage<SignalData<T>>,
S: Storage<SignalData<Vec<T>>>
);
impl<T: 'static, S: Storage<SignalData<T>>> Clone for ReadOnlySignal<T, S> {
fn clone(&self) -> Self {
@@ -149,5 +160,8 @@ impl<T: 'static, S: Storage<SignalData<T>>> Clone for ReadOnlySignal<T, S> {
impl<T: 'static, S: Storage<SignalData<T>>> Copy for ReadOnlySignal<T, S> {}
read_impls!(GlobalSignal);
default_impl!(GlobalSignal);
read_impls!(GlobalMemo: PartialEq);
read_impls!(MappedSignal, S: AnyStorage, S: AnyStorage);
+63 -91
View File
@@ -1,114 +1,86 @@
use crate::read::Readable;
use crate::CopyValue;
use crate::Signal;
use crate::SignalData;
use dioxus_core::ScopeId;
use generational_box::Storage;
use std::fmt::Debug;
use std::fmt::Display;
use std::{ops::Deref, rc::Rc};
use crate::{read::Readable, ReadableRef};
use dioxus_core::prelude::*;
use generational_box::{AnyStorage, UnsyncStorage};
/// A read only signal that has been mapped to a new type.
pub struct MappedSignal<U: 'static + ?Sized> {
origin_scope: ScopeId,
mapping: CopyValue<Box<dyn Fn() -> U>>,
pub struct MappedSignal<O: ?Sized + 'static, S: AnyStorage = UnsyncStorage> {
try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
}
impl MappedSignal<()> {
/// Create a new mapped signal.
pub fn new<T, S, U>(
signal: Signal<T, S>,
mapping: impl Fn(&T) -> &U + 'static,
) -> MappedSignal<S::Ref<U>>
where
S: Storage<SignalData<T>>,
U: ?Sized,
{
impl<O: ?Sized, S: AnyStorage> Clone for MappedSignal<O, S> {
fn clone(&self) -> Self {
MappedSignal {
origin_scope: signal.origin_scope(),
mapping: CopyValue::new(Box::new(move || S::map(signal.read(), &mapping))),
try_read: self.try_read.clone(),
peek: self.peek.clone(),
}
}
}
impl<U> MappedSignal<U> {
/// Get the scope that the signal was created in.
pub fn origin_scope(&self) -> ScopeId {
self.origin_scope
}
/// Get the current value of the signal. This will subscribe the current scope to the signal.
pub fn read(&self) -> U {
(self.mapping.read())()
}
/// Run a closure with a reference to the signal's value.
pub fn with<O>(&self, f: impl FnOnce(U) -> O) -> O {
f(self.read())
impl<O, S> MappedSignal<O, S>
where
O: ?Sized,
S: AnyStorage,
{
/// Create a new mapped signal.
pub(crate) fn new(
try_read: Rc<dyn Fn() -> Result<S::Ref<O>, generational_box::BorrowError> + 'static>,
peek: Rc<dyn Fn() -> S::Ref<O> + 'static>,
) -> Self {
MappedSignal { try_read, peek }
}
}
impl<U: ?Sized + Clone> MappedSignal<U> {
/// Get the current value of the signal. This will subscribe the current scope to the signal.
pub fn value(&self) -> U {
self.read().clone()
impl<O, S> Readable for MappedSignal<O, S>
where
O: ?Sized,
S: AnyStorage,
{
type Target = O;
type Storage = S;
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
(self.try_read)()
}
fn peek(&self) -> ReadableRef<Self> {
(self.peek)()
}
}
impl<U: ?Sized> PartialEq for MappedSignal<U> {
impl<O, S> IntoAttributeValue for MappedSignal<O, S>
where
O: Clone + IntoAttributeValue,
S: AnyStorage,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<O, S> PartialEq for MappedSignal<O, S>
where
O: ?Sized,
S: AnyStorage,
{
fn eq(&self, other: &Self) -> bool {
self.mapping == other.mapping
std::ptr::eq(&self.peek, &other.peek) && std::ptr::eq(&self.try_read, &other.try_read)
}
}
impl<U> std::clone::Clone for MappedSignal<U> {
fn clone(&self) -> Self {
*self
}
}
impl<U> Copy for MappedSignal<U> {}
impl<U: Display> Display for MappedSignal<U> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.with(|v| Display::fmt(&v, f))
}
}
impl<U: Debug> Debug for MappedSignal<U> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.with(|v| Debug::fmt(&v, f))
}
}
impl<T> std::ops::Deref for MappedSignal<T> {
type Target = dyn Fn() -> T;
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
impl<O, S> Deref for MappedSignal<O, S>
where
O: Clone,
S: AnyStorage + 'static,
{
type Target = dyn Fn() -> O;
fn deref(&self) -> &Self::Target {
// https://github.com/dtolnay/case-studies/tree/master/callable-types
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
let uninit_callable = std::mem::MaybeUninit::<Self>::uninit();
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() });
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
let size_of_closure = std::mem::size_of_val(&uninit_closure);
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
// Then cast the lifetime of the closure to the lifetime of &self.
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
b
}
let reference_to_closure = cast_lifetime(
{
// The real closure that we will never use.
&uninit_closure
},
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
unsafe { std::mem::transmute(self) },
);
// Cast the closure to a trait object.
reference_to_closure as &Self::Target
Readable::deref_impl(self)
}
}
+67 -43
View File
@@ -1,66 +1,92 @@
use std::{mem::MaybeUninit, ops::Deref};
use std::{mem::MaybeUninit, ops::Index, rc::Rc};
use generational_box::AnyStorage;
use crate::MappedSignal;
/// A reference to a value that can be read from.
#[allow(type_alias_bounds)]
pub type ReadableRef<T: Readable, O = <T as Readable>::Target> = <T::Storage as AnyStorage>::Ref<O>;
/// 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<T: 'static = ()> {
/// The type of the reference.
type Ref<R: ?Sized + 'static>: Deref<Target = R>;
pub trait Readable {
/// The target type of the reference.
type Target: ?Sized + 'static;
/// Map the reference to a new type.
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U>;
/// The type of the storage this readable uses.
type Storage: AnyStorage;
/// Try to map the reference to a new type.
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>>;
/// Try to 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 try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError>;
/// Map the readable type to a new type.
fn map<O>(self, f: impl Fn(&Self::Target) -> &O + 'static) -> MappedSignal<O, Self::Storage>
where
Self: Clone + Sized + 'static,
{
let mapping = Rc::new(f);
let try_read = Rc::new({
let self_ = self.clone();
let mapping = mapping.clone();
move || {
self_
.try_read()
.map(|ref_| <Self::Storage as AnyStorage>::map(ref_, |r| mapping(r)))
}
})
as Rc<
dyn Fn() -> Result<ReadableRef<Self, O>, generational_box::BorrowError> + 'static,
>;
let peek = Rc::new(move || <Self::Storage as AnyStorage>::map(self.peek(), |r| mapping(r)))
as Rc<dyn Fn() -> ReadableRef<Self, O> + 'static>;
MappedSignal::new(try_read, peek)
}
/// 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.
#[track_caller]
fn read(&self) -> Self::Ref<T> {
fn read(&self) -> ReadableRef<Self> {
self.try_read().unwrap()
}
/// Try to 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.
#[track_caller]
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError>;
/// 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<T>;
fn peek(&self) -> ReadableRef<Self>;
/// Clone the inner value and return it. If the value has been dropped, this will panic.
#[track_caller]
fn cloned(&self) -> T
fn cloned(&self) -> Self::Target
where
T: Clone,
Self::Target: Clone,
{
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<O>(&self, f: impl FnOnce(&T) -> O) -> O {
fn with<O>(&self, f: impl FnOnce(&Self::Target) -> 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<O>(&self, f: impl FnOnce(&T) -> O) -> O {
fn with_peek<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O {
f(&*self.peek())
}
/// 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<I>(&self, index: I) -> Self::Ref<T::Output>
fn index<I>(&self, index: I) -> ReadableRef<Self, <Self::Target as std::ops::Index<I>>::Output>
where
T: std::ops::Index<I>,
Self::Target: std::ops::Index<I>,
{
Self::map_ref(self.read(), |v| v.index(index))
<Self::Storage as AnyStorage>::map(self.read(), |v| v.index(index))
}
#[doc(hidden)]
fn deref_impl<'a>(&self) -> &'a dyn Fn() -> T
fn deref_impl<'a>(&self) -> &'a dyn Fn() -> Self::Target
where
Self: Sized + 'a,
T: Clone,
Self::Target: Clone,
{
// https://github.com/dtolnay/case-studies/tree/master/callable-types
@@ -92,7 +118,7 @@ pub trait Readable<T: 'static = ()> {
}
/// An extension trait for Readable<Vec<T>> that provides some convenience methods.
pub trait ReadableVecExt<T: 'static>: Readable<Vec<T>> {
pub trait ReadableVecExt<T: 'static>: Readable<Target = Vec<T>> {
/// Returns the length of the inner vector.
#[track_caller]
fn len(&self) -> usize {
@@ -107,45 +133,43 @@ pub trait ReadableVecExt<T: 'static>: Readable<Vec<T>> {
/// Get the first element of the inner vector.
#[track_caller]
fn first(&self) -> Option<Self::Ref<T>> {
Self::try_map_ref(self.read(), |v| v.first())
fn first(&self) -> Option<ReadableRef<Self, T>> {
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.first())
}
/// Get the last element of the inner vector.
#[track_caller]
fn last(&self) -> Option<Self::Ref<T>> {
Self::try_map_ref(self.read(), |v| v.last())
fn last(&self) -> Option<ReadableRef<Self, T>> {
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.last())
}
/// Get the element at the given index of the inner vector.
#[track_caller]
fn get(&self, index: usize) -> Option<Self::Ref<T>> {
Self::try_map_ref(self.read(), |v| v.get(index))
fn get(&self, index: usize) -> Option<ReadableRef<Self, T>> {
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(index))
}
/// Get an iterator over the values of the inner vector.
#[track_caller]
fn iter(&self) -> ReadableValueIterator<'_, T, Self>
fn iter(&self) -> ReadableValueIterator<'_, Self>
where
Self: Sized,
{
ReadableValueIterator {
index: 0,
value: self,
phantom: std::marker::PhantomData,
}
}
}
/// An iterator over the values of a `Readable<Vec<T>>`.
pub struct ReadableValueIterator<'a, T, R> {
pub struct ReadableValueIterator<'a, R> {
index: usize,
value: &'a R,
phantom: std::marker::PhantomData<T>,
}
impl<'a, T: 'static, R: Readable<Vec<T>>> Iterator for ReadableValueIterator<'a, T, R> {
type Item = R::Ref<T>;
impl<'a, T: 'static, R: Readable<Target = Vec<T>>> Iterator for ReadableValueIterator<'a, R> {
type Item = ReadableRef<R, T>;
fn next(&mut self) -> Option<Self::Item> {
let index = self.index;
@@ -157,12 +181,12 @@ impl<'a, T: 'static, R: Readable<Vec<T>>> Iterator for ReadableValueIterator<'a,
impl<T, R> ReadableVecExt<T> for R
where
T: 'static,
R: Readable<Vec<T>>,
R: Readable<Target = Vec<T>>,
{
}
/// An extension trait for Readable<Option<T>> that provides some convenience methods.
pub trait ReadableOptionExt<T: 'static>: Readable<Option<T>> {
pub trait ReadableOptionExt<T: 'static>: Readable<Target = Option<T>> {
/// Unwraps the inner value and clones it.
#[track_caller]
fn unwrap(&self) -> T
@@ -174,14 +198,14 @@ pub trait ReadableOptionExt<T: 'static>: Readable<Option<T>> {
/// Attempts to read the inner value of the Option.
#[track_caller]
fn as_ref(&self) -> Option<Self::Ref<T>> {
Self::try_map_ref(self.read(), |v| v.as_ref())
fn as_ref(&self) -> Option<ReadableRef<Self, T>> {
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref())
}
}
impl<T, R> ReadableOptionExt<T> for R
where
T: 'static,
R: Readable<Option<T>>,
R: Readable<Target = Option<T>>,
{
}
+5 -15
View File
@@ -1,4 +1,4 @@
use crate::{read::Readable, Signal, SignalData};
use crate::{read::Readable, ReadableRef, Signal, SignalData};
use std::ops::Deref;
use dioxus_core::{prelude::IntoAttributeValue, ScopeId};
@@ -54,22 +54,12 @@ impl<T: 'static, S: Storage<SignalData<T>>> ReadOnlySignal<T, S> {
}
}
impl<T, S: Storage<SignalData<T>>> Readable<T> for ReadOnlySignal<T, S> {
type Ref<R: ?Sized + 'static> = S::Ref<R>;
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
S::map(ref_, f)
}
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>> {
S::try_map(ref_, f)
}
impl<T, S: Storage<SignalData<T>>> Readable for ReadOnlySignal<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read(&self) -> Result<Self::Ref<T>, generational_box::BorrowError> {
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
self.inner.try_read()
}
+14 -25
View File
@@ -1,6 +1,6 @@
use crate::{
read::Readable, write::Writable, CopyValue, GlobalMemo, GlobalSignal, MappedSignal,
ReactiveContext, ReadOnlySignal,
read::Readable, write::Writable, CopyValue, GlobalMemo, GlobalSignal, ReactiveContext,
ReadOnlySignal, ReadableRef,
};
use dioxus_core::{
prelude::{flush_sync, spawn, IntoAttributeValue},
@@ -187,33 +187,18 @@ impl<T: 'static, S: Storage<SignalData<T>>> Signal<T, S> {
}
}
/// Map the signal to a new type.
pub fn map<O>(self, f: impl Fn(&T) -> &O + 'static) -> MappedSignal<S::Ref<O>> {
MappedSignal::new(self, f)
}
/// Get the generational id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.inner.id()
}
}
impl<T, S: Storage<SignalData<T>>> Readable<T> for Signal<T, S> {
type Ref<R: ?Sized + 'static> = S::Ref<R>;
fn map_ref<I, U: ?Sized, F: FnOnce(&I) -> &U>(ref_: Self::Ref<I>, f: F) -> Self::Ref<U> {
S::map(ref_, f)
}
fn try_map_ref<I, U: ?Sized, F: FnOnce(&I) -> Option<&U>>(
ref_: Self::Ref<I>,
f: F,
) -> Option<Self::Ref<U>> {
S::try_map(ref_, f)
}
impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read(&self) -> Result<S::Ref<T>, generational_box::BorrowError> {
fn try_read(&self) -> Result<ReadableRef<Self>, generational_box::BorrowError> {
let inner = self.inner.try_read()?;
let reactive_context = ReactiveContext::current();
@@ -225,23 +210,27 @@ impl<T, S: Storage<SignalData<T>>> Readable<T> for Signal<T, S> {
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
///
/// If the signal has been dropped, this will panic.
fn peek(&self) -> S::Ref<T> {
fn peek(&self) -> ReadableRef<Self> {
let inner = self.inner.read();
S::map(inner, |v| &v.value)
}
}
impl<T: 'static, S: Storage<SignalData<T>>> Writable<T> for Signal<T, S> {
impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
type Mut<R: ?Sized + 'static> = Write<R, S>;
fn map_mut<I, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
fn map_mut<I: ?Sized, U: ?Sized + 'static, F: FnOnce(&mut I) -> &mut U>(
ref_: Self::Mut<I>,
f: F,
) -> Self::Mut<U> {
Write::map(ref_, f)
}
fn try_map_mut<I: 'static, U: ?Sized + 'static, F: FnOnce(&mut I) -> Option<&mut U>>(
fn try_map_mut<
I: ?Sized + 'static,
U: ?Sized + 'static,
F: FnOnce(&mut I) -> Option<&mut U>,
>(
ref_: Self::Mut<I>,
f: F,
) -> Option<Self::Mut<U>> {
+32 -25
View File
@@ -1,40 +1,46 @@
use std::ops::DerefMut;
use std::ops::IndexMut;
use crate::read::Readable;
/// 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<T: 'static>: Readable<T> {
pub trait Writable: Readable {
/// The type of the reference.
type Mut<R: ?Sized + 'static>: DerefMut<Target = R>;
type Mut<R: ?Sized + 'static>: DerefMut<Target = R> + 'static;
/// Map the reference to a new type.
fn map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(ref_: Self::Mut<I>, f: F)
-> Self::Mut<U>;
fn map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> &mut U>(
ref_: Self::Mut<I>,
f: F,
) -> Self::Mut<U>;
/// Try to map the reference to a new type.
fn try_map_mut<I, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
fn try_map_mut<I: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
ref_: Self::Mut<I>,
f: F,
) -> Option<Self::Mut<U>>;
/// Get a mutable reference to the value. If the value has been dropped, this will panic.
#[track_caller]
fn write(&mut self) -> Self::Mut<T> {
fn write(&mut self) -> Self::Mut<Self::Target> {
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<Self::Mut<T>, generational_box::BorrowMutError>;
fn try_write(&self) -> Result<Self::Mut<Self::Target>, 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<O>(&mut self, f: impl FnOnce(&mut T) -> O) -> O {
fn with_mut<O>(&mut self, f: impl FnOnce(&mut Self::Target) -> O) -> O {
f(&mut *self.write())
}
/// Set the value of the signal. This will trigger an update on all subscribers.
#[track_caller]
fn set(&mut self, value: T) {
fn set(&mut self, value: Self::Target)
where
Self::Target: Sized,
{
*self.write() = value;
}
@@ -42,38 +48,41 @@ pub trait Writable<T: 'static>: Readable<T> {
#[track_caller]
fn toggle(&mut self)
where
T: std::ops::Not<Output = T> + Clone,
Self::Target: std::ops::Not<Output = Self::Target> + Clone,
{
self.set(!self.cloned());
}
/// Index into the inner value and return a reference to the result.
#[track_caller]
fn index_mut<I>(&mut self, index: I) -> Self::Mut<T::Output>
fn index_mut<I>(&mut self, index: I) -> Self::Mut<<Self::Target as std::ops::Index<I>>::Output>
where
T: std::ops::IndexMut<I>,
Self::Target: std::ops::IndexMut<I>,
{
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(&mut self) -> T
fn take(&mut self) -> Self::Target
where
T: Default,
Self::Target: Default,
{
self.with_mut(|v| std::mem::take(v))
self.with_mut(std::mem::take)
}
/// Replace the value in the Signal, returning the old value.
#[track_caller]
fn replace(&mut self, value: T) -> T {
fn replace(&mut self, value: Self::Target) -> Self::Target
where
Self::Target: Sized,
{
self.with_mut(|v| std::mem::replace(v, value))
}
}
/// An extension trait for Writable<Option<T>> that provides some convenience methods.
pub trait WritableOptionExt<T: 'static>: Writable<Option<T>> {
pub trait WritableOptionExt<T: 'static>: Writable<Target = Option<T>> {
/// Gets the value out of the Option, or inserts the given value if the Option is empty.
fn get_or_insert(&mut self, default: T) -> Self::Mut<T> {
self.get_or_insert_with(|| default)
@@ -101,12 +110,12 @@ pub trait WritableOptionExt<T: 'static>: Writable<Option<T>> {
impl<T, W> WritableOptionExt<T> for W
where
T: 'static,
W: Writable<Option<T>>,
W: Writable<Target = Option<T>>,
{
}
/// An extension trait for Writable<Vec<T>> that provides some convenience methods.
pub trait WritableVecExt<T: 'static>: Writable<Vec<T>> {
pub trait WritableVecExt<T: 'static>: Writable<Target = Vec<T>> {
/// Pushes a new value to the end of the vector.
#[track_caller]
fn push(&mut self, value: T) {
@@ -175,26 +184,24 @@ pub trait WritableVecExt<T: 'static>: Writable<Vec<T>> {
/// Gets an iterator over the values of the vector.
#[track_caller]
fn iter_mut(&self) -> WritableValueIterator<T, Self>
fn iter_mut(&self) -> WritableValueIterator<Self>
where
Self: Sized + Clone,
{
WritableValueIterator {
index: 0,
value: self.clone(),
phantom: std::marker::PhantomData,
}
}
}
/// An iterator over the values of a `Writable<Vec<T>>`.
pub struct WritableValueIterator<T, R> {
pub struct WritableValueIterator<R> {
index: usize,
value: R,
phantom: std::marker::PhantomData<T>,
}
impl<T: 'static, R: Writable<Vec<T>>> Iterator for WritableValueIterator<T, R> {
impl<T: 'static, R: Writable<Target = Vec<T>>> Iterator for WritableValueIterator<R> {
type Item = R::Mut<T>;
fn next(&mut self) -> Option<Self::Item> {
@@ -207,6 +214,6 @@ impl<T: 'static, R: Writable<Vec<T>>> Iterator for WritableValueIterator<T, R> {
impl<T, W> WritableVecExt<T> for W
where
T: 'static,
W: Writable<Vec<T>>,
W: Writable<Target = Vec<T>>,
{
}