// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! Branching on one bit of a byte in the zero page: sixteen instructions, one //! for each bit either way round. //! //! Three bytes: which byte, and how far to go. Testing a bit and branching on //! it otherwise takes a load, a test and a branch, and disturbs a register to //! do it. Rockwell's part added these and Western Design's kept them. /// One of them: which bit, and whether it branches when the bit is set. pub fn at(comptime which: u3, comptime when_set: bool) type { return struct { pub fn data(comptime CPU: type) type { return struct { pub const mnemonic = (if (when_set) "BBS" else "BBR") ++ .{'0' + @as(u8, which)}; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = (if (when_set) 0x8f else 0x0f) | @as(u8, which) << 4, .addressing_mode = .@"Zero Page, Relative", .cycles = 5, }, }; pub fn func(comptime addressing_mode: CPU.AddressingModes) *const fn (*CPU) error{}!void { if (addressing_mode != .@"Zero Page, Relative") @compileError("illegal addressing mode"); const f = struct { pub fn branch(cpu: *CPU) error{}!void { // The byte comes first and is read twice, the way // this chip reads anything it might have written, // and only then is the distance fetched. const address: u16 = cpu.program_counter.read(u8); const value = cpu.memory.read(u8, address); _ = cpu.memory.read(u8, address); const offset: i8 = @bitCast(cpu.program_counter.read(u8)); const target = cpu.program_counter.calculateBranchLocation(offset); const bit = value & (@as(u8, 1) << which) != 0; if (bit != when_set) return; // Taken costs a cycle, and landing in another page // costs a second. Both of them are spent with the // counter on the bus, which is not what an // ordinary branch does: that one drives the // address it built before fixing up the high byte. cpu.program_counter.phantomRead(); if (cpu.program_counter.value & 0xff00 != target & 0xff00) { cpu.program_counter.phantomRead(); } cpu.program_counter.value = target; } }; return f.branch; } }; } }; }