Skip to main content

switch_bank

Function switch_bank 

Source
pub unsafe fn switch_bank(bank: BankNumber)
Available on crate feature bank only.
Expand description

Switch the active ROM bank.

Writes the cartridge’s bank register (see BankNumber for which, and how many) and the software bank shadow that interrupt handlers rely on to save and restore the mapped bank.

Prefer the safe scope / Far API; this is the raw primitive for hand rolled control. After calling it, use Bank::assume to mint a matching token.

A cartridge with no switchable window has nothing to write, so this compiles to nothing.

§Safety

bank must be a valid bank for the cartridge’s MBC, and the caller is responsible for restoring the previous bank and for any pointers that become invalid across the switch.

MBC1, MBC2, and MBC3 read a written 0 as 1, so switch_bank(BankNumber::new(0)) maps bank 1 there while the shadow records 0, and an interrupt would restore the wrong bank. Only MBC5 maps bank 0 into the window.

Under gb_wide_bank="mbc5" the shadow spans two cells, so an interrupt landing between the two writes would afterwards read a bank that was never mapped. An interrupt handler must not call this in that mode, which also rules out far! and DynFar there, since those restore through current_bank.