Skip to content

Instantly share code, notes, and snippets.

@nikomatsakis
Created October 1, 2018 18:26
Show Gist options
  • Save nikomatsakis/c9ee94232f44d88a69a10f1c4c3646a4 to your computer and use it in GitHub Desktop.
Save nikomatsakis/c9ee94232f44d88a69a10f1c4c3646a4 to your computer and use it in GitHub Desktop.
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