banked: Break address translation into its own function

This commit is contained in:
John 2024-07-09 01:41:32 -05:00
parent 95b3f3007e
commit 73e52f6aea

View File

@ -91,6 +91,12 @@ impl<const BASE: usize, const LEN: usize, const BANKS: usize> UpperBanked<BASE,
pub fn selected(&self) -> usize { pub fn selected(&self) -> usize {
self.selected self.selected
} }
/// Translates an address into a (bank, address) pair
pub fn translate(&self, addr: usize) -> Option<(usize, usize)> {
let addr = addr.checked_sub(BASE).filter(|v| *v < LEN * 2)?;
Some((addr / LEN, addr % LEN))
}
} }
impl<const BASE: usize, const LEN: usize, const BANKS: usize> Default impl<const BASE: usize, const LEN: usize, const BANKS: usize> Default
@ -107,8 +113,7 @@ impl<const BASE: usize, const LEN: usize, const BANKS: usize> BusIO
{ {
fn read(&self, addr: usize) -> Option<u8> { fn read(&self, addr: usize) -> Option<u8> {
// Pray this gets optimized // Pray this gets optimized
let addr = addr.checked_sub(BASE).filter(|v| *v < LEN * 2)?; let (bank, addr) = self.translate(addr)?;
let (bank, addr) = (addr / LEN, addr % LEN);
match bank { match bank {
0 => self.mem[0].read(addr), 0 => self.mem[0].read(addr),
_ => self.mem[self.selected].read(addr), _ => self.mem[self.selected].read(addr),
@ -117,8 +122,7 @@ impl<const BASE: usize, const LEN: usize, const BANKS: usize> BusIO
fn write(&mut self, addr: usize, data: u8) -> Option<()> { fn write(&mut self, addr: usize, data: u8) -> Option<()> {
// Pray this gets optimized // Pray this gets optimized
let addr = addr.checked_sub(BASE).filter(|v| *v < LEN * 2)?; let (bank, addr) = self.translate(addr)?;
let (bank, addr) = (addr / LEN, addr % LEN);
match bank { match bank {
0 => self.mem[0].write(addr, data), 0 => self.mem[0].write(addr, data),
_ => self.mem[self.selected].write(addr, data), _ => self.mem[self.selected].write(addr, data),