dioxus_signals/
copy_value.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#![allow(clippy::unnecessary_operation)]
#![allow(clippy::no_effect)]

use generational_box::UnsyncStorage;
use generational_box::{BorrowResult, GenerationalBoxId};
use std::ops::Deref;

use dioxus_core::prelude::*;

use generational_box::{GenerationalBox, Storage};

use crate::read_impls;
use crate::Readable;
use crate::ReadableRef;
use crate::Writable;
use crate::WritableRef;
use crate::{default_impl, write_impls};

/// CopyValue is a wrapper around a value to make the value mutable and Copy.
///
/// It is internally backed by [`generational_box::GenerationalBox`].
pub struct CopyValue<T: 'static, S: Storage<T> = UnsyncStorage> {
    pub(crate) value: GenerationalBox<T, S>,
    pub(crate) origin_scope: ScopeId,
}

#[cfg(feature = "serialize")]
impl<T: 'static, Store: Storage<T>> serde::Serialize for CopyValue<T, Store>
where
    T: serde::Serialize,
{
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.value.read().serialize(serializer)
    }
}

#[cfg(feature = "serialize")]
impl<'de, T: 'static, Store: Storage<T>> serde::Deserialize<'de> for CopyValue<T, Store>
where
    T: serde::Deserialize<'de>,
{
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = T::deserialize(deserializer)?;

        Ok(Self::new_maybe_sync(value))
    }
}

impl<T: 'static> CopyValue<T> {
    /// Create a new CopyValue. The value will be stored in the current component.
    ///
    /// Once the component this value is created in is dropped, the value will be dropped.
    #[track_caller]
    pub fn new(value: T) -> Self {
        Self::new_maybe_sync(value)
    }

    /// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
    #[track_caller]
    pub fn new_in_scope(value: T, scope: ScopeId) -> Self {
        Self::new_maybe_sync_in_scope(value, scope)
    }
}

impl<T: 'static, S: Storage<T>> CopyValue<T, S> {
    /// Create a new CopyValue. The value will be stored in the current component.
    ///
    /// Once the component this value is created in is dropped, the value will be dropped.
    #[track_caller]
    pub fn new_maybe_sync(value: T) -> Self {
        Self::new_with_caller(value, std::panic::Location::caller())
    }

    /// Create a new CopyValue without an owner. This will leak memory if you don't manually drop it.
    pub fn leak_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self {
        Self {
            value: GenerationalBox::leak(value, caller),
            origin_scope: current_scope_id().expect("in a virtual dom"),
        }
    }

    /// Point to another copy value
    pub fn point_to(&self, other: Self) -> BorrowResult {
        self.value.point_to(other.value)
    }

    pub(crate) fn new_with_caller(
        value: T,
        caller: &'static std::panic::Location<'static>,
    ) -> Self {
        let owner = current_owner();

        Self {
            value: owner.insert_rc_with_caller(value, caller),
            origin_scope: current_scope_id().expect("in a virtual dom"),
        }
    }

    /// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
    #[track_caller]
    pub fn new_maybe_sync_in_scope(value: T, scope: ScopeId) -> Self {
        Self::new_maybe_sync_in_scope_with_caller(value, scope, std::panic::Location::caller())
    }

    /// Create a new CopyValue with a custom caller. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
    #[track_caller]
    pub fn new_maybe_sync_in_scope_with_caller(
        value: T,
        scope: ScopeId,
        caller: &'static std::panic::Location<'static>,
    ) -> Self {
        let owner = scope.owner();

        Self {
            value: owner.insert_rc_with_caller(value, caller),
            origin_scope: scope,
        }
    }

    /// Manually drop the value in the CopyValue, invalidating the value in the process.
    pub fn manually_drop(&self) {
        self.value.manually_drop()
    }

    /// Get the scope this value was created in.
    pub fn origin_scope(&self) -> ScopeId {
        self.origin_scope
    }

    /// Get the generational id of the value.
    pub fn id(&self) -> GenerationalBoxId {
        self.value.id()
    }

    /// Get the underlying [`GenerationalBox`] value.
    pub fn value(&self) -> GenerationalBox<T, S> {
        self.value
    }
}

impl<T: 'static, S: Storage<T>> Readable for CopyValue<T, S> {
    type Target = T;
    type Storage = S;

    #[track_caller]
    fn try_read_unchecked(
        &self,
    ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
        crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
        self.value.try_read()
    }

    #[track_caller]
    fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>> {
        crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
        self.value.try_read()
    }
}

impl<T: 'static, S: Storage<T>> Writable for CopyValue<T, S> {
    type Mut<'a, R: ?Sized + 'static> = S::Mut<'a, R>;

    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: ?Sized, U: ?Sized, F: FnOnce(&mut I) -> Option<&mut U>>(
        mut_: Self::Mut<'_, I>,
        f: F,
    ) -> Option<Self::Mut<'_, U>> {
        S::try_map_mut(mut_, f)
    }

    fn downcast_lifetime_mut<'a: 'b, 'b, R: ?Sized + 'static>(
        mut_: Self::Mut<'a, R>,
    ) -> Self::Mut<'b, R> {
        S::downcast_lifetime_mut(mut_)
    }

    #[track_caller]
    fn try_write_unchecked(
        &self,
    ) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
        crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
        self.value.try_write()
    }

    #[track_caller]
    fn set(&mut self, value: T) {
        crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
        self.value.set(value);
    }
}

impl<T: 'static, S: Storage<T>> PartialEq for CopyValue<T, S> {
    fn eq(&self, other: &Self) -> bool {
        self.value.ptr_eq(&other.value)
    }
}
impl<T: 'static, S: Storage<T>> Eq for CopyValue<T, S> {}

impl<T: Copy, S: Storage<T>> Deref for CopyValue<T, S> {
    type Target = dyn Fn() -> T;

    fn deref(&self) -> &Self::Target {
        unsafe { Readable::deref_impl(self) }
    }
}

impl<T, S: Storage<T>> Clone for CopyValue<T, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T, S: Storage<T>> Copy for CopyValue<T, S> {}

read_impls!(CopyValue<T, S: Storage<T>>);
default_impl!(CopyValue<T, S: Storage<T>>);
write_impls!(CopyValue<T, S: Storage<T>>);