Skip to content

Instantly share code, notes, and snippets.

@aidancully
Created February 4, 2015 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidancully/f1deac354b320ac300c9 to your computer and use it in GitHub Desktop.
Save aidancully/f1deac354b320ac300c9 to your computer and use it in GitHub Desktop.
use std::cell::UnsafeCell;
struct Pool(usize);
impl Pool {
fn new(&mut self) -> Box<Data> {
// record which pool `data` came from.
Box::new(Data(self.0))
}
fn free(&mut self, data: Box<Data>) {
// enfore that `data` wwas allocated from this pool
assert_eq!((*data).0, self.0);
}
}
struct Data(usize);
struct DataBox {
data: Box<Data>,
pool: *mut Pool,
}
impl DataBox {
fn new(pool: &UnsafeCell<Pool>) -> DataBox {
let pool: *mut _ = pool.get();
DataBox {
data: unsafe { &mut *pool }.new(),
pool: pool,
}
}
}
/*
impl Drop for DataBox {
fn drop(&mut self) {
unsafe { &mut *self.pool }.free(self.data);
}
}
*/
fn drop_databox(db: DataBox) {
unsafe { &mut *db.pool }.free(db.data);
}
fn main() {
let pool0 = UnsafeCell::new(Pool(0));
let b0 = DataBox::new(&pool0);
drop_databox(b0);
let pool1 = UnsafeCell::new(Pool(1));
let b1 = DataBox::new(&pool1);
drop_databox(b1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment