1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::collections::HashMap;

use super::Memory;
use crate::addr::Addr;

#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Byte(u8);

/// [`NaiveMemory`](crate::memory::NaiveMemory) is an incredibly simple, but inefficient
/// implementation that uses a hashmap to assign each memory addresses to its current value.
/// It is here only as an illustration of the [`Memory`](crate::Memory) interface.
#[derive(Debug)]
pub struct NaiveMemory {
    bytes: HashMap<Addr, Byte>,
}

impl NaiveMemory {
    pub fn new() -> Self {
        NaiveMemory { bytes: HashMap::new() }
    }
}

impl Memory for NaiveMemory {
    fn load_byte(&self, addr: Addr) -> u8 {
        let Byte(val) = *self.bytes.get(&addr).unwrap_or(&Byte(0));
        val
    }

    fn store_byte(&mut self, addr: Addr, value: u8) {
        if value != 0 {
            self.bytes.insert(addr, Byte(value));
        } else {
            self.bytes.remove(&addr);
        }
    }
}