From 2e30c611ae277c263a42351f2f88b2ddc3aa576c Mon Sep 17 00:00:00 2001 From: psincf <44228825+psincf@users.noreply.github.com> Date: Sat, 4 May 2019 01:20:56 +0200 Subject: [PATCH] Make IdentityManager strongly typed --- wgpu-native/src/hub.rs | 89 ++++++++++++++++------------------------ wgpu-native/src/lib.rs | 45 ++++++++++---------- wgpu-native/src/track.rs | 14 ++++--- wgpu-remote/src/lib.rs | 19 ++++----- 4 files changed, 72 insertions(+), 95 deletions(-) diff --git a/wgpu-native/src/hub.rs b/wgpu-native/src/hub.rs index f07e5ec1e..07028a34b 100644 --- a/wgpu-native/src/hub.rs +++ b/wgpu-native/src/hub.rs @@ -15,6 +15,8 @@ use crate::{ ComputePipelineId, DeviceHandle, DeviceId, + Epoch, + Index, InstanceHandle, InstanceId, PipelineLayoutHandle, @@ -35,65 +37,45 @@ use crate::{ TextureViewId, TypedId }; - use lazy_static::lazy_static; #[cfg(feature = "local")] use parking_lot::Mutex; use parking_lot::RwLock; -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; use vec_map::VecMap; use std::{ops, sync::Arc}; -pub(crate) type Index = u32; -pub(crate) type Epoch = u32; - -#[repr(C)] -#[derive(Clone, Copy, Debug, Hash, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct Id(Index, Epoch); - -pub trait NewId { - fn new(index: Index, epoch: Epoch) -> Self; - fn index(&self) -> Index; - fn epoch(&self) -> Epoch; -} - -impl NewId for Id { - fn new(index: Index, epoch: Epoch) -> Self { - Id(index, epoch) - } - - fn index(&self) -> Index { - self.0 - } - - fn epoch(&self) -> Epoch { - self.1 - } -} - /// A simple structure to manage identities of objects. -#[derive(Default)] -pub struct IdentityManager { +pub struct IdentityManager { free: Vec, epochs: Vec, + phantom: std::marker::PhantomData, } -impl IdentityManager { - pub fn alloc(&mut self) -> Id { +impl Default for IdentityManager { + fn default() -> IdentityManager { + IdentityManager { + free: Default::default(), + epochs: Default::default(), + phantom: std::marker::PhantomData, + } + } +} + +impl IdentityManager { + pub fn alloc(&mut self) -> I { match self.free.pop() { - Some(index) => Id(index, self.epochs[index as usize]), + Some(index) => I::new(index, self.epochs[index as usize]), None => { - let id = Id(self.epochs.len() as Index, 1); - self.epochs.push(id.1); + let id = I::new(self.epochs.len() as Index, 1); + self.epochs.push(id.epoch()); id } } } - pub fn free(&mut self, Id(index, epoch): Id) { + pub fn free(&mut self, id: I) { + let (index, epoch) = (id.index(), id.epoch()); // avoid doing this check in release if cfg!(debug_assertions) { assert!(!self.free.contains(&index)); @@ -114,24 +96,24 @@ pub struct Storage { impl ops::Index for Storage { type Output = T; fn index(&self, id: I) -> &T { - let (ref value, epoch) = self.map[id.raw().index() as usize]; - assert_eq!(epoch, id.raw().1); + let (ref value, epoch) = self.map[id.index() as usize]; + assert_eq!(epoch, id.index()); value } } impl ops::IndexMut for Storage { fn index_mut(&mut self, id: I) -> &mut T { - let (ref mut value, epoch) = self.map[id.raw().index() as usize]; - assert_eq!(epoch, id.raw().1); + let (ref mut value, epoch) = self.map[id.index() as usize]; + assert_eq!(epoch, id.index()); value } } impl Storage { pub fn contains(&self, id: I) -> bool { - match self.map.get(id.raw().index() as usize) { - Some(&(_, epoch)) if epoch == id.raw().1 => true, + match self.map.get(id.index() as usize) { + Some(&(_, epoch)) if epoch == id.index() => true, _ => false, } } @@ -139,7 +121,7 @@ impl Storage { pub struct Registry { #[cfg(feature = "local")] - identity: Mutex, + identity: Mutex>, data: RwLock>, } @@ -166,25 +148,24 @@ impl ops::DerefMut for Registry { } } -impl Registry { +impl Registry { pub fn register(&self, id: I, value: T) { - let old = self.data.write().map.insert(id.raw().0 as usize, (value, id.raw().1)); + let old = self.data.write().map.insert(id.index() as usize, (value, id.epoch())); assert!(old.is_none()); } #[cfg(feature = "local")] pub fn register_local(&self, value: T) -> I { - let raw_id = self.identity.lock().alloc(); - let id:I = raw_id.into(); - self.register(id.clone(), value); + let id = self.identity.lock().alloc(); + self.register(id, value); id } pub fn unregister(&self, id: I) -> T { #[cfg(feature = "local")] - self.identity.lock().free(id.raw()); - let (value, epoch) = self.data.write().map.remove(id.raw().0 as usize).unwrap(); - assert_eq!(epoch, id.raw().1); + self.identity.lock().free(id); + let (value, epoch) = self.data.write().map.remove(id.index() as usize).unwrap(); + assert_eq!(epoch, id.epoch()); value } } diff --git a/wgpu-native/src/lib.rs b/wgpu-native/src/lib.rs index 62a8d8699..2aa1a7f2a 100644 --- a/wgpu-native/src/lib.rs +++ b/wgpu-native/src/lib.rs @@ -37,7 +37,6 @@ pub use self::instance::*; pub use self::pipeline::*; pub use self::resource::*; pub use self::swap_chain::*; -use self::hub::{Epoch, Id, Index, NewId}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -46,6 +45,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; type SubmissionIndex = usize; +pub(crate) type Index = u32; +pub(crate) type Epoch = u32; //TODO: make it private. Currently used for swapchain creation impl. #[derive(Debug)] @@ -169,15 +170,24 @@ pub struct ByteArray { pub length: usize, } +#[repr(C)] +#[derive(Clone, Copy, Debug, Hash, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +struct Id(Index, Epoch); + +pub trait TypedId { + fn new(index: Index, epoch: Epoch) -> Self; + fn index(&self) -> Index; + fn epoch(&self) -> Epoch; +} + macro_rules! define_id { ($i:ident) => { transparent!($i); typed_id!($i); - new_id!($i); } } - macro_rules! transparent { ($i:ident) => ( #[repr(transparent)] @@ -187,43 +197,30 @@ macro_rules! transparent { ) } -pub trait TypedId:From { - fn raw(&self) -> Id; -} - macro_rules! typed_id { - ($i:ident) => ( - impl From for $i { - fn from(id:Id) -> $i { - $i(id) - } - } - impl TypedId for $i { + ($i:ident) => ( + impl $i { fn raw(&self) -> Id { self.0 } } - ) -} - -macro_rules! new_id { - ($i:ident) => ( - impl NewId for $i { + impl TypedId for $i { fn new(index: Index, epoch: Epoch) -> Self { - let id = Id::new(index, epoch); + let id = Id(index, epoch); $i(id) } fn index(&self) -> Index { - (self.raw()).index() + (self.raw()).0 } fn epoch(&self) -> Epoch { - (self.raw()).epoch() - } + (self.raw()).1 + } } ) } + define_id!(InstanceId); type InstanceHandle = back::Instance; diff --git a/wgpu-native/src/track.rs b/wgpu-native/src/track.rs index b331eb293..71b6af068 100644 --- a/wgpu-native/src/track.rs +++ b/wgpu-native/src/track.rs @@ -1,7 +1,9 @@ use crate::{ - hub::{Epoch, Index, NewId, Storage}, + hub::{Storage}, resource::{BufferUsageFlags, TextureUsageFlags}, BufferId, + Epoch, + Index, RefCount, TextureId, TextureViewId, @@ -133,7 +135,7 @@ impl TrackerSet { } } -impl + PartialEq> Tracker { +impl + PartialEq> Tracker { pub fn new() -> Self { Tracker { map: FastHashMap::default(), @@ -277,7 +279,7 @@ impl + PartialEq> Tracker + PartialEq> Tracker { +impl + PartialEq> Tracker { fn _get_with_usage<'a, T: 'a + Borrow>( &mut self, storage: &'a Storage, @@ -285,7 +287,7 @@ impl + Pa usage: U, permit: TrackPermit, ) -> Result<(&'a T, Tracktion), U> { - let item = &storage[id.clone()]; + let item = &storage[id]; self.transit(id, item.borrow(), usage, permit) .map(|tracktion| (item, tracktion)) } @@ -296,7 +298,7 @@ impl + Pa id: I, usage: U, ) -> Result<&'a T, U> { - let item = &storage[id.clone()]; + let item = &storage[id]; self.transit(id, item.borrow(), usage, TrackPermit::EXTEND) .map(|_tracktion| item) } @@ -307,7 +309,7 @@ impl + Pa id: I, usage: U, ) -> Result<(&'a T, Option), U> { - let item = &storage[id.clone()]; + let item = &storage[id]; self.transit(id, item.borrow(), usage, TrackPermit::REPLACE) .map(|tracktion| { ( diff --git a/wgpu-remote/src/lib.rs b/wgpu-remote/src/lib.rs index 423106778..0fc43a0dd 100644 --- a/wgpu-remote/src/lib.rs +++ b/wgpu-remote/src/lib.rs @@ -1,6 +1,6 @@ //TODO: remove once `cbindgen` is smart enough extern crate wgpu_native as wgn; -use wgn::TypedId; +use wgn::{AdapterId, DeviceId, InstanceId}; use crate::server::Server; @@ -35,8 +35,8 @@ enum GlobalMessage { #[derive(Default)] struct IdentityHub { - adapters: wgn::IdentityManager, - devices: wgn::IdentityManager, + adapters: wgn::IdentityManager, + devices: wgn::IdentityManager, } pub struct Client { @@ -47,7 +47,7 @@ pub struct Client { pub struct ClientFactory { channel: ipc::IpcSender, - instance_identities: Mutex, + instance_identities: Mutex>, } #[repr(C)] @@ -93,8 +93,7 @@ pub extern "C" fn wgpu_terminate(factory: *mut ClientFactory) { #[no_mangle] pub extern "C" fn wgpu_client_create(factory: &ClientFactory) -> *mut Client { - let id = factory.instance_identities.lock().alloc(); - let instance_id = id.into(); + let instance_id = factory.instance_identities.lock().alloc(); let msg = GlobalMessage::Instance(InstanceMessage::Create(instance_id)); factory.channel.send(msg).unwrap(); let client = Client { @@ -110,7 +109,7 @@ pub extern "C" fn wgpu_client_destroy(factory: &ClientFactory, client: *mut Clie let client = unsafe { Box::from_raw(client) }; - factory.instance_identities.lock().free(client.instance_id.raw()); + factory.instance_identities.lock().free(client.instance_id); let msg = GlobalMessage::Instance(InstanceMessage::Destroy(client.instance_id)); client.channel.send(msg).unwrap(); } @@ -120,8 +119,7 @@ pub extern "C" fn wgpu_client_get_adapter( client: &Client, desc: &wgn::AdapterDescriptor, ) -> wgn::AdapterId { - let id = client.identity.lock().adapters.alloc(); - let adapter_id = id.into(); + let adapter_id = client.identity.lock().adapters.alloc(); let msg = GlobalMessage::Instance(InstanceMessage::InstanceGetAdapter( client.instance_id, desc.clone(), @@ -137,8 +135,7 @@ pub extern "C" fn wgpu_client_adapter_create_device( adapter_id: wgn::AdapterId, desc: &wgn::DeviceDescriptor, ) -> wgn::DeviceId { - let id = client.identity.lock().devices.alloc(); - let device_id = id.into(); + let device_id = client.identity.lock().devices.alloc(); let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice( adapter_id, desc.clone(),