use std::{ fmt, mem, ptr };
use std::borrow::{ Borrow, BorrowMut };
use libc::{ c_void, malloc, free };
use memsec::{ memeq, mlock, munlock };
pub struct Key<T: Sized>(*mut T);
impl<T> From<T> for Key<T> {
#[inline]
fn from(t: T) -> Key<T> {
let memptr = unsafe { malloc(mem::size_of::<T>()) as *mut T };
unsafe { ptr::write(memptr, t) };
unsafe { mlock(memptr, mem::size_of::<T>()) };
Key(memptr)
}
}
impl<T> Borrow<T> for Key<T> {
fn borrow(&self) -> &T {
unsafe { &*self.0 }
}
}
impl<T> BorrowMut<T> for Key<T> {
fn borrow_mut(&mut self) -> &mut T {
unsafe { &mut *self.0 }
}
}
impl<T> Default for Key<T> where T: Default {
#[inline]
fn default() -> Key<T> {
Key::from(T::default())
}
}
impl<T> Clone for Key<T> where T: Clone {
fn clone(&self) -> Key<T> {
let t: &T = self.borrow();
Key::from(t.clone())
}
}
impl<T> fmt::Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "** tmp key **")
}
}
impl<T: Sized> PartialEq<T> for Key<T> {
fn eq(&self, rhs: &T) -> bool {
unsafe { memeq(self.0, rhs, mem::size_of::<T>()) }
}
}
impl<T: Sized> PartialEq<Key<T>> for Key<T> {
fn eq(&self, rhs: &Key<T>) -> bool {
let t: &T = rhs.borrow();
self.eq(t)
}
}
impl<T: Sized> Eq for Key<T> {}
impl<T> Drop for Key<T> where T: Sized {
fn drop(&mut self) {
unsafe {
ptr::drop_in_place(self.0);
munlock(self.0, mem::size_of::<T>());
free(self.0 as *mut c_void);
}
}
}