Commit fe4c6745 authored by Benjamin Woodruff's avatar Benjamin Woodruff

WIP

parent 3f8febe2
...@@ -5,7 +5,7 @@ use std::{ ...@@ -5,7 +5,7 @@ use std::{
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexSet, InvalidationReason, InvalidationReasonKind, util::StaticOrArc}; use turbo_tasks::{FxIndexSet, InvalidationReason, InvalidationReasonKind, StaticOrArc};
/// Invalidation was caused by a file change detected by the file watcher /// Invalidation was caused by a file change detected by the file watcher
#[derive(PartialEq, Eq, Hash)] #[derive(PartialEq, Eq, Hash)]
......
...@@ -21,8 +21,8 @@ use serde::{Deserialize, Serialize}; ...@@ -21,8 +21,8 @@ use serde::{Deserialize, Serialize};
use tracing::instrument; use tracing::instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ use turbo_tasks::{
FxIndexSet, InvalidationReason, InvalidationReasonKind, Invalidator, parallel, spawn_thread, FxIndexSet, InvalidationReason, InvalidationReasonKind, Invalidator, StaticOrArc, parallel,
util::StaticOrArc, spawn_thread,
}; };
use crate::{ use crate::{
......
...@@ -17,12 +17,13 @@ use rustc_hash::FxHashMap; ...@@ -17,12 +17,13 @@ use rustc_hash::FxHashMap;
use tokio::sync::mpsc::Receiver; use tokio::sync::mpsc::Receiver;
use turbo_tasks::{ use turbo_tasks::{
CellId, ExecutionId, InvalidationReason, LocalTaskId, MagicAny, RawVc, ReadCellOptions, CellId, ExecutionId, InvalidationReason, LocalTaskId, MagicAny, RawVc, ReadCellOptions,
ReadOutputOptions, TaskId, TaskPersistence, TraitTypeId, TurboTasksApi, TurboTasksCallApi, ReadOutputOptions, StaticOrArc, TaskId, TaskPersistence, TraitTypeId, TurboTasksApi,
TurboTasksCallApi,
backend::{CellContent, TaskCollectiblesMap, TypedCellContent}, backend::{CellContent, TaskCollectiblesMap, TypedCellContent},
event::{Event, EventListener}, event::{Event, EventListener},
message_queue::CompilationEvent, message_queue::CompilationEvent,
test_helpers::with_turbo_tasks_for_testing, test_helpers::with_turbo_tasks_for_testing,
util::{SharedError, StaticOrArc}, util::SharedError,
}; };
pub use crate::run::{ pub use crate::run::{
...@@ -164,7 +165,7 @@ impl TurboTasksApi for VcStorage { ...@@ -164,7 +165,7 @@ impl TurboTasksApi for VcStorage {
fn invalidate_with_reason( fn invalidate_with_reason(
&self, &self,
_task: TaskId, _task: TaskId,
_reason: turbo_tasks::util::StaticOrArc<dyn turbo_tasks::InvalidationReason>, _reason: turbo_tasks::StaticOrArc<dyn turbo_tasks::InvalidationReason>,
) { ) {
unreachable!() unreachable!()
} }
......
...@@ -14,10 +14,9 @@ use turbo_dyn_eq_hash::{ ...@@ -14,10 +14,9 @@ use turbo_dyn_eq_hash::{
}; };
use crate::{ use crate::{
FxIndexMap, FxIndexSet, TaskId, TurboTasksApi, FxIndexMap, FxIndexSet, StaticOrArc, TaskId, TurboTasksApi,
manager::{current_task_if_available, mark_invalidator, with_turbo_tasks}, manager::{current_task_if_available, mark_invalidator, with_turbo_tasks},
trace::TraceRawVcs, trace::TraceRawVcs,
util::StaticOrArc,
}; };
/// Get an [`Invalidator`] that can be used to invalidate the current task /// Get an [`Invalidator`] that can be used to invalidate the current task
......
...@@ -128,6 +128,7 @@ pub use task::{SharedReference, TypedSharedReference, task_input::TaskInput}; ...@@ -128,6 +128,7 @@ pub use task::{SharedReference, TypedSharedReference, task_input::TaskInput};
pub use task_execution_reason::TaskExecutionReason; pub use task_execution_reason::TaskExecutionReason;
pub use trait_ref::{IntoTraitRef, TraitRef}; pub use trait_ref::{IntoTraitRef, TraitRef};
pub use turbo_tasks_macros::{TaskInput, function, value_impl}; pub use turbo_tasks_macros::{TaskInput, function, value_impl};
pub use util::{StaticOrArc, StaticOrWeak};
pub use value::{TransientInstance, TransientValue}; pub use value::{TransientInstance, TransientValue};
pub use value_type::{TraitMethod, TraitType, ValueType}; pub use value_type::{TraitMethod, TraitType, ValueType};
pub use vc::{ pub use vc::{
......
...@@ -7,7 +7,7 @@ use std::{ ...@@ -7,7 +7,7 @@ use std::{
mem::ManuallyDrop, mem::ManuallyDrop,
ops::Deref, ops::Deref,
pin::Pin, pin::Pin,
sync::{Arc, LazyLock}, sync::{Arc, LazyLock, Weak},
task::{Context, Poll}, task::{Context, Poll},
thread::available_parallelism, thread::available_parallelism,
time::Duration, time::Duration,
...@@ -17,7 +17,7 @@ use anyhow::{Error, anyhow}; ...@@ -17,7 +17,7 @@ use anyhow::{Error, anyhow};
use pin_project_lite::pin_project; use pin_project_lite::pin_project;
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub use super::{ pub use crate::{
id_factory::{IdFactory, IdFactoryWithReuse}, id_factory::{IdFactory, IdFactoryWithReuse},
once_map::*, once_map::*,
}; };
...@@ -237,6 +237,64 @@ impl<T: ?Sized + Debug + 'static> Debug for StaticOrArc<T> { ...@@ -237,6 +237,64 @@ impl<T: ?Sized + Debug + 'static> Debug for StaticOrArc<T> {
} }
} }
/// Weak pointer that stores data either in a [Weak] or as a static reference.
/// Can be upgraded to [StaticOrArc].
pub enum StaticOrWeak<T: ?Sized + 'static> {
Static(&'static T),
Weak(Weak<T>),
}
impl<T: ?Sized + 'static> StaticOrWeak<T> {
/// Attempts to upgrade the weak pointer to a [StaticOrArc].
///
/// Returns [None] if the inner value has been dropped (for the [Weak] variant).
/// Always succeeds for the [Static] variant.
pub fn upgrade(&self) -> Option<StaticOrArc<T>> {
match self {
Self::Static(s) => Some(StaticOrArc::Static(s)),
Self::Weak(w) => w.upgrade().map(StaticOrArc::Shared),
}
}
/// Returns true if the two weak pointers point to the same allocation.
/// For static references, this compares pointer equality.
pub fn ptr_eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Static(a), Self::Static(b)) => std::ptr::eq(*a, *b),
(Self::Weak(a), Self::Weak(b)) => Weak::ptr_eq(a, b),
_ => false,
}
}
}
impl<T: ?Sized + 'static> StaticOrArc<T> {
/// Creates a weak pointer to this allocation.
pub fn downgrade(&self) -> StaticOrWeak<T> {
match self {
Self::Static(s) => StaticOrWeak::Static(s),
Self::Shared(arc) => StaticOrWeak::Weak(Arc::downgrade(arc)),
}
}
}
impl<T: ?Sized + 'static> Clone for StaticOrWeak<T> {
fn clone(&self) -> Self {
match self {
Self::Static(s) => Self::Static(s),
Self::Weak(w) => Self::Weak(w.clone()),
}
}
}
impl<T: ?Sized + Debug + 'static> Debug for StaticOrWeak<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Static(s) => f.debug_tuple("Static").field(s).finish(),
Self::Weak(w) => f.debug_tuple("Weak").field(w).finish(),
}
}
}
pin_project! { pin_project! {
/// A future that wraps another future and applies a function on every poll call. /// A future that wraps another future and applies a function on every poll call.
pub struct WrapFuture<F, W> { pub struct WrapFuture<F, W> {
...@@ -391,4 +449,56 @@ mod tests { ...@@ -391,4 +449,56 @@ mod tests {
assert_eq!(Arc::strong_count(&arc), 1); assert_eq!(Arc::strong_count(&arc), 1);
} }
} }
#[test]
fn test_static_or_weak_arc_upgrade_downgrade() {
let arc: StaticOrArc<i32> = Arc::new(42).into();
let weak: StaticOrWeak<i32> = arc.downgrade();
// Upgrade should succeed while Arc is alive
assert_eq!(*weak.upgrade().unwrap(), 42);
// Clone the weak pointer
let weak2 = weak.clone();
// Drop the Arc
drop(arc);
// Upgrade should fail after Arc is dropped
assert!(weak.upgrade().is_none());
assert!(weak2.upgrade().is_none());
}
#[test]
fn test_static_or_weak_static_references() {
static VALUE: i32 = 100;
let static_arc: StaticOrArc<i32> = StaticOrArc::Static(&VALUE);
let static_weak = static_arc.downgrade();
// Upgrade should always succeed for static references
assert_eq!(*static_weak.upgrade().unwrap(), 100);
// Even after dropping the StaticOrArc, upgrade should still work
drop(static_arc);
assert_eq!(*static_weak.upgrade().unwrap(), 100);
}
#[test]
fn test_static_or_weak_ptr_eq() {
// Test pointer equality with Arc
let arc: StaticOrArc<i32> = Arc::new(42).into();
let weak1 = arc.downgrade();
let weak2 = weak1.clone();
assert!(weak1.ptr_eq(&weak2));
// Test pointer equality with static references
static VALUE: i32 = 100;
let static_arc: StaticOrArc<i32> = StaticOrArc::Static(&VALUE);
let static_weak1 = static_arc.downgrade();
let static_weak2 = static_weak1.clone();
assert!(static_weak1.ptr_eq(&static_weak2));
// Different types should not be equal
assert!(!weak1.ptr_eq(&static_weak1));
}
} }
...@@ -4,7 +4,7 @@ use std::{ ...@@ -4,7 +4,7 @@ use std::{
}; };
use hyper::{Method, Uri}; use hyper::{Method, Uri};
use turbo_tasks::{FxIndexSet, InvalidationReason, InvalidationReasonKind, util::StaticOrArc}; use turbo_tasks::{FxIndexSet, InvalidationReason, InvalidationReasonKind, StaticOrArc};
/// Computation was caused by a request to the server. /// Computation was caused by a request to the server.
#[derive(PartialEq, Eq, Hash)] #[derive(PartialEq, Eq, Hash)]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment