portability/libportability-gfx/src/handle.rs

106 lines
2 KiB
Rust
Raw Normal View History

use VK_NULL_HANDLE;
2018-02-16 10:31:10 -05:00
use std::{borrow, fmt, ops};
2017-09-06 21:34:41 -04:00
static ICD_LOADER_MAGIC: u32 = 0x01CDC0DE;
2017-09-06 21:34:41 -04:00
#[repr(C)]
2017-11-13 22:55:43 -05:00
pub struct Handle<T>(*mut T);
2017-09-06 21:34:41 -04:00
impl<T> Handle<T> {
pub fn new(value: T) -> Self {
2017-11-13 22:55:43 -05:00
let ptr = Box::into_raw(Box::new(value));
Handle(ptr)
2017-09-06 21:34:41 -04:00
}
pub fn unwrap(self) -> Box<T> {
2017-11-13 22:55:43 -05:00
unsafe { Box::from_raw(self.0) }
2017-09-06 21:34:41 -04:00
}
pub fn is_null(&self) -> bool {
self.0 == VK_NULL_HANDLE as *mut T
}
2017-09-06 21:34:41 -04:00
}
impl<T> Clone for Handle<T> {
fn clone(&self) -> Self {
2017-11-13 22:55:43 -05:00
Handle(self.0)
2017-09-06 21:34:41 -04:00
}
}
impl<T> Copy for Handle<T> {}
impl<T> ops::Deref for Handle<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.0 }
2017-09-06 21:34:41 -04:00
}
}
impl<T> ops::DerefMut for Handle<T> {
fn deref_mut(&mut self) -> &mut T {
2017-11-13 22:55:43 -05:00
unsafe { &mut *self.0 }
2017-09-06 21:34:41 -04:00
}
}
2018-02-16 10:31:10 -05:00
impl<T> borrow::Borrow<T> for Handle<T> {
fn borrow(&self) -> &T {
unsafe { &*self.0 }
}
}
2017-09-06 21:34:41 -04:00
impl<T> fmt::Debug for Handle<T> {
2017-11-13 22:55:43 -05:00
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "Handle({:p})", self.0)
2017-09-06 21:34:41 -04:00
}
}
#[repr(C)]
pub struct DispatchHandle<T>(u32, Handle<T>);
impl<T> DispatchHandle<T> {
pub fn new(value: T) -> Self {
DispatchHandle(ICD_LOADER_MAGIC, Handle::new(value))
}
pub fn unwrap(self) -> Box<T> {
self.1.unwrap()
}
pub fn is_null(&self) -> bool {
self.1.is_null()
}
}
impl<T> Clone for DispatchHandle<T> {
fn clone(&self) -> Self {
DispatchHandle(self.0, self.1)
}
}
impl<T> Copy for DispatchHandle<T> {}
impl<T> ops::Deref for DispatchHandle<T> {
type Target = T;
fn deref(&self) -> &T {
self.1.deref()
}
}
impl<T> ops::DerefMut for DispatchHandle<T> {
fn deref_mut(&mut self) -> &mut T {
self.1.deref_mut()
}
}
impl<T> borrow::Borrow<T> for DispatchHandle<T> {
fn borrow(&self) -> &T {
self.1.borrow()
}
}
impl<T> fmt::Debug for DispatchHandle<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "DispatchHandle({:p})", (self.1).0)
}
}