turbo_tasks/
id.rs

1use std::{
2    fmt::{Debug, Display},
3    mem::transmute_copy,
4    num::{NonZero, NonZeroU64, TryFromIntError},
5    ops::Deref,
6};
7
8use serde::{Deserialize, Serialize, de::Visitor};
9
10use crate::{
11    TaskPersistence, registry,
12    trace::{TraceRawVcs, TraceRawVcsContext},
13};
14
15macro_rules! define_id {
16    (
17        $name:ident : $primitive:ty
18        $(,derive($($derive:ty),*))?
19        $(,serde($serde:tt))?
20        $(,doc = $doc:literal)*
21        $(,)?
22    ) => {
23        $(#[doc = $doc])*
24        #[derive(Hash, Clone, Copy, PartialEq, Eq, PartialOrd, Ord $($(,$derive)*)? )]
25        $(#[serde($serde)])?
26        pub struct $name {
27            id: NonZero<$primitive>,
28        }
29
30        impl $name {
31            pub const MIN: Self = Self { id: NonZero::<$primitive>::MIN };
32            pub const MAX: Self = Self { id: NonZero::<$primitive>::MAX };
33
34            /// Constructs a wrapper type from the numeric identifier.
35            ///
36            /// # Safety
37            ///
38            /// The passed `id` must not be zero.
39            pub const unsafe fn new_unchecked(id: $primitive) -> Self {
40                Self { id: unsafe { NonZero::<$primitive>::new_unchecked(id) } }
41            }
42
43            /// Allows `const` conversion to a [`NonZeroU64`], useful with
44            /// [`crate::id_factory::IdFactory::new_const`].
45            pub const fn to_non_zero_u64(self) -> NonZeroU64 {
46                const {
47                    assert!(<$primitive>::BITS <= u64::BITS);
48                }
49                unsafe { NonZeroU64::new_unchecked(self.id.get() as u64) }
50            }
51        }
52
53        impl Display for $name {
54            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55                write!(f, concat!(stringify!($name), " {}"), self.id)
56            }
57        }
58
59        impl Deref for $name {
60            type Target = $primitive;
61
62            fn deref(&self) -> &Self::Target {
63                unsafe { transmute_copy(&&self.id) }
64            }
65        }
66
67        define_id!(@impl_try_from_primitive_conversion $name $primitive);
68
69        impl From<NonZero<$primitive>> for $name {
70            fn from(id: NonZero::<$primitive>) -> Self {
71                Self {
72                    id,
73                }
74            }
75        }
76
77        impl From<$name> for NonZeroU64 {
78            fn from(id: $name) -> Self {
79                id.to_non_zero_u64()
80            }
81        }
82
83        impl TraceRawVcs for $name {
84            fn trace_raw_vcs(&self, _trace_context: &mut TraceRawVcsContext) {}
85        }
86    };
87    (
88        @impl_try_from_primitive_conversion $name:ident u64
89    ) => {
90        // we get a `TryFrom` blanket impl for free via the `From` impl
91    };
92    (
93        @impl_try_from_primitive_conversion $name:ident $primitive:ty
94    ) => {
95        impl TryFrom<$primitive> for $name {
96            type Error = TryFromIntError;
97
98            fn try_from(id: $primitive) -> Result<Self, Self::Error> {
99                Ok(Self {
100                    id: NonZero::try_from(id)?
101                })
102            }
103        }
104
105        impl TryFrom<NonZeroU64> for $name {
106            type Error = TryFromIntError;
107
108            fn try_from(id: NonZeroU64) -> Result<Self, Self::Error> {
109                Ok(Self { id: NonZero::try_from(id)? })
110            }
111        }
112    };
113}
114
115define_id!(TaskId: u32, derive(Serialize, Deserialize), serde(transparent));
116define_id!(ValueTypeId: u32);
117define_id!(TraitTypeId: u32);
118define_id!(BackendJobId: u32);
119define_id!(SessionId: u32, derive(Debug, Serialize, Deserialize), serde(transparent));
120define_id!(
121    LocalTaskId: u32,
122    derive(Debug, Serialize, Deserialize),
123    serde(transparent),
124    doc = "Represents the nth `local` function call inside a task.",
125);
126define_id!(
127    ExecutionId: u16,
128    derive(Debug, Serialize, Deserialize),
129    serde(transparent),
130    doc = "An identifier for a specific task execution. Used to assert that local `Vc`s don't \
131        leak. This value may overflow and re-use old values.",
132);
133
134impl Debug for TaskId {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        f.debug_struct("TaskId").field("id", &self.id).finish()
137    }
138}
139
140pub const TRANSIENT_TASK_BIT: u32 = 0x8000_0000;
141
142impl TaskId {
143    pub fn is_transient(&self) -> bool {
144        **self & TRANSIENT_TASK_BIT != 0
145    }
146    pub fn persistence(&self) -> TaskPersistence {
147        // tasks with `TaskPersistence::LocalCells` have no `TaskId`, so we can ignore that case
148        if self.is_transient() {
149            TaskPersistence::Transient
150        } else {
151            TaskPersistence::Persistent
152        }
153    }
154}
155
156macro_rules! make_serializable {
157    ($ty:ty, $get_global_name:path, $get_id:path, $visitor_name:ident) => {
158        impl Serialize for $ty {
159            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
160            where
161                S: serde::Serializer,
162            {
163                serializer.serialize_str($get_global_name(*self))
164            }
165        }
166
167        impl<'de> Deserialize<'de> for $ty {
168            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
169            where
170                D: serde::Deserializer<'de>,
171            {
172                deserializer.deserialize_str($visitor_name)
173            }
174        }
175
176        struct $visitor_name;
177
178        impl<'de> Visitor<'de> for $visitor_name {
179            type Value = $ty;
180
181            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
182                formatter.write_str(concat!("a name of a registered ", stringify!($ty)))
183            }
184
185            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
186            where
187                E: serde::de::Error,
188            {
189                $get_id(v).ok_or_else(|| E::unknown_variant(v, &[]))
190            }
191        }
192
193        impl Debug for $ty {
194            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195                f.debug_struct(stringify!($ty))
196                    .field("id", &self.id)
197                    .field("name", &$get_global_name(*self))
198                    .finish()
199            }
200        }
201    };
202}
203
204make_serializable!(
205    ValueTypeId,
206    registry::get_value_type_global_name,
207    registry::get_value_type_id_by_global_name,
208    ValueTypeVisitor
209);
210make_serializable!(
211    TraitTypeId,
212    registry::get_trait_type_global_name,
213    registry::get_trait_type_id_by_global_name,
214    TraitTypeVisitor
215);