const ADDR_LO_BARE: u16 = 0x0000;
const ADDR_HI_BARE: u16 = 0xFFFF;
pub const MEMORY_ADDRESS_LO: u16 = ADDR_LO_BARE;
pub const MEMORY_ADDRESS_HI: u16 = ADDR_HI_BARE;
pub const STACK_ADDRESS_LO: u16 = 0x0100;
pub const STACK_ADDRESS_HI: u16 = 0x01FF;
pub const NMI_INTERRUPT_VECTOR_LO: u16 = 0xFFFA;
pub const NMI_INTERRUPT_VECTOR_HI: u16 = 0xFFFB;
pub const RESET_VECTOR_LO: u16 = 0xFFFC;
pub const RESET_VECTOR_HI: u16 = 0xFFFD;
pub const IRQ_INTERRUPT_VECTOR_LO: u16 = 0xFFFE;
pub const IRQ_INTERRUPT_VECTOR_HI: u16 = 0xFFFF;
const MEMORY_SIZE: usize = (ADDR_HI_BARE - ADDR_LO_BARE) as usize + 1usize;
#[derive(Copy, Clone, Debug)]
pub struct Memory {
#[allow(clippy::large_stack_arrays)]
bytes: [u8; MEMORY_SIZE],
}
impl Default for Memory {
fn default() -> Self {
Self::new()
}
}
pub trait Bus {
fn get_byte(&mut self, address: u16) -> u8;
fn set_byte(&mut self, address: u16, value: u8);
fn set_word(&mut self, address: u16, value: u16) {
let bytes = value.to_le_bytes();
self.set_byte(address, bytes[0]);
self.set_byte(address.wrapping_add(1), bytes[1]);
}
#[allow(clippy::cast_possible_truncation)]
fn set_bytes(&mut self, start: u16, values: &[u8]) {
for i in 0..values.len() as u16 {
self.set_byte(start + i, values[i as usize]);
}
}
fn nmi_pending(&mut self) -> bool {
false
}
fn irq_pending(&mut self) -> bool {
false
}
}
impl Memory {
#[must_use]
#[allow(clippy::large_stack_arrays)]
pub const fn new() -> Memory {
Memory {
#[allow(clippy::large_stack_arrays)]
bytes: [0; MEMORY_SIZE],
}
}
}
impl Bus for Memory {
fn get_byte(&mut self, address: u16) -> u8 {
self.bytes[address as usize]
}
fn set_byte(&mut self, address: u16, value: u8) {
self.bytes[address as usize] = value;
}
fn set_bytes(&mut self, start: u16, values: &[u8]) {
let start = start as usize;
let end = start + values.len();
self.bytes[start..end].copy_from_slice(values);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "range end index 65537 out of range for slice of length 65536")]
fn test_memory_overflow_panic() {
let mut memory = Memory::new();
memory.set_bytes(0xFFFE, &[1, 2, 3]);
}
}