From b0e02bc6306fe1aabb89c28c9fe0f5fd1201d2fb Mon Sep 17 00:00:00 2001 From: Benjamin Woodruff Date: Fri, 27 Sep 2024 11:51:09 -0700 Subject: [PATCH] feat(turbo-tasks): Add ResolvedVc versions of casting functions --- .../crates/turbo-tasks/src/vc/resolved.rs | 75 ++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/turbopack/crates/turbo-tasks/src/vc/resolved.rs b/turbopack/crates/turbo-tasks/src/vc/resolved.rs index be126034f20ab..3f194faed1567 100644 --- a/turbopack/crates/turbo-tasks/src/vc/resolved.rs +++ b/turbopack/crates/turbo-tasks/src/vc/resolved.rs @@ -24,7 +24,7 @@ use serde::{Deserialize, Serialize}; use crate::{ trace::{TraceRawVcs, TraceRawVcsContext}, vc::Vc, - RcStr, VcRead, VcTransparentRead, VcValueType, + RcStr, ResolveTypeError, Upcast, VcRead, VcTransparentRead, VcValueTrait, VcValueType, }; #[derive(Serialize, Deserialize)] @@ -122,6 +122,79 @@ where } } +impl ResolvedVc +where + T: ?Sized + Send, +{ + /// Upcasts the given `ResolvedVc` to a `ResolvedVc>`. + /// + /// See also: [`Vc::upcast`]. + #[inline(always)] + pub fn upcast(this: Self) -> ResolvedVc + where + T: Upcast, + K: VcValueTrait + ?Sized + Send, + { + ResolvedVc { + node: Vc::upcast(this.node), + } + } +} + +impl ResolvedVc +where + T: VcValueTrait + ?Sized + Send, +{ + /// Attempts to sidecast the given `Vc>` to a `Vc>`. + /// + /// Returns `None` if the underlying value type does not implement `K`. + /// + /// **Note:** if the trait `T` is required to implement `K`, use [`ResolvedVc::upcast`] instead. + /// This provides stronger guarantees, removing the need for a [`Result`] return type. + /// + /// See also: [`Vc::try_resolve_sidecast`]. + pub async fn try_sidecast(this: Self) -> Result>, ResolveTypeError> + where + K: VcValueTrait + ?Sized + Send, + { + // must be async, as we must read the cell to determine the type + Ok(Vc::try_resolve_sidecast(this.node) + .await? + .map(|node| ResolvedVc { node })) + } + + /// Attempts to downcast the given `ResolvedVc>` to a `ResolvedVc`, where `K` + /// is of the form `Box`, and `L` is a value trait. + /// + /// Returns `None` if the underlying value type is not a `K`. + /// + /// See also: [`Vc::try_resolve_downcast`]. + pub async fn try_downcast(this: Self) -> Result>, ResolveTypeError> + where + K: Upcast, + K: VcValueTrait + ?Sized + Send, + { + Ok(Vc::try_resolve_downcast(this.node) + .await? + .map(|node| ResolvedVc { node })) + } + + /// Attempts to downcast the given `Vc>` to a `Vc`, where `K` is a value type. + /// + /// Returns `None` if the underlying value type is not a `K`. + /// + /// See also: [`Vc::try_resolve_downcast_type`]. + pub async fn try_downcast_type(this: Self) -> Result>, ResolveTypeError> + where + K: Upcast, + K: VcValueType, + { + Ok(Vc::try_resolve_downcast_type(this.node) + .await? + .map(|node| ResolvedVc { node })) + } +} + impl std::fmt::Debug for ResolvedVc where T: Send,