use std::{ fmt::Debug, mem::take, ops::{Deref, DerefMut}, }; use auto_hash_map::AutoSet; use parking_lot::{Mutex, MutexGuard}; use serde::{Deserialize, Serialize}; use crate::{ Invalidator, OperationValue, SerializationInvalidator, get_invalidator, mark_session_dependent, mark_stateful, trace::TraceRawVcs, }; #[derive(Serialize, Deserialize)] struct StateInner { value: T, invalidators: AutoSet, } impl StateInner { pub fn new(value: T) -> Self { Self { value, invalidators: AutoSet::new(), } } pub fn add_invalidator(&mut self, invalidator: Invalidator) { self.invalidators.insert(invalidator); } pub fn set_unconditionally(&mut self, value: T) { self.value = value; for invalidator in take(&mut self.invalidators) { invalidator.invalidate(); } } pub fn update_conditionally(&mut self, update: impl FnOnce(&mut T) -> bool) -> bool { if !update(&mut self.value) { return false; } for invalidator in take(&mut self.invalidators) { invalidator.invalidate(); } true } } impl StateInner { pub fn set(&mut self, value: T) -> bool { if self.value == value { return false; } self.value = value; for invalidator in take(&mut self.invalidators) { invalidator.invalidate(); } true } } pub struct StateRef<'a, T> { serialization_invalidator: Option<&'a SerializationInvalidator>, inner: MutexGuard<'a, StateInner>, mutated: bool, } impl Deref for StateRef<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.inner.value } } impl DerefMut for StateRef<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.mutated = true; &mut self.inner.value } } impl Drop for StateRef<'_, T> { fn drop(&mut self) { if self.mutated { for invalidator in take(&mut self.inner.invalidators) { invalidator.invalidate(); } if let Some(serialization_invalidator) = self.serialization_invalidator { serialization_invalidator.invalidate(); } } } } /// **This API violates core assumption of turbo-tasks, is believed to be unsound, and there's no /// plan fix it.** You should prefer to use [collectibles][crate::CollectiblesSource] instead of /// state where at all possible. This API may be removed in the future. /// /// An [internally-mutable] type, similar to [`RefCell`][std::cell::RefCell] or [`Mutex`] that can /// be stored inside a [`VcValueType`]. /// /// **[`State`] should only be used with [`OperationVc`] and types that implement /// [`OperationValue`]**. /// /// Setting values inside a [`State`] bypasses the normal argument and return value tracking /// that's tracks child function calls and re-runs tasks until their values settled. That system is /// needed for [strong consistency]. [`OperationVc`] ensures that function calls are reconnected /// with the parent/child call graph. /// /// When reading a `State` with [`State::get`], the state itself (though not any values inside of /// it) is marked as a dependency of the current task. /// /// [internally-mutable]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html /// [`VcValueType`]: crate::VcValueType /// [strong consistency]: crate::OperationVc::read_strongly_consistent /// [`OperationVc`]: crate::OperationVc /// [`OperationValue`]: crate::OperationValue #[derive(Serialize, Deserialize)] pub struct State { serialization_invalidator: SerializationInvalidator, inner: Mutex>, } impl Debug for State { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("State") .field("value", &self.inner.lock().value) .finish() } } impl TraceRawVcs for State { fn trace_raw_vcs(&self, trace_context: &mut crate::trace::TraceRawVcsContext) { self.inner.lock().value.trace_raw_vcs(trace_context); } } impl Default for State { fn default() -> Self { // Need to be explicit to ensure marking as stateful. Self::new(Default::default()) } } impl PartialEq for State { fn eq(&self, _other: &Self) -> bool { false } } impl Eq for State {} impl State { pub fn new(value: T) -> Self where T: OperationValue, { Self { serialization_invalidator: mark_stateful(), inner: Mutex::new(StateInner::new(value)), } } /// Gets the current value of the state. The current task will be registered /// as dependency of the state and will be invalidated when the state /// changes. pub fn get(&self) -> StateRef<'_, T> { let invalidator = get_invalidator(); let mut inner = self.inner.lock(); inner.add_invalidator(invalidator); StateRef { serialization_invalidator: Some(&self.serialization_invalidator), inner, mutated: false, } } /// Gets the current value of the state. Untracked. pub fn get_untracked(&self) -> StateRef<'_, T> { let inner = self.inner.lock(); StateRef { serialization_invalidator: Some(&self.serialization_invalidator), inner, mutated: false, } } /// Sets the current state without comparing it with the old value. This /// should only be used if one is sure that the value has changed. pub fn set_unconditionally(&self, value: T) { { let mut inner = self.inner.lock(); inner.set_unconditionally(value); } self.serialization_invalidator.invalidate(); } /// Updates the current state with the `update` function. The `update` /// function need to return `true` when the value was modified. Exposing /// the current value from the `update` function is not allowed and will /// result in incorrect cache invalidation. pub fn update_conditionally(&self, update: impl FnOnce(&mut T) -> bool) { { let mut inner = self.inner.lock(); if !inner.update_conditionally(update) { return; } } self.serialization_invalidator.invalidate(); } } impl State { /// Update the current state when the `value` is different from the current /// value. `T` must implement [PartialEq] for this to work. pub fn set(&self, value: T) { { let mut inner = self.inner.lock(); if !inner.set(value) { return; } } self.serialization_invalidator.invalidate(); } } pub struct TransientState { inner: Mutex>>, } impl Serialize for TransientState { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { Serialize::serialize(&(), serializer) } } impl<'de, T> Deserialize<'de> for TransientState { fn deserialize(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, { let () = Deserialize::deserialize(deserializer)?; Ok(TransientState { inner: Mutex::new(StateInner::new(Default::default())), }) } } impl Debug for TransientState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TransientState") .field("value", &self.inner.lock().value) .finish() } } impl TraceRawVcs for TransientState { fn trace_raw_vcs(&self, trace_context: &mut crate::trace::TraceRawVcsContext) { self.inner.lock().value.trace_raw_vcs(trace_context); } } impl Default for TransientState { fn default() -> Self { // Need to be explicit to ensure marking as stateful. Self::new() } } impl PartialEq for TransientState { fn eq(&self, _other: &Self) -> bool { false } } impl Eq for TransientState {} impl TransientState { pub fn new() -> Self { mark_stateful(); Self { inner: Mutex::new(StateInner::new(None)), } } /// Gets the current value of the state. The current task will be registered /// as dependency of the state and will be invalidated when the state /// changes. pub fn get(&self) -> StateRef<'_, Option> { mark_session_dependent(); let invalidator = get_invalidator(); let mut inner = self.inner.lock(); inner.add_invalidator(invalidator); StateRef { serialization_invalidator: None, inner, mutated: false, } } /// Gets the current value of the state. Untracked. pub fn get_untracked(&self) -> StateRef<'_, Option> { let inner = self.inner.lock(); StateRef { serialization_invalidator: None, inner, mutated: false, } } /// Sets the current state without comparing it with the old value. This /// should only be used if one is sure that the value has changed. pub fn set_unconditionally(&self, value: T) { let mut inner = self.inner.lock(); inner.set_unconditionally(Some(value)); } /// Unset the current value without comparing it with the old value. This /// should only be used if one is sure that the value has changed. pub fn unset_unconditionally(&self) { let mut inner = self.inner.lock(); inner.set_unconditionally(None); } /// Updates the current state with the `update` function. The `update` /// function need to return `true` when the value was modified. Exposing /// the current value from the `update` function is not allowed and will /// result in incorrect cache invalidation. pub fn update_conditionally(&self, update: impl FnOnce(&mut Option) -> bool) { let mut inner = self.inner.lock(); inner.update_conditionally(update); } } impl TransientState { /// Update the current state when the `value` is different from the current /// value. `T` must implement [PartialEq] for this to work. pub fn set(&self, value: T) { let mut inner = self.inner.lock(); inner.set(Some(value)); } /// Unset the current value. pub fn unset(&self) { let mut inner = self.inner.lock(); inner.set(None); } }