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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]

extern crate alloc;

use alloc::vec::Vec;
use core::marker::PhantomData;

use emulator_hal::{BasicBusError, BusAccess, Instant as EmuInstant};

/// A contiguous block of memory, backed by a `Vec`
pub struct MemoryBlock<Instant> {
    read_only: bool,
    contents: Vec<u8>,
    instant: PhantomData<Instant>,
}

impl<Instant> MemoryBlock<Instant> {
    /// Construct a memory block from a given `Vec`
    pub fn from(contents: Vec<u8>) -> Self {
        MemoryBlock {
            read_only: false,
            contents,
            instant: PhantomData,
        }
    }

    /// Make this memory block read only
    pub fn read_only(&mut self) {
        self.read_only = true;
    }

    /// Resize the underlying `Vec` to be the given `newsize`
    pub fn resize(&mut self, new_size: usize) {
        self.contents.resize(new_size, 0);
    }
}

#[cfg(feature = "std")]
use std::io;

#[cfg(feature = "std")]
impl<Instant> MemoryBlock<Instant> {
    /// Load the binary contents of a file into a new `MemoryBlock`
    ///
    /// The resulting `MemoryBlock` will be sized to exactly the length of the file
    pub fn load(filename: &str) -> Result<Self, io::Error> {
        let contents = std::fs::read(filename)?;
        Ok(MemoryBlock::from(contents))
    }

    /// Load the binary contents of a file into an existing `MemoryBlock` at the given address
    ///
    /// The `MemoryBlock` must already be big enough to contain the contents of the file
    pub fn load_at(&mut self, addr: usize, filename: &str) -> Result<(), io::Error> {
        let contents = std::fs::read(filename)?;
        self.contents[addr..addr + contents.len()].copy_from_slice(&contents);
        Ok(())
    }
}

impl<Address, Instant> BusAccess<Address> for MemoryBlock<Instant>
where
    Address: TryInto<usize> + Copy,
    Instant: EmuInstant,
{
    type Instant = Instant;
    type Error = BasicBusError;

    fn read(
        &mut self,
        _now: Instant,
        addr: Address,
        data: &mut [u8],
    ) -> Result<usize, Self::Error> {
        let addr = addr
            .try_into()
            .map_err(|_| BasicBusError::UnmappedAddress)?;

        if addr + data.len() > self.contents.len() {
            return Err(BasicBusError::UnmappedAddress);
        }

        data.copy_from_slice(&self.contents[addr..addr + data.len()]);
        Ok(data.len())
    }

    fn write(&mut self, _now: Instant, addr: Address, data: &[u8]) -> Result<usize, Self::Error> {
        if self.read_only {
            return Ok(0);
        }

        let addr = addr
            .try_into()
            .map_err(|_| BasicBusError::UnmappedAddress)?;

        if addr + data.len() > self.contents.len() {
            return Err(BasicBusError::UnmappedAddress);
        }

        self.contents[addr..addr + data.len()].copy_from_slice(data);
        Ok(data.len())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use emulator_hal::Instant;
    use std::time::Duration;

    #[test]
    fn test_memory_block() {
        #[derive(Clone, Debug, PartialEq, Eq)]
        struct SimpleError();

        impl From<core::num::TryFromIntError> for SimpleError {
            fn from(_: core::num::TryFromIntError) -> Self {
                SimpleError()
            }
        }

        let mut memory = MemoryBlock::<Duration>::from(vec![0; 1024]);

        let number = 0x1234_5678;
        memory.write_leu32(Duration::START, 0, number).unwrap();
        let result = memory.read_leu32(Duration::START, 0).unwrap();
        assert_eq!(result, number);
    }
}