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 = <::Read as VcRead>::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(triomphe::Arc); impl Clone for ReadRef { fn clone(&self) -> Self { Self(self.0.clone()) } } impl std::ops::Deref for ReadRef where T: VcValueType, { type Target = VcReadTarget; fn deref(&self) -> &Self::Target { T::Read::value_to_target_ref(&self.0) } } impl Display for ReadRef where T: VcValueType, VcReadTarget: Display, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&**self, f) } } impl Debug for ReadRef where T: VcValueType, VcReadTarget: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl TraceRawVcs for ReadRef where T: VcValueType, VcReadTarget: TraceRawVcs, { fn trace_raw_vcs(&self, trace_context: &mut TraceRawVcsContext) { (**self).trace_raw_vcs(trace_context); } } impl ValueDebugFormat for ReadRef where T: VcValueType, VcReadTarget: ValueDebugFormat + 'static, { fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> { let value = &**self; value.value_debug_format(depth) } } impl PartialEq for ReadRef where T: VcValueType, VcReadTarget: PartialEq, { fn eq(&self, other: &Self) -> bool { PartialEq::eq(&**self, &**other) } } impl Eq for ReadRef where T: VcValueType, VcReadTarget: Eq, { } impl PartialOrd for ReadRef where T: VcValueType, VcReadTarget: PartialOrd, { fn partial_cmp(&self, other: &Self) -> Option { PartialOrd::partial_cmp(&**self, &**other) } } impl Ord for ReadRef where T: VcValueType, VcReadTarget: Ord, { fn cmp(&self, other: &Self) -> std::cmp::Ordering { Ord::cmp(&**self, &**other) } } impl Hash for ReadRef where T: VcValueType, VcReadTarget: Hash, { fn hash(&self, state: &mut H) { Hash::hash(&**self, state) } } impl DeterministicHash for ReadRef where T: VcValueType, VcReadTarget: DeterministicHash, { fn deterministic_hash(&self, state: &mut H) { let p = &**self; p.deterministic_hash(state); } } impl<'a, T, I, J: Iterator> IntoIterator for &'a ReadRef where T: VcValueType, &'a VcReadTarget: IntoIterator, { type Item = I; type IntoIter = J; fn into_iter(self) -> Self::IntoIter { (&**self).into_iter() } } impl> IntoIterator for ReadRef where T: VcValueType, &'static VcReadTarget: IntoIterator, { type Item = I; type IntoIter = ReadRefIter; 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, &'static VcReadTarget>(&r) }; ReadRefIter { read_ref: self, iter: r.into_iter(), } } } pub struct ReadRefIter> where T: VcValueType, { iter: J, #[allow(dead_code)] read_ref: ReadRef, } impl> Iterator for ReadRefIter where T: VcValueType, { type Item = I; fn next(&mut self) -> Option { self.iter.next() } } impl Serialize for ReadRef where T: VcValueType, VcReadTarget: Serialize, { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { (**self).serialize(serializer) } } impl<'de, T> Deserialize<'de> for ReadRef where T: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let value = T::deserialize(deserializer)?; Ok(Self(triomphe::Arc::new(value))) } } impl ReadRef { pub fn new_owned(value: T) -> Self { Self(triomphe::Arc::new(value)) } pub fn new_arc(arc: triomphe::Arc) -> Self { Self(arc) } pub fn ptr_eq(&self, other: &ReadRef) -> bool { triomphe::Arc::ptr_eq(&self.0, &other.0) } pub fn ptr(&self) -> *const T { &*self.0 as *const T } } impl ReadRef where T: VcValueType, { /// Returns a new cell that points to the same value as the given /// reference. pub fn cell(read_ref: ReadRef) -> Vc { 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::>::Repr>(read_ref.0) }; Vc { node: >::raw_cell( SharedReference::new(value).into_typed(type_id), ), _t: PhantomData, } } } impl ReadRef 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, Self> { match triomphe::Arc::try_unwrap(this.0) { Ok(value) => Ok(T::Read::value_to_target(value)), Err(arc) => Err(Self(arc)), } } } impl ReadRef where T: VcValueType, VcReadTarget: 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 { Self::try_unwrap(this).unwrap_or_else(|this| (*this).clone()) } }