1use crate::{Epoch, Index};
2use std::{cmp::Ordering, fmt, marker::PhantomData};
3use wgt::Backend;
4
5#[cfg(feature = "id32")]
6type IdType = u32;
7#[cfg(not(feature = "id32"))]
8type IdType = u64;
9#[cfg(feature = "id32")]
10type NonZeroId = std::num::NonZeroU32;
11#[cfg(not(feature = "id32"))]
12type NonZeroId = std::num::NonZeroU64;
13#[cfg(feature = "id32")]
14type ZippedIndex = u16;
15#[cfg(not(feature = "id32"))]
16type ZippedIndex = Index;
17
18const INDEX_BITS: usize = std::mem::size_of::<ZippedIndex>() * 8;
19const EPOCH_BITS: usize = INDEX_BITS - BACKEND_BITS;
20const BACKEND_BITS: usize = 3;
21const BACKEND_SHIFT: usize = INDEX_BITS * 2 - BACKEND_BITS;
22pub const EPOCH_MASK: u32 = (1 << (EPOCH_BITS)) - 1;
23type Dummy = hal::api::Empty;
24
25#[repr(transparent)]
55#[cfg_attr(feature = "trace", derive(serde::Serialize), serde(into = "SerialId"))]
56#[cfg_attr(
57 feature = "replay",
58 derive(serde::Deserialize),
59 serde(from = "SerialId")
60)]
61#[cfg_attr(
62 all(feature = "serde", not(feature = "trace")),
63 derive(serde::Serialize)
64)]
65#[cfg_attr(
66 all(feature = "serde", not(feature = "replay")),
67 derive(serde::Deserialize)
68)]
69pub struct Id<T>(NonZeroId, PhantomData<T>);
70
71#[allow(dead_code)]
73#[cfg_attr(feature = "trace", derive(serde::Serialize))]
74#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
75enum SerialId {
76 Id(Index, Epoch, Backend),
78}
79#[cfg(feature = "trace")]
80impl<T> From<Id<T>> for SerialId {
81 fn from(id: Id<T>) -> Self {
82 let (index, epoch, backend) = id.unzip();
83 Self::Id(index, epoch, backend)
84 }
85}
86#[cfg(feature = "replay")]
87impl<T> From<SerialId> for Id<T> {
88 fn from(id: SerialId) -> Self {
89 match id {
90 SerialId::Id(index, epoch, backend) => TypedId::zip(index, epoch, backend),
91 }
92 }
93}
94
95impl<T> Id<T> {
96 pub unsafe fn from_raw(raw: NonZeroId) -> Self {
100 Self(raw, PhantomData)
101 }
102
103 #[allow(dead_code)]
104 pub(crate) fn dummy(index: u32) -> Valid<Self> {
105 Valid(Id::zip(index, 1, Backend::Empty))
106 }
107
108 pub fn backend(self) -> Backend {
109 match self.0.get() >> (BACKEND_SHIFT) as u8 {
110 0 => Backend::Empty,
111 1 => Backend::Vulkan,
112 2 => Backend::Metal,
113 3 => Backend::Dx12,
114 4 => Backend::Dx11,
115 5 => Backend::Gl,
116 _ => unreachable!(),
117 }
118 }
119}
120
121impl<T> Copy for Id<T> {}
122
123impl<T> Clone for Id<T> {
124 fn clone(&self) -> Self {
125 Self(self.0, PhantomData)
126 }
127}
128
129impl<T> fmt::Debug for Id<T> {
130 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
131 self.unzip().fmt(formatter)
132 }
133}
134
135impl<T> std::hash::Hash for Id<T> {
136 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
137 self.0.hash(state);
138 }
139}
140
141impl<T> PartialEq for Id<T> {
142 fn eq(&self, other: &Self) -> bool {
143 self.0 == other.0
144 }
145}
146
147impl<T> Eq for Id<T> {}
148
149impl<T> PartialOrd for Id<T> {
150 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
151 self.0.partial_cmp(&other.0)
152 }
153}
154
155impl<T> Ord for Id<T> {
156 fn cmp(&self, other: &Self) -> Ordering {
157 self.0.cmp(&other.0)
158 }
159}
160
161#[repr(transparent)]
164#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
165#[cfg_attr(feature = "trace", derive(serde::Serialize))]
166#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
167pub(crate) struct Valid<I>(pub I);
168
169pub trait TypedId: Copy {
175 fn zip(index: Index, epoch: Epoch, backend: Backend) -> Self;
176 fn unzip(self) -> (Index, Epoch, Backend);
177 fn into_raw(self) -> NonZeroId;
178}
179
180#[allow(trivial_numeric_casts)]
181impl<T> TypedId for Id<T> {
182 fn zip(index: Index, epoch: Epoch, backend: Backend) -> Self {
183 assert_eq!(0, epoch >> EPOCH_BITS);
184 assert_eq!(0, (index as IdType) >> INDEX_BITS);
185 let v = index as IdType
186 | ((epoch as IdType) << INDEX_BITS)
187 | ((backend as IdType) << BACKEND_SHIFT);
188 Id(NonZeroId::new(v).unwrap(), PhantomData)
189 }
190
191 fn unzip(self) -> (Index, Epoch, Backend) {
192 (
193 (self.0.get() as ZippedIndex) as Index,
194 (((self.0.get() >> INDEX_BITS) as ZippedIndex) & (EPOCH_MASK as ZippedIndex)) as Index,
195 self.backend(),
196 )
197 }
198
199 fn into_raw(self) -> NonZeroId {
200 self.0
201 }
202}
203
204pub type AdapterId = Id<crate::instance::Adapter<Dummy>>;
205pub type SurfaceId = Id<crate::instance::Surface>;
206pub type DeviceId = Id<crate::device::Device<Dummy>>;
208pub type QueueId = DeviceId;
209pub type BufferId = Id<crate::resource::Buffer<Dummy>>;
211pub type StagingBufferId = Id<crate::resource::StagingBuffer<Dummy>>;
212pub type TextureViewId = Id<crate::resource::TextureView<Dummy>>;
213pub type TextureId = Id<crate::resource::Texture<Dummy>>;
214pub type SamplerId = Id<crate::resource::Sampler<Dummy>>;
215pub type BindGroupLayoutId = Id<crate::binding_model::BindGroupLayout<Dummy>>;
217pub type PipelineLayoutId = Id<crate::binding_model::PipelineLayout<Dummy>>;
218pub type BindGroupId = Id<crate::binding_model::BindGroup<Dummy>>;
219pub type ShaderModuleId = Id<crate::pipeline::ShaderModule<Dummy>>;
221pub type RenderPipelineId = Id<crate::pipeline::RenderPipeline<Dummy>>;
222pub type ComputePipelineId = Id<crate::pipeline::ComputePipeline<Dummy>>;
223pub type CommandEncoderId = CommandBufferId;
225pub type CommandBufferId = Id<crate::command::CommandBuffer<Dummy>>;
226pub type RenderPassEncoderId = *mut crate::command::RenderPass;
227pub type ComputePassEncoderId = *mut crate::command::ComputePass;
228pub type RenderBundleEncoderId = *mut crate::command::RenderBundleEncoder;
229pub type RenderBundleId = Id<crate::command::RenderBundle<Dummy>>;
230pub type QuerySetId = Id<crate::resource::QuerySet<Dummy>>;
231
232#[test]
233fn test_id_backend() {
234 for &b in &[
235 Backend::Empty,
236 Backend::Vulkan,
237 Backend::Metal,
238 Backend::Dx12,
239 Backend::Dx11,
240 Backend::Gl,
241 ] {
242 let id: Id<()> = Id::zip(1, 0, b);
243 let (_id, _epoch, backend) = id.unzip();
244 assert_eq!(id.backend(), b);
245 assert_eq!(backend, b);
246 }
247}
248
249#[test]
250fn test_id() {
251 let last_index = ((1u64 << INDEX_BITS) - 1) as Index;
252 let indexes = [1, last_index / 2 - 1, last_index / 2 + 1, last_index];
253 let epochs = [1, EPOCH_MASK / 2 - 1, EPOCH_MASK / 2 + 1, EPOCH_MASK];
254 let backends = [
255 Backend::Empty,
256 Backend::Vulkan,
257 Backend::Metal,
258 Backend::Dx12,
259 Backend::Dx11,
260 Backend::Gl,
261 ];
262 for &i in &indexes {
263 for &e in &epochs {
264 for &b in &backends {
265 let id: Id<()> = Id::zip(i, e, b);
266 let (index, epoch, backend) = id.unzip();
267 assert_eq!(index, i);
268 assert_eq!(epoch, e);
269 assert_eq!(backend, b);
270 }
271 }
272 }
273}