Make IdentityManager strongly typed

This commit is contained in:
psincf committed 2019-05-04 01:20:56 +02:00
1 parent 10547b937f
commit 2e30c611ae
4 files changed
+72 -95

No files matched your search

+35 -54
View File
@@ -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<I:TypedId> {
free: Vec<Index>,
epochs: Vec<Epoch>,
phantom: std::marker::PhantomData<I>,
}
impl IdentityManager {
pub fn alloc(&mut self) -> Id {
impl<I: TypedId> Default for IdentityManager<I> {
fn default() -> IdentityManager<I> {
IdentityManager {
free: Default::default(),
epochs: Default::default(),
phantom: std::marker::PhantomData,
}
}
}
impl<I: TypedId> IdentityManager<I> {
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<T, I:TypedId> {
impl<T, I:TypedId> ops::Index<I> for Storage<T, I> {
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<T, I:TypedId> ops::IndexMut<I> for Storage<T, I> {
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<T, I:TypedId> Storage<T, I> {
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<T, I:TypedId> Storage<T, I> {
pub struct Registry<T, I:TypedId> {
#[cfg(feature = "local")]
identity: Mutex<IdentityManager>,
identity: Mutex<IdentityManager<I>>,
data: RwLock<Storage<T, I>>,
}
@@ -166,25 +148,24 @@ impl<T, I: TypedId> ops::DerefMut for Registry<T, I> {
}
}
impl<T, I: TypedId + Clone> Registry<T, I> {
impl<T, I: TypedId + Copy> Registry<T, I> {
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
}
}
+21 -24
View File
@@ -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<Id> {
fn raw(&self) -> Id;
}
macro_rules! typed_id {
($i:ident) => (
impl From<Id> 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;
+8 -6
View File
@@ -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<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I, U> {
impl<I: TypedId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I, U> {
pub fn new() -> Self {
Tracker {
map: FastHashMap::default(),
@@ -277,7 +279,7 @@ impl<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I
}
}
impl<I: TypedId + NewId + Clone, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I, U> {
impl<I: TypedId + Copy, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I, U> {
fn _get_with_usage<'a, T: 'a + Borrow<RefCount>>(
&mut self,
storage: &'a Storage<T, I>,
@@ -285,7 +287,7 @@ impl<I: TypedId + NewId + Clone, U: Copy + GenericUsage + BitOr<Output = U> + Pa
usage: U,
permit: TrackPermit,
) -> Result<(&'a T, Tracktion<U>), 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<I: TypedId + NewId + Clone, U: Copy + GenericUsage + BitOr<Output = U> + 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<I: TypedId + NewId + Clone, U: Copy + GenericUsage + BitOr<Output = U> + Pa
id: I,
usage: U,
) -> Result<(&'a T, Option<U>), U> {
let item = &storage[id.clone()];
let item = &storage[id];
self.transit(id, item.borrow(), usage, TrackPermit::REPLACE)
.map(|tracktion| {
(
+8 -11
View File
@@ -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<AdapterId>,
devices: wgn::IdentityManager<DeviceId>,
}
pub struct Client {
@@ -47,7 +47,7 @@ pub struct Client {
pub struct ClientFactory {
channel: ipc::IpcSender<GlobalMessage>,
instance_identities: Mutex<wgn::IdentityManager>,
instance_identities: Mutex<wgn::IdentityManager<InstanceId>>,
}
#[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(),