Created
January 14, 2017 17:07
-
-
Save anonymous/955a7bf4483d983bac1b705d6142a0f2 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or 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
struct CpuHook { | |
counter: u64 | |
} | |
impl CpuHook { | |
pub fn inspect(&mut self, cpu: &Cpu) { | |
// here I don't use the cpu but I could log the cpu register in a mutable file for instance | |
self.counter = self.counter.wrapping_add(1); | |
} | |
} | |
struct Cpu { | |
register: u8, | |
memory: Memory, | |
memory_hooks: Vec<MemoryHook> | |
// lot of other fields here | |
} | |
impl Cpu { | |
fn run_1_instruction(&mut self) { | |
// running an instruction modifies the Cpu and the memory | |
let r = self.register; | |
for memory_hook in self.memory_hooks.iter_mut() { | |
memory_hook.on_read(0, &self.memory) | |
} | |
let m = self.memory.read_at(0); | |
self.memory.write_at(0, r); | |
self.register = m | |
} | |
} | |
struct MemoryHook { | |
last_read: u8 | |
} | |
impl MemoryHook { | |
pub fn on_read(&mut self, address: u16, memory: &Memory) { | |
self.last_read = memory.read_at(address); | |
} | |
} | |
struct Memory { | |
byte0: u8 | |
} | |
impl Memory { | |
fn read_at(&self, address: u16) -> u8 { | |
self.byte0 | |
} | |
fn write_at(&mut self, address: u16, word: u8) { | |
self.byte0 = word | |
} | |
} | |
struct Computer { | |
cpu: Cpu, | |
cpu_hooks: Vec<CpuHook>, | |
} | |
impl Computer { | |
pub fn one_tick(&mut self) { | |
for hook in self.cpu_hooks.iter_mut() { | |
hook.inspect(&self.cpu); | |
} | |
self.cpu.run_1_instruction() | |
} | |
} | |
fn main() { | |
let mut computer = Computer { | |
cpu_hooks: vec!(CpuHook{counter:0}), | |
cpu: Cpu{ | |
register: 3, | |
memory: Memory{byte0: 100}, | |
memory_hooks: vec!(MemoryHook {last_read: 50}) | |
}, | |
}; | |
computer.one_tick(); | |
assert_eq!(computer.cpu.register, 100); | |
assert_eq!(computer.cpu_hooks[0].counter, 1); | |
assert_eq!(computer.cpu.memory.byte0, 3); | |
assert_eq!(computer.cpu.memory_hooks[0].last_read, 100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment