#memory #emulator #abstraction #read #write #readable #writable

mem_storage

为可读和可写内存提供抽象。设计用于模拟器。

2 个版本

0.1.1 2020年7月19日
0.1.0 2020年7月17日

#135 in 模拟器

每月 26 次下载
2 crate 中使用

Zlib OR Apache-2.0

13KB
92

mem-storage

Crates.io doc

mem-storage 是对一块可读和可写内存的抽象。它可以用在任何需要某种内存的地方,例如模拟器中的 RAM。此 crate 还可以在 no_std 环境中使用。

动机

每次我编写模拟器时,都不喜欢反复创建一个 struct Memory 并总是复制粘贴像 read_u8read_u16 等方法。因此,我为此问题想出了一个通用的解决方案。

用法

使用 MemoryStorage 特性

use mem_storage::MemoryStorage;

let mem = MyMemory::new();

/// The `read` and `write` method will read / write data using little endian format.
/// For big endian format use `read_be` and `write_be`.
mem.write(0xABCD, 123);

let value = mem.read::<u8>(0xABCD);
assert_eq!(123u8, value);

mem.write(0x1000, 12345u64);

let value = mem.read::<u64>(0x1000);
assert_eq!(12345u64, value);

mem.write_be(0x2000, 1234567u64);

let value = mem.read_be::<u64>(0x2000);
assert_eq!(1234567u64, value);

实现 MemoryStorage 特性

use mem_storage::MemoryStorage;

/// This time your struct is responsible for storing the data.
struct MyMemory {
  ram: Vec<u8>,
}

impl MyMemory {
  fn new() -> Self {
    // Create 1KiB of zero initialized memory
    Self { ram: vec![0u8; 1024 * 1024] }
  }
}

impl MemoryStorage for MyMemory {
  /// If an `Err` is returned, the addr is out of bounds
  type Error = ();

  fn get<I>(&self, index: I) -> Result<&I::Output, Self::Error>
  where
      I: std::slice::SliceIndex<[u8]>,
  {
      self.ram.get(index).ok_or(())
  }

  fn get_mut<I>(&mut self, index: I) -> Result<&mut I::Output, Self::Error>
  where
      I: std::slice::SliceIndex<[u8]>,
  {
      self.ram.get_mut(index).ok_or(())
  }

  fn try_read_byte(&self, addr: usize) -> Result<u8, Self::Error> {
    self.ram.get(addr).copied().ok_or(())
  }

  fn try_write_byte(&mut self, addr: usize, value: u8) -> Result<(), Self::Error> {
    let mut value = self.ram.get_mut(addr).ok_or(())?;
    *value = *value;
    Ok(())
  }

  // The trait will provide a generic `read` and `read_be` method for you.
}

许可证

本项目在 Zlib 或 Apache2.0 许可证下双重授权。

无运行时依赖