Created
February 4, 2015 04:06
-
-
Save aidancully/f1deac354b320ac300c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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