Skip to main content

cambridge_asm/exec/
memory.rs

1// Copyright (c) 2021 Saadi Save
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
6use super::{RtError, RtResult};
7use std::{
8    collections::btree_map::{BTreeMap, Iter},
9    fmt::Debug,
10};
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15/// Struct providing random-access memory (RAM)
16#[derive(Debug, Default, Clone)]
17#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
18#[repr(transparent)]
19pub struct Memory(BTreeMap<usize, usize>);
20
21impl Memory {
22    pub fn new(mem: BTreeMap<usize, usize>) -> Self {
23        Self(mem)
24    }
25
26    pub fn iter(&'_ self) -> Iter<'_, usize, usize> {
27        self.0.iter()
28    }
29
30    pub fn get(&self, addr: &usize) -> RtResult<&usize> {
31        self.0.get(addr).ok_or(RtError::InvalidAddr(*addr))
32    }
33
34    pub fn get_mut(&mut self, addr: &usize) -> RtResult<&mut usize> {
35        self.0.get_mut(addr).ok_or(RtError::InvalidAddr(*addr))
36    }
37
38    pub fn inner(&self) -> &BTreeMap<usize, usize> {
39        &self.0
40    }
41}
42
43impl<'a> IntoIterator for &'a Memory {
44    type IntoIter = std::collections::btree_map::Iter<'a, usize, usize>;
45    type Item = (&'a usize, &'a usize);
46    fn into_iter(self) -> Self::IntoIter {
47        self.iter()
48    }
49}
50
51impl<T> From<T> for Memory
52where
53    T: Into<BTreeMap<usize, usize>>,
54{
55    fn from(x: T) -> Self {
56        Self(x.into())
57    }
58}