#![feature(std_misc, optin_builtin_traits)]
#![allow(unused_unsafe)]
use std::cell::{self, Cell, RefCell, BorrowState};
use std::ops::{Deref, DerefMut};
use std::marker;
use gc::GcBox;
mod gc;
pub mod trace;
#[cfg(test)]
mod test;
pub use trace::Trace;
pub use gc::{force_collect, GcBoxTrait};
pub struct Gc<T: Trace + 'static> {
root: Cell<bool>,
_ptr: *mut GcBox<T>,
}
impl<T> !marker::Send for Gc<T> {}
impl<T> !marker::Sync for Gc<T> {}
impl<T: Trace> Gc<T> {
pub fn new(value: T) -> Gc<T> {
unsafe {
let ptr = GcBox::new(value);
(*ptr).value().unroot();
Gc { _ptr: ptr, root: Cell::new(true) }
}
}
fn inner(&self) -> &GcBox<T> {
unsafe { &*self._ptr }
}
}
impl<T: Trace> Trace for Gc<T> {
fn trace(&self) {
self.inner().trace_inner();
}
fn root(&self) {
assert!(!self.root.get(), "Can't double-root a Gc<T>");
self.root.set(true);
unsafe {
<<<<<<< HEAD
=======
>>>>>>> 8b7dca28695b5cca214d043f0b50f69a8d96c688
self.inner().root_inner();
}
}
fn unroot(&self) {
assert!(self.root.get(), "Can't double-unroot a Gc<T>");
self.root.set(false);
unsafe {
<<<<<<< HEAD
=======
>>>>>>> 8b7dca28695b5cca214d043f0b50f69a8d96c688
self.inner().unroot_inner();
}
}
}
impl<T: Trace> Clone for Gc<T> {
fn clone(&self) -> Gc<T> {
self.root();
Gc { _ptr: self._ptr, root: Cell::new(true) }
}
}
impl<T: Trace> Deref for Gc<T> {
type Target = T;
fn deref(&self) -> &T {
&self.inner().value()
}
}
impl<T: Trace> Drop for Gc<T> {
fn drop(&mut self) {
if self.root.get() {
self.unroot();
}
}
}
pub struct GcCell<T: 'static> {
cell: RefCell<T>,
}
impl<T> !marker::Send for GcCell<T> {}
impl<T> !marker::Sync for GcCell<T> {}
impl <T: Trace> GcCell<T> {
pub fn new(value: T) -> GcCell<T> {
GcCell{
cell: RefCell::new(value)
}
}
pub fn borrow(&self) -> GcCellRef<T> {
self.cell.borrow()
}
pub fn borrow_mut(&self) -> GcCellRefMut<T> {
let val_ref = self.cell.borrow_mut();
val_ref.root();
GcCellRefMut {
_ref: val_ref,
}
}
}
impl<T: Trace> Trace for GcCell<T> {
fn trace(&self) {
match self.cell.borrow_state() {
BorrowState::Writing => (),
_ => self.cell.borrow().trace(),
}
}
fn root(&self) {
self.cell.borrow().root();
}
fn unroot(&self) {
self.cell.borrow().unroot();
}
}
pub type GcCellRef<'a, T> = cell::Ref<'a, T>;
pub struct GcCellRefMut<'a, T: Trace + 'static> {
_ref: ::std::cell::RefMut<'a, T>,
}
impl<'a, T: Trace> Deref for GcCellRefMut<'a, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T { &*self._ref }
}
impl<'a, T: Trace> DerefMut for GcCellRefMut<'a, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T { &mut *self._ref }
}
impl<'a, T: Trace> Drop for GcCellRefMut<'a, T> {
fn drop(&mut self) {
self._ref.unroot();
}
}