Created
October 1, 2018 18:26
-
-
Save nikomatsakis/c9ee94232f44d88a69a10f1c4c3646a4 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::RefCell; | |
use std::collections::HashMap; | |
use std::rc::Rc; | |
use typed_arena::Arena; | |
struct Memory { | |
root_alloc: Allocation, | |
table: RefCell<HashMap<u32, Rc<Allocation>>>, | |
} | |
impl Memory { | |
fn op(&self) -> MemoryOp<'_> { | |
MemoryOp { | |
memory: self, | |
arena: Arena::new(), | |
} | |
} | |
} | |
struct Allocation; | |
struct MemoryOp<'me> { | |
memory: &'me Memory, | |
arena: Arena<Rc<Allocation>>, | |
} | |
impl<'me> MemoryOp<'me> { | |
fn get(&self, address: u32) -> &Allocation { | |
if address == 0 { | |
&self.memory.root_alloc | |
} else { | |
let handle: Rc<Allocation> = self | |
.memory | |
.table | |
.borrow_mut() | |
.entry(address) | |
.or_insert_with(|| Rc::new(Allocation)) | |
.clone(); | |
let reference: &Rc<Allocation> = self.arena.alloc(handle); | |
reference | |
} | |
} | |
} | |
fn foo(x: &Memory) { | |
let op = x.op(); | |
let addr = op.get(2); | |
let addr = op.get(3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment