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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use interface::*;
use errors::*;
pub struct MemVector {
size: Addr,
mem: Vec<Byte>,
}
impl MemoryCreator<MemVector> for MemVector {
fn new(size: Addr) -> MemVector {
let mut vec: Vec<Byte> = Vec::new();
vec.resize(size + 1, 0);
MemVector {
size: size,
mem: vec,
}
}
}
impl MemoryBlock for MemVector {
fn get_size(&self) -> Addr {
self.size
}
fn get(&self, addr: Addr) -> Result<Byte, Error> {
match self.mem.get(addr) {
Some(b) => Ok(*b),
None => bail!(ErrorKind::NoData(addr)),
}
}
fn set(&mut self, addr: Addr, byte: Byte) -> Result<(), Error> {
if addr > self.size {
bail!(ErrorKind::TooBig(addr, self.size));
}
self.mem[addr] = byte;
Ok(())
}
}
impl MemoryBlock32be for MemVector {}
impl MemoryBlock32le for MemVector {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memvec_works_basic() {
let mut mem = Box::new(MemVector::new(0xFF));
mem.set(0x00, 101).unwrap();
mem.flush().unwrap();
assert_eq!(101, mem.get(0x00).unwrap());
}
#[test]
fn memvec_works_all() {
let mut mem = Box::new(MemVector::new(0xFF));
let sz = mem.get_size();
assert_eq!(0xFF, sz);
for i in 0..sz + 1 {
mem.set(i, (i & 0xFF) as u8).unwrap()
}
mem.flush().unwrap();
for i in 0..sz + 1 {
assert_eq!((i & 0xFF) as u8, mem.get(i).unwrap());
}
mem.delete(0, sz).unwrap();
mem.flush().unwrap();
for i in 0..sz + 1 {
assert_eq!(0, mem.get(i).unwrap());
}
}
#[test]
fn memvec_works_32bit() {
let mut mem = Box::new(MemVector::new(0xFF));
let sz = mem.get_size();
assert_eq!(0xFF, sz);
mem.set32be(0, 0x12345678).unwrap();
mem.set32le(4, 0x12345678).unwrap();
mem.flush().unwrap();
assert_eq!(0x12345678, mem.get32be(0).unwrap());
assert_eq!(0x12345678, mem.get32le(4).unwrap());
}
}