I want to build an emulator in rust and currently try to find a good design pattern for the following problem: My emulator right now aims to consists of two structs: The CPU
and the RAM
. Since multiple other components will follow, I dont want the CPU
to reference the RAM
directly. Instead, there is a Bus
struct that will tie everything together:
struct CPU;
impl CPU {
pub fn clock() {
// read data from RAM, do stuff..
unimplemented!();
}
}
struct RAM;
impl RAM {
pub fn read_byte(addr: u16) -> u8 { unimplemented!() }
}
struct Bus {
pub cpu: CPU,
pub ram: RAM,
}
impl Bus {
fn clock() {
self.cpu.clock();
}
}
Now for the CPU
to read some memory from the RAM
, it needs to get a reference to the Bus
. However, this would lead to a circular reference because the Bus
already holds the CPU
. Now imagine another component added: the GPU
, which also wants to access features of the Bus
. Now both (CPU
and GPU
) will require a mutable reference to the Bus
which is also not possible because we can only have one.
I can't think of a good design pattern to resolve this in rust. In C++ I would instantiate the CPU
, store it in the Bus
, and then set a pointer to the Bus
in the CPU
. But in Rust, this does not work. What's a good design pattern to implement this in Rust?
Aucun commentaire:
Enregistrer un commentaire