Write a CHIP-8 Emulator in Rust From Scratch
Write a CHIP-8 emulator in Rust 1.85: a safe Chip8 struct, enum-based opcode decoding with pattern matching, wrapping arithmetic and a testable display buffer.

The C version of a CHIP-8 emulator leans on the programmer to keep integer widths and array bounds right. Rust moves most of that work to the compiler. An 8-bit register is a u8, arithmetic that might overflow is a visible choice between wrapping_add and checked_add, array indexing is bounds-checked, and the instruction decoder can be a pattern match the compiler checks for completeness. This post writes the same machine as the C post, 4 KiB of memory, sixteen registers, a stack, two timers and a 64 by 32 display, in safe Rust 1.85 with only the standard library, and keeps the design testable by separating the machine from any window. It differs from the C version in how it models instructions: it decodes each opcode into an enum first, then executes the enum, which is the idiomatic way to write an interpreter in Rust. The instruction semantics follow the same references as the C post, so read that for the machine's overview and for the notes about quirks.
The state
The machine is a struct with fixed-size arrays. Rust requires the arrays to be initialized, and [0; N] does that.
pub const SCREEN_W: usize = 64;
pub const SCREEN_H: usize = 32;
const FONT_START: usize = 0x050;
const PROGRAM_START: usize = 0x200;
const FONT: [u8; 80] = [
0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70,
0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0,
0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0,
0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40,
0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0,
0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0,
0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0,
0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80,
];
pub struct Chip8 {
pub memory: [u8; 4096],
pub v: [u8; 16],
pub i: u16,
pub pc: u16,
stack: Vec<u16>,
pub delay_timer: u8,
pub sound_timer: u8,
pub screen: [bool; SCREEN_W * SCREEN_H],
pub keys: [bool; 16],
rng: u32,
}
impl Chip8 {
pub fn new() -> Self {
let mut memory = [0u8; 4096];
memory[FONT_START..FONT_START + FONT.len()].copy_from_slice(&FONT);
Chip8 {
memory,
v: [0; 16],
i: 0,
pc: PROGRAM_START as u16,
stack: Vec::with_capacity(16),
delay_timer: 0,
sound_timer: 0,
screen: [false; SCREEN_W * SCREEN_H],
keys: [false; 16],
rng: 0x1234_abcd,
}
}
pub fn load(&mut self, rom: &[u8]) {
let end = (PROGRAM_START + rom.len()).min(self.memory.len());
self.memory[PROGRAM_START..end].copy_from_slice(&rom[..end - PROGRAM_START]);
}
}The stack is a Vec<u16> with a capacity of 16. Using a vector means that push and pop are explicit and that popping an empty stack returns None, so a ROM with an unbalanced return does not read garbage. A fixed array with a stack pointer would be closer to the hardware, and either choice is defensible.
Decoding into an enum
The distinctive Rust step is a decoder that turns the 16-bit opcode into a value of an enum that names each instruction and carries its operands. The execute step then matches on the enum, and the compiler warns if a variant is not handled.
#[derive(Debug, PartialEq)]
pub enum Op {
Cls,
Ret,
Jp(u16),
Call(u16),
SeByte(usize, u8),
SneByte(usize, u8),
SeReg(usize, usize),
LdByte(usize, u8),
AddByte(usize, u8),
LdReg(usize, usize),
Or(usize, usize),
And(usize, usize),
Xor(usize, usize),
AddReg(usize, usize),
Sub(usize, usize),
Shr(usize, usize),
Subn(usize, usize),
Shl(usize, usize),
SneReg(usize, usize),
LdI(u16),
JpV0(u16),
Rnd(usize, u8),
Drw(usize, usize, u8),
Skp(usize),
Sknp(usize),
LdVxDt(usize),
LdKey(usize),
LdDtVx(usize),
LdStVx(usize),
AddI(usize),
LdFont(usize),
Bcd(usize),
StoreRegs(usize),
LoadRegs(usize),
Unknown(u16),
}
pub fn decode(op: u16) -> Op {
let x = ((op >> 8) & 0xF) as usize;
let y = ((op >> 4) & 0xF) as usize;
let n = (op & 0xF) as u8;
let nn = (op & 0xFF) as u8;
let nnn = op & 0xFFF;
match (op >> 12, n, nn) {
(0x0, _, 0xE0) if op == 0x00E0 => Op::Cls,
(0x0, _, 0xEE) if op == 0x00EE => Op::Ret,
(0x1, _, _) => Op::Jp(nnn),
(0x2, _, _) => Op::Call(nnn),
(0x3, _, _) => Op::SeByte(x, nn),
(0x4, _, _) => Op::SneByte(x, nn),
(0x5, 0x0, _) => Op::SeReg(x, y),
(0x6, _, _) => Op::LdByte(x, nn),
(0x7, _, _) => Op::AddByte(x, nn),
(0x8, 0x0, _) => Op::LdReg(x, y),
(0x8, 0x1, _) => Op::Or(x, y),
(0x8, 0x2, _) => Op::And(x, y),
(0x8, 0x3, _) => Op::Xor(x, y),
(0x8, 0x4, _) => Op::AddReg(x, y),
(0x8, 0x5, _) => Op::Sub(x, y),
(0x8, 0x6, _) => Op::Shr(x, y),
(0x8, 0x7, _) => Op::Subn(x, y),
(0x8, 0xE, _) => Op::Shl(x, y),
(0x9, 0x0, _) => Op::SneReg(x, y),
(0xA, _, _) => Op::LdI(nnn),
(0xB, _, _) => Op::JpV0(nnn),
(0xC, _, _) => Op::Rnd(x, nn),
(0xD, _, _) => Op::Drw(x, y, n),
(0xE, _, 0x9E) => Op::Skp(x),
(0xE, _, 0xA1) => Op::Sknp(x),
(0xF, _, 0x07) => Op::LdVxDt(x),
(0xF, _, 0x0A) => Op::LdKey(x),
(0xF, _, 0x15) => Op::LdDtVx(x),
(0xF, _, 0x18) => Op::LdStVx(x),
(0xF, _, 0x1E) => Op::AddI(x),
(0xF, _, 0x29) => Op::LdFont(x),
(0xF, _, 0x33) => Op::Bcd(x),
(0xF, _, 0x55) => Op::StoreRegs(x),
(0xF, _, 0x65) => Op::LoadRegs(x),
_ => Op::Unknown(op),
}
}Matching on a tuple of the family, the low nibble and the low byte is a compact way to express the opcode table. The decoder is a pure function with no machine state, so it can be unit-tested on its own, and the Unknown variant carries the raw opcode for the error message.
Execution
The execute method matches every variant. It uses wrapping_add and wrapping_sub wherever the original hardware wraps, and overflowing_add where the carry matters, which makes the arithmetic intent explicit.
use crate::chip8::{Chip8, SCREEN_H, SCREEN_W};
use crate::opcode::{decode, Op};
impl Chip8 {
fn next_random(&mut self) -> u8 {
self.rng = self.rng.wrapping_mul(1664525).wrapping_add(1013904223);
(self.rng >> 24) as u8
}
pub fn cycle(&mut self) -> Result<(), String> {
let pc = self.pc as usize;
let opcode = (u16::from(self.memory[pc]) << 8) | u16::from(self.memory[pc + 1]);
self.pc += 2;
match decode(opcode) {
Op::Cls => self.screen.fill(false),
Op::Ret => self.pc = self.stack.pop().ok_or("return with empty stack")?,
Op::Jp(a) => self.pc = a,
Op::Call(a) => {
self.stack.push(self.pc);
self.pc = a;
}
Op::SeByte(x, nn) => if self.v[x] == nn { self.pc += 2 },
Op::SneByte(x, nn) => if self.v[x] != nn { self.pc += 2 },
Op::SeReg(x, y) => if self.v[x] == self.v[y] { self.pc += 2 },
Op::LdByte(x, nn) => self.v[x] = nn,
Op::AddByte(x, nn) => self.v[x] = self.v[x].wrapping_add(nn),
Op::LdReg(x, y) => self.v[x] = self.v[y],
Op::Or(x, y) => { self.v[x] |= self.v[y]; self.v[0xF] = 0; }
Op::And(x, y) => { self.v[x] &= self.v[y]; self.v[0xF] = 0; }
Op::Xor(x, y) => { self.v[x] ^= self.v[y]; self.v[0xF] = 0; }
Op::AddReg(x, y) => {
let (sum, carry) = self.v[x].overflowing_add(self.v[y]);
self.v[x] = sum;
self.v[0xF] = carry as u8;
}
Op::Sub(x, y) => {
let (diff, borrow) = self.v[x].overflowing_sub(self.v[y]);
self.v[x] = diff;
self.v[0xF] = !borrow as u8;
}
Op::Subn(x, y) => {
let (diff, borrow) = self.v[y].overflowing_sub(self.v[x]);
self.v[x] = diff;
self.v[0xF] = !borrow as u8;
}
Op::Shr(x, y) => {
let out = self.v[y] & 1;
self.v[x] = self.v[y] >> 1;
self.v[0xF] = out;
}
Op::Shl(x, y) => {
let out = self.v[y] >> 7;
self.v[x] = self.v[y] << 1;
self.v[0xF] = out;
}
Op::SneReg(x, y) => if self.v[x] != self.v[y] { self.pc += 2 },
Op::LdI(a) => self.i = a,
Op::JpV0(a) => self.pc = a + u16::from(self.v[0]),
Op::Rnd(x, nn) => { let r = self.next_random(); self.v[x] = r & nn; }
Op::Drw(x, y, n) => self.draw(x, y, n),
Op::Skp(x) => if self.keys[(self.v[x] & 0xF) as usize] { self.pc += 2 },
Op::Sknp(x) => if !self.keys[(self.v[x] & 0xF) as usize] { self.pc += 2 },
Op::LdVxDt(x) => self.v[x] = self.delay_timer,
Op::LdKey(x) => match self.keys.iter().position(|&k| k) {
Some(k) => self.v[x] = k as u8,
None => self.pc -= 2,
},
Op::LdDtVx(x) => self.delay_timer = self.v[x],
Op::LdStVx(x) => self.sound_timer = self.v[x],
Op::AddI(x) => self.i = self.i.wrapping_add(u16::from(self.v[x])),
Op::LdFont(x) => self.i = 0x050 + u16::from(self.v[x] & 0xF) * 5,
Op::Bcd(x) => {
let v = self.v[x];
let i = self.i as usize;
self.memory[i] = v / 100;
self.memory[i + 1] = (v / 10) % 10;
self.memory[i + 2] = v % 10;
}
Op::StoreRegs(x) => {
for k in 0..=x { self.memory[self.i as usize + k] = self.v[k]; }
self.i += x as u16 + 1;
}
Op::LoadRegs(x) => {
for k in 0..=x { self.v[k] = self.memory[self.i as usize + k]; }
self.i += x as u16 + 1;
}
Op::Unknown(op) => return Err(format!("unknown opcode {:04X} at {:03X}", op, pc)),
}
Ok(())
}
fn draw(&mut self, x: usize, y: usize, n: u8) {
let px = self.v[x] as usize % SCREEN_W;
let py = self.v[y] as usize % SCREEN_H;
self.v[0xF] = 0;
for row in 0..n as usize {
if py + row >= SCREEN_H { break; }
let bits = self.memory[self.i as usize + row];
for col in 0..8 {
if px + col >= SCREEN_W { break; }
if bits & (0x80 >> col) != 0 {
let idx = (py + row) * SCREEN_W + px + col;
if self.screen[idx] { self.v[0xF] = 1; }
self.screen[idx] ^= true;
}
}
}
}
pub fn tick_timers(&mut self) {
self.delay_timer = self.delay_timer.saturating_sub(1);
self.sound_timer = self.sound_timer.saturating_sub(1);
}
}The method returns Result<(), String>, so an unknown opcode or an empty-stack return becomes an error the caller prints and not a panic or silent misbehaviour. Indexing with self.memory[pc + 1] panics if the program counter runs off the end, which is the right outcome during development: a loud failure at the exact line.
Running and testing
A main that loads a ROM, runs a number of frames and prints the screen is the whole host. Because the machine has no I/O dependencies, unit tests run it directly.
mod chip8;
mod exec;
mod opcode;
use chip8::{Chip8, SCREEN_H, SCREEN_W};
fn main() {
let mut c = Chip8::new();
// V0 = 0; V1 = 0; I = font glyph 0; draw 5 rows; loop forever
let rom = [0x60, 0x00, 0x61, 0x00, 0xA0, 0x50, 0xD0, 0x15, 0x12, 0x08];
c.load(&rom);
for _ in 0..6 {
if let Err(e) = c.cycle() {
eprintln!("{e}");
return;
}
}
for y in 0..5 {
let row: String = (0..8)
.map(|x| if c.screen[y * SCREEN_W + x] { '#' } else { '.' })
.collect();
println!("{row}");
}
println!("VF={} pc=0x{:03X}", c.v[0xF], c.pc);
let _ = SCREEN_H;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_sets_carry() {
let mut c = Chip8::new();
c.load(&[0x60, 0xFF, 0x61, 0x02, 0x80, 0x14]); // V0=FF, V1=2, V0+=V1
for _ in 0..3 { c.cycle().unwrap(); }
assert_eq!(c.v[0], 0x01);
assert_eq!(c.v[0xF], 1);
}
}The program prints the same glyph as the C version, since the semantics are identical:
####....
#..#....
#..#....
#..#....
####....
VF=0 pc=0x208Run it with cargo run, and the test with cargo test. The test loads three instructions, V0 = 0xFF, V1 = 0x02 and V0 += V1, and expects the wrapped result 0x01 with the carry flag set.
Why an enum beats a bare match on the opcode
A beginner may ask why the decoder produces an enum when the executor could match the opcode bits directly, as the C version does. There are three reasons, and they all matter as the project grows.
The first is that decoding and executing are different jobs with different tests. The decoder is a pure function, so a test can assert that 0xA2F0 decodes to Op::LdI(0x2F0) without constructing a machine. When a game misbehaves you can tell whether the fault is in decoding, which is wrong bit extraction, or in execution, which is wrong semantics.
The second is that the enum is a value you can store and print. A trace log is a list of Op values, a debugger can show the next instruction by decoding it without running it, and a cache can keep decoded instructions so a hot loop does not decode the same opcode repeatedly. Adding a Debug or Display implementation turns the enum into a disassembler.
The third is exhaustiveness. If you add a variant for a new SUPER-CHIP instruction and forget to handle it in cycle, the compiler refuses to build, whereas a C switch with no default simply ignores the case. The Unknown variant is the one place where ignorance is deliberate, and it reports the raw opcode.
The cost is a little more code and the overhead of building the enum value on each cycle. For a machine this small the overhead is not measurable against the host's speed, and the clarity is worth far more than any saving.
Running it on a real window
The core in this post has no dependency on any library, which is deliberate. To see games, wrap it in a host loop. Pick a crate that gives you a window and a pixel buffer, copy screen into the buffer scaled by a factor of ten so each CHIP-8 pixel is a ten by ten block, read the keyboard into keys, and call cycle about ten times and tick_timers once per frame. The host should also play a tone while sound_timer is above zero. Because none of that touches the machine, the same core works with a terminal renderer for tests, a window for play and a web page if you compile to WebAssembly.
What Rust changes about the design
Three differences are worth keeping in mind as the emulator grows. First, the enum decoder gives you a free disassembler: implement Display for Op and the same match prints mnemonics. Second, the borrow checker rejects the pattern of passing the whole machine to a function while holding references into it, which pushes you towards small methods on the struct, as above, and towards separating the display buffer if a renderer needs to read it while the CPU runs. Third, usize indexes and u8 or u16 values need explicit conversion, which is verbose and removes the class of bug where an index silently truncates.
The performance is the same as C for this workload. Release builds with cargo run --release remove the bounds checks that the optimizer can prove unnecessary and leave the rest, and for an interpreter that executes under a thousand instructions per second the difference is immaterial.


