Files
byte-pusher-emu/src/emu/mem.rs

41 lines
1.2 KiB
Rust
Raw Normal View History

2024-02-17 09:54:41 +05:30
use std::ops::Index;
2024-02-16 23:13:59 +05:30
use crate::emu::mmu::Memory;
2024-02-17 09:54:41 +05:30
use crate::misc::emulator_error::DeviceType::RAM;
use crate::misc::emulator_error::EmulatorError;
use crate::misc::result::EmulatorResult;
2024-02-16 23:13:59 +05:30
const MEM_LENGTH: usize = 2 << 24;
#[derive(Clone, Debug)]
pub struct RamMemory {
data: Box<[u8; MEM_LENGTH]>,
}
impl RamMemory {
2024-02-17 09:54:41 +05:30
pub fn try_new() -> EmulatorResult<RamMemory> {
let alloc_result = vec![0; MEM_LENGTH].into_boxed_slice();
let data = alloc_result.try_into().map_err(|err|{
2024-02-17 11:22:26 +05:30
EmulatorError::AllocationFailure(RAM, "Allocation failed")
2024-02-17 09:54:41 +05:30
})?;
Ok(RamMemory {
data
})
2024-02-16 23:13:59 +05:30
}
}
2024-02-17 09:54:41 +05:30
2024-02-16 23:13:59 +05:30
impl Memory for RamMemory {
2024-02-17 09:54:41 +05:30
fn try_get_byte(&self, address: u32) -> EmulatorResult<u8> {
2024-02-16 23:13:59 +05:30
log::trace!("Fetch RAM memory at address {}",address);
2024-02-17 11:22:26 +05:30
let x = *self.data.get(address as usize).ok_or(EmulatorError::UnreachableMemory(RAM, address))?;
2024-02-17 09:54:41 +05:30
Ok(x)
2024-02-16 23:13:59 +05:30
}
2024-02-17 09:54:41 +05:30
fn try_set_byte(&mut self, address: u32, value: u8) -> EmulatorResult<()> {
if address>= MEM_LENGTH as u32 {
2024-02-17 11:22:26 +05:30
return Err(EmulatorError::UnreachableMemory(RAM, address))
2024-02-17 09:54:41 +05:30
}
self.data[address as usize] = value;
Ok(())
2024-02-16 23:13:59 +05:30
}
}