use std::fmt;
use std::hash;
use std::marker::{PhantomData, PhantomFn};
use std::mem;
use std::ops::{Deref, DerefMut};
use Message;
use runtime::Object;
#[link(name = "objc", kind = "dylib")]
extern {
fn objc_retain(obj: *mut Object) -> *mut Object;
fn objc_release(obj: *mut Object);
}
unsafe fn retain<T: Message>(ptr: *mut T) -> *mut T {
objc_retain(ptr as *mut Object) as *mut T
}
unsafe fn release<T: Message>(ptr: *mut T) {
objc_release(ptr as *mut Object);
}
pub enum Owned { }
pub enum Shared { }
pub trait Ownership : 'static + PhantomFn<Self> { }
impl Ownership for Owned { }
impl Ownership for Shared { }
pub struct Id<T, O = Owned> {
ptr: *mut T,
own: PhantomData<O>,
}
impl<T, O> Id<T, O> where T: Message, O: Ownership {
unsafe fn from_ptr_unchecked(ptr: *mut T) -> Id<T, O> {
Id { ptr: ptr, own: PhantomData }
}
pub unsafe fn from_ptr(ptr: *mut T) -> Id<T, O> {
assert!(!ptr.is_null(), "Attempted to construct an Id from a null pointer");
let ptr = retain(ptr);
Id::from_ptr_unchecked(ptr)
}
pub unsafe fn from_retained_ptr(ptr: *mut T) -> Id<T, O> {
assert!(!ptr.is_null(), "Attempted to construct an Id from a null pointer");
Id::from_ptr_unchecked(ptr)
}
}
impl<T> Id<T, Owned> where T: Message {
pub fn share(self) -> ShareId<T> {
unsafe {
let ptr = self.ptr;
mem::forget(self);
Id::from_ptr_unchecked(ptr)
}
}
}
impl<T> Clone for Id<T, Shared> where T: Message {
fn clone(&self) -> ShareId<T> {
unsafe {
let ptr = retain(self.ptr);
Id::from_ptr_unchecked(ptr)
}
}
}
#[unsafe_destructor]
impl<T, O> Drop for Id<T, O> where T: Message {
fn drop(&mut self) {
unsafe {
release(self.ptr);
}
}
}
unsafe impl<T, O> Sync for Id<T, O> where T: Sync { }
unsafe impl<T> Send for Id<T, Owned> where T: Send { }
unsafe impl<T> Send for Id<T, Shared> where T: Sync { }
impl<T, O> Deref for Id<T, O> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<T> DerefMut for Id<T, Owned> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.ptr }
}
}
impl<T, O> PartialEq for Id<T, O> where T: PartialEq {
fn eq(&self, other: &Id<T, O>) -> bool {
self.deref() == other.deref()
}
fn ne(&self, other: &Id<T, O>) -> bool {
self.deref() != other.deref()
}
}
impl<T, O> Eq for Id<T, O> where T: Eq { }
impl<T, O> hash::Hash for Id<T, O> where T: hash::Hash {
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
self.deref().hash(state)
}
}
impl<T, O> fmt::Debug for Id<T, O> where T: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.deref().fmt(f)
}
}
pub type ShareId<T> = Id<T, Shared>;
#[cfg(test)]
mod tests {
use runtime::Object;
use test_utils;
fn retain_count(obj: &Object) -> usize {
unsafe { msg_send![obj, retainCount] }
}
#[test]
fn test_clone() {
let obj = test_utils::sample_object();
assert!(retain_count(&obj) == 1);
let obj = obj.share();
assert!(retain_count(&obj) == 1);
let cloned = obj.clone();
assert!(retain_count(&cloned) == 2);
assert!(retain_count(&obj) == 2);
drop(obj);
assert!(retain_count(&cloned) == 1);
}
}