use std::mem::forget;
use std::ops::Deref;
use std::ptr::null_mut;
use winapi::Interface;
use winapi::um::unknwnbase::IUnknown;
pub struct ComPtr<T>(*mut T) where T: Interface;
impl<T> ComPtr<T> where T: Interface {
pub unsafe fn from_raw(ptr: *mut T) -> ComPtr<T> {
assert!(!ptr.is_null());
ComPtr(ptr)
}
pub fn up<U>(self) -> ComPtr<U> where T: Deref<Target=U>, U: Interface {
ComPtr(self.into_raw() as *mut U)
}
pub fn into_raw(self) -> *mut T {
let p = self.0;
forget(self);
p
}
fn as_unknown(&self) -> &IUnknown {
unsafe { &*(self.0 as *mut IUnknown) }
}
pub fn cast<U>(&self) -> Result<ComPtr<U>, i32> where U: Interface {
let mut obj = null_mut();
let err = unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) };
if err < 0 { return Err(err); }
Ok(unsafe { ComPtr::from_raw(obj as *mut U) })
}
pub fn as_raw(&self) -> *mut T {
self.0
}
}
impl<T> Deref for ComPtr<T> where T: Interface {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.0 }
}
}
impl<T> Clone for ComPtr<T> where T: Interface {
fn clone(&self) -> Self {
unsafe {
self.as_unknown().AddRef();
ComPtr::from_raw(self.0)
}
}
}
impl<T> Drop for ComPtr<T> where T: Interface {
fn drop(&mut self) {
unsafe { self.as_unknown().Release(); }
}
}
impl<T> PartialEq<ComPtr<T>> for ComPtr<T> where T: Interface {
fn eq(&self, other: &ComPtr<T>) -> bool {
self.0 == other.0
}
}