File size: 6,863 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use std::{
    fmt::{Debug, Display},
    hash::Hash,
    marker::PhantomData,
    mem::transmute_copy,
};

use serde::{Deserialize, Serialize};
use turbo_tasks_hash::DeterministicHash;

use crate::{
    SharedReference, Vc, VcRead, VcValueType,
    debug::{ValueDebugFormat, ValueDebugFormatString},
    trace::{TraceRawVcs, TraceRawVcsContext},
    triomphe_utils::unchecked_sidecast_triomphe_arc,
    vc::VcCellMode,
};

type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;

/// The read value of a value cell. The read value is immutable, while the cell
/// itself might change over time. It's basically a snapshot of a value at a
/// certain point in time.
///
/// Internally it stores a reference counted reference to a value on the heap.
pub struct ReadRef<T>(triomphe::Arc<T>);

impl<T> Clone for ReadRef<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T> std::ops::Deref for ReadRef<T>
where
    T: VcValueType,
{
    type Target = VcReadTarget<T>;

    fn deref(&self) -> &Self::Target {
        T::Read::value_to_target_ref(&self.0)
    }
}

impl<T> Display for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&**self, f)
    }
}

impl<T> Debug for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&**self, f)
    }
}

impl<T> TraceRawVcs for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: TraceRawVcs,
{
    fn trace_raw_vcs(&self, trace_context: &mut TraceRawVcsContext) {
        (**self).trace_raw_vcs(trace_context);
    }
}

impl<T> ValueDebugFormat for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: ValueDebugFormat + 'static,
{
    fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> {
        let value = &**self;
        value.value_debug_format(depth)
    }
}

impl<T> PartialEq for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(&**self, &**other)
    }
}

impl<T> Eq for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Eq,
{
}

impl<T> PartialOrd for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
}

impl<T> Ord for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Ord,
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        Ord::cmp(&**self, &**other)
    }
}

impl<T> Hash for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Hash,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        Hash::hash(&**self, state)
    }
}

impl<T> DeterministicHash for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: DeterministicHash,
{
    fn deterministic_hash<H: turbo_tasks_hash::DeterministicHasher>(&self, state: &mut H) {
        let p = &**self;
        p.deterministic_hash(state);
    }
}

impl<'a, T, I, J: Iterator<Item = I>> IntoIterator for &'a ReadRef<T>
where
    T: VcValueType,
    &'a VcReadTarget<T>: IntoIterator<Item = I, IntoIter = J>,
{
    type Item = I;

    type IntoIter = J;

    fn into_iter(self) -> Self::IntoIter {
        (&**self).into_iter()
    }
}

impl<T, I: 'static, J: Iterator<Item = I>> IntoIterator for ReadRef<T>
where
    T: VcValueType,
    &'static VcReadTarget<T>: IntoIterator<Item = I, IntoIter = J>,
{
    type Item = I;

    type IntoIter = ReadRefIter<T, I, J>;

    fn into_iter(self) -> Self::IntoIter {
        let r = &*self;
        // # Safety
        // The reference will we valid as long as the ReadRef is valid.
        let r = unsafe { transmute_copy::<&'_ VcReadTarget<T>, &'static VcReadTarget<T>>(&r) };
        ReadRefIter {
            read_ref: self,
            iter: r.into_iter(),
        }
    }
}

pub struct ReadRefIter<T, I: 'static, J: Iterator<Item = I>>
where
    T: VcValueType,
{
    iter: J,
    #[allow(dead_code)]
    read_ref: ReadRef<T>,
}

impl<T, I: 'static, J: Iterator<Item = I>> Iterator for ReadRefIter<T, I, J>
where
    T: VcValueType,
{
    type Item = I;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

impl<T> Serialize for ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        (**self).serialize(serializer)
    }
}

impl<'de, T> Deserialize<'de> for ReadRef<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = T::deserialize(deserializer)?;
        Ok(Self(triomphe::Arc::new(value)))
    }
}

impl<T> ReadRef<T> {
    pub fn new_owned(value: T) -> Self {
        Self(triomphe::Arc::new(value))
    }

    pub fn new_arc(arc: triomphe::Arc<T>) -> Self {
        Self(arc)
    }

    pub fn ptr_eq(&self, other: &ReadRef<T>) -> bool {
        triomphe::Arc::ptr_eq(&self.0, &other.0)
    }

    pub fn ptr(&self) -> *const T {
        &*self.0 as *const T
    }
}

impl<T> ReadRef<T>
where
    T: VcValueType,
{
    /// Returns a new cell that points to the same value as the given
    /// reference.
    pub fn cell(read_ref: ReadRef<T>) -> Vc<T> {
        let type_id = T::get_value_type_id();
        // SAFETY: `T` and `T::Read::Repr` must have equivalent memory representations,
        // guaranteed by the unsafe implementation of `VcValueType`.
        let value = unsafe {
            unchecked_sidecast_triomphe_arc::<T, <T::Read as VcRead<T>>::Repr>(read_ref.0)
        };
        Vc {
            node: <T::CellMode as VcCellMode<T>>::raw_cell(
                SharedReference::new(value).into_typed(type_id),
            ),
            _t: PhantomData,
        }
    }
}

impl<T> ReadRef<T>
where
    T: VcValueType,
{
    /// Returns the inner value, if this [`ReadRef`] has exactly one strong reference.
    ///
    /// Otherwise, an [`Err`] is returned with the same [`ReadRef`] that was passed in.
    pub fn try_unwrap(this: Self) -> Result<VcReadTarget<T>, Self> {
        match triomphe::Arc::try_unwrap(this.0) {
            Ok(value) => Ok(T::Read::value_to_target(value)),
            Err(arc) => Err(Self(arc)),
        }
    }
}

impl<T> ReadRef<T>
where
    T: VcValueType,
    VcReadTarget<T>: Clone,
{
    /// This is return a owned version of the value. It potentially clones the value.
    /// The clone might be expensive. Prefer Deref to get a reference to the value.
    pub fn into_owned(this: Self) -> VcReadTarget<T> {
        Self::try_unwrap(this).unwrap_or_else(|this| (*this).clone())
    }
}