oxid8-core 0.2.0

CHIP-8 interpreter core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! # Oxid-8 Core
//!
//! `oxid8_core` is an interpreter core for the Chip-8 programming language,
//! developed by Joseph Weisbecker in the mid-1970s for making games on the
//! COSMAC VIP and Telmac 1800.
//!
//! This is the core interpreter library for `Oxid8`. So that developers can
//! create their own renderers on top of this library crate.
//!
//! # Getting Started
//!
//! ```no_run
//! use oxid8_core::Oxid8;
//! use std::time::{Duration, Instant};
//!
//! #[derive(Default)]
//! struct State {
//!     should_exit: bool,
//!     last_frame: Option<Instant>,
//! }
//!
//! #[derive(Default)]
//! struct Emu {
//!     state: State,
//!     core: Oxid8,
//! }
//!
//! fn main() -> std::io::Result<()> {
//!     let mut emu = Emu::default();
//!     emu.core.load_font();
//!     emu.core.load_rom("rom_path")?;
//!
//!     while !emu.state.should_exit {
//!         let time = Instant::now();
//!
//!         // TODO: Poll and Handle Events.
//!
//!         if let Some(last_frame) = emu.state.last_frame {
//!             if time.duration_since(last_frame) >= Duration::from_millis(16) {
//!                 if let Err(err) = emu.core.next_frame() {
//!                     panic!("{err}");
//!                 }
//!
//!                 // TODO: Draw current frame.
//!
//!                 emu.state.last_frame = Some(time);
//!             }
//!
//!             if emu.core.sound() {
//!                 // TODO: Beep!
//!             }
//!
//!         } else {
//!             emu.state.last_frame = Some(Instant::now());
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! # WASM Compatibility
//!
//! ```toml
//! # Cargo.toml
//!
//! [dependencies]
//! web-time = "1.1.0"
//!
//! [target.'cfg(target_arch = "wasm32")'.dependencies]
//! getrandom = { version = "0.3", features = ["wasm_js"] }
//! ```
//!
//! ```toml
//! # config.toml
//!
//! [target.'cfg(target_arch = "wasm32")']
//! rustflags = ["--cfg", 'getrandom_backend="wasm_js"']
//! ```
//!
//! # Frame Time
//!
//! You should generate frames at 60Hz or roughly 16ms if not relying on
//! vsync. `std::time::{Instant, Duration}` panic in the web so use the
//! [web-time](https://crates.io/crates/web-time) crate when compiling to
//! web assembly.

use rand::{Rng, rng, rngs::ThreadRng};
use std::{fmt, io, time::Duration};

/// Standard CPU tick rate set to 700Hz. This value is not used internally.
/// Run a CPU cycle this often.
pub const CPU_TICK: Duration = Duration::from_micros(1430);

/// Standard TIMER tick rate set to 60Hz. This value is not used internally.
/// Decrement the timers and refresh the display this often.
pub const TIMER_TICK: Duration = Duration::from_micros(16667);

/// Virtual screen width (64 pixels).
pub const SCREEN_WIDTH: usize = 64;

/// Virtual screen height (32 pixels).
pub const SCREEN_HEIGHT: usize = 32;

/// Virtual screen area (2048 pixels).
pub const SCREEN_AREA: usize = SCREEN_WIDTH * SCREEN_HEIGHT;

// Source for font and constants:
// https://aquova.net/emudev/chip8/
const FONTSET_SIZE: usize = 80;
const FONT_ADDR: u16 = 0x050;

// Some games may behave differently based on the font.
// This font set is common.
const FONTSET: [u8; FONTSET_SIZE] = [
    0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
    0x20, 0x60, 0x20, 0x20, 0x70, // 1
    0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
    0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
    0x90, 0x90, 0xF0, 0x10, 0x10, // 4
    0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
    0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
    0xF0, 0x10, 0x20, 0x40, 0x40, // 7
    0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
    0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
    0xF0, 0x90, 0xF0, 0x90, 0x90, // A
    0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
    0xF0, 0x80, 0x80, 0x80, 0xF0, // C
    0xE0, 0x90, 0x90, 0x90, 0xE0, // D
    0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
    0xF0, 0x80, 0xF0, 0x80, 0x80, // F
];

const RAM_SIZE: usize = 4096;
const NUM_REGS: usize = 16;
const STACK_SIZE: usize = 16;
const NUM_KEYS: usize = 16;
const VF: usize = 15;
const START_ADDR: u16 = 0x200;

#[derive(Debug)]
struct Opcode(u8, u8, u8, u8);

// struct Oxid8 fields based on:
// https://aquova.net/emudev/chip8/

/// Oxid8 Core
#[derive(Debug)]
pub struct Oxid8 {
    pc: u16,                     // Program Counter
    ram: [u8; RAM_SIZE],         // RAM
    screen: [bool; SCREEN_AREA], // Monochrome Display
    v_reg: [u8; NUM_REGS],       // 8-bit V Registers
    i_reg: u16,                  // 16[12]-bit I Register
    sp: u16,                     // Stack Pointer
    stack: [u16; STACK_SIZE],    // Stack
    keys: [bool; NUM_KEYS],      // Keys (0-F)
    stored_key: Option<usize>,   // Stored key
    dt: u8,                      // Delay Timer
    st: u8,                      // Sound Timer
    rng: ThreadRng,              // RNG
}

/// 4-byte opcode.
impl Opcode {
    /// New Opcode.
    fn new(byte1: u8, byte2: u8) -> Self {
        Self(
            (byte1 & 0xF0) >> 4,
            byte1 & 0x0F,
            (byte2 & 0xF0) >> 4,
            byte2 & 0x0F,
        )
    }

    /// A 16-bit value, the whole instruction.
    fn full(&self) -> u16 {
        (self.0 as u16) << 12 | (self.1 as u16) << 8 | (self.2 as u16) << 4 | (self.3 as u16)
    }

    /// A 12-bit value, the lowest 12 bits of the instruction.
    fn nnn(&self) -> u16 {
        (self.1 as u16) << 8 | (self.2 as u16) << 4 | (self.3 as u16)
    }

    /// A 4-bit value, the lowest 4 bits of the instruction.
    fn n(&self) -> u8 {
        self.3
    }

    /// A 4-bit value, the lower 4 bits of the high byte of the instruction.
    fn x(&self) -> u8 {
        self.1
    }

    /// A 4-bit value, the upper 4 bits of the low byte of the instruction.
    fn y(&self) -> u8 {
        self.2
    }

    /// An 8-bit value, the lowest 8 bits of the instruction.
    fn kk(&self) -> u8 {
        self.2 << 4 | self.3
    }
}

/// Formatted as "(byte1, byte2, byte3, byte4)"
impl fmt::Display for Opcode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {}, {}, {})", self.0, self.1, self.2, self.3)
    }
}

/// Oxid8 Core
impl Oxid8 {
    /// Create a new oxid8 instance.
    pub fn new() -> Self {
        Oxid8::default()
    }

    /// Reset all parameters to default.
    /// Must call `load_font` to reload font.
    pub fn reset(&mut self) {
        *self = Oxid8::default();
    }

    /// Emulates a full frame.
    ///
    /// Each frame emulates 10 cpu cycles and decrements
    /// the sound and delay timers. If your frame time is
    /// 60Hz, cpu cycles run at 600Hz and timers at 60Hz.
    /// CHIP-8 cpu cycles have historically ran anywhere
    /// between 500Hz to 700Hz depending on hardware and
    /// implementation. If you want finer control over
    /// cpu speeds use call `run_cycle` yourself, and
    /// call `dec_timers` at a rate of 16ms.
    ///
    /// # Errors
    ///
    /// Invalid opcodes will cause `frame` to return
    /// an error string with the full opcode and program
    /// counter at that point. The rom is bad.
    ///
    /// # Panics
    ///
    /// `push` and `pop` instructions can panic with a
    /// Stack Overflow/Underflow error.
    ///
    /// Other opcodes may panic if the game attempts to
    /// perform an invalid action. Otherwise the interpreter
    /// can be left in an invalid state. The rom is bad.
    pub fn next_frame(&mut self) -> Result<(), String> {
        for _ in 0..10 {
            self.run_cycle()?;
        }
        self.dec_timers();

        Ok(())
    }

    /// Emulates a single cycle.
    ///
    /// Use `next_frame` instead if you don't want to
    /// control cpu speed.
    ///
    /// # Errors
    ///
    /// Invalid opcodes will cause `run_cycle` to return
    /// an error string with the full opcode and program
    /// counter at that point. The rom is bad.
    ///
    /// # Panics
    ///
    /// `push` and `pop` instructions can panic with a
    /// Stack Overflow/Underflow error.
    ///
    /// Other opcodes may panic if the game attempts to
    /// perform an invalid action. Otherwise the interpreter
    /// can be left in an invalid state. The rom is bad.
    pub fn run_cycle(&mut self) -> Result<(), String> {
        let opcode = Opcode::new(
            self.ram[self.pc as usize],     //
            self.ram[self.pc as usize + 1], //
        );

        let pc_at_err = self.pc;
        self.pc += 2;

        let invalid = || -> Result<(), String> {
            Err(format!(
                "Invalid Instruction: {:04X} at {}",
                opcode.full(),
                pc_at_err,
            ))
        };

        match opcode.0 {
            0x0 => match opcode.kk() {
                0xE0 => self.cls(),
                0xEE => self.ret(),
                _ => invalid()?,
            },
            0x1 => self.jp_nnn(opcode.nnn()),
            0x2 => self.call(opcode.nnn()),
            0x3 => self.se_xkk(opcode.x() as usize, opcode.kk()),
            0x4 => self.sne_xkk(opcode.x() as usize, opcode.kk()),
            0x5 => self.se_xy(opcode.x() as usize, opcode.y() as usize),
            0x6 => self.ld_xkk(opcode.x() as usize, opcode.kk()),
            0x7 => self.add_xkk(opcode.x() as usize, opcode.kk()),
            0x8 => match opcode.n() {
                0x0 => self.ld_xy(opcode.x() as usize, opcode.y() as usize),
                0x1 => self.or(opcode.x() as usize, opcode.y() as usize),
                0x2 => self.and(opcode.x() as usize, opcode.y() as usize),
                0x3 => self.xor(opcode.x() as usize, opcode.y() as usize),
                0x4 => self.add_xy(opcode.x() as usize, opcode.y() as usize),
                0x5 => self.sub_xy(opcode.x() as usize, opcode.y() as usize),
                0x6 => self.shr(opcode.x() as usize, opcode.y() as usize),
                0x7 => self.subn_xy(opcode.x() as usize, opcode.y() as usize),
                0xE => self.shl(opcode.x() as usize, opcode.y() as usize),
                _ => invalid()?,
            },
            0x9 => self.sne_xy(opcode.x() as usize, opcode.y() as usize),
            0xA => self.ld_innn(opcode.nnn()),
            0xB => self.jp_0nnn(opcode.nnn()),
            0xC => self.rnd(opcode.x() as usize, opcode.kk()),
            0xD => {
                self.drw(
                    opcode.x() as usize, //
                    opcode.y() as usize, //
                    opcode.n(),          //
                );
            }
            0xE => match opcode.kk() {
                0x9E => self.skp(opcode.x() as usize),
                0xA1 => self.sknp(opcode.x() as usize),
                _ => invalid()?,
            },
            0xF => match opcode.kk() {
                0x07 => self.ld_xdt(opcode.x() as usize),
                0x0A => self.ld_xk(opcode.x() as usize),
                0x15 => self.ld_dtx(opcode.x() as usize),
                0x18 => self.ld_stx(opcode.x() as usize),
                0x1E => self.add_ix(opcode.x() as usize),
                0x29 => self.ld_fx(opcode.x() as usize),
                0x33 => self.ld_bx(opcode.x() as usize),
                0x55 => self.ld_ix(opcode.x() as usize),
                0x65 => self.ld_xi(opcode.x() as usize),
                _ => invalid()?,
            },
            _ => invalid()?,
        }

        Ok(())
    }

    /// Decrements the delay and sound and timers.
    ///
    /// Use `next_frame` instead if you don't want to
    /// control cpu speed.
    pub fn dec_timers(&mut self) {
        if self.dt > 0 {
            self.dt -= 1;
        }
        if self.st > 0 {
            self.st -= 1;
        }
    }

    /// Returns true if sound timer is zero.
    #[must_use]
    pub fn sound(&self) -> bool {
        self.st != 0
    }

    /// Sets a key on the virtual keypad.
    ///
    /// # Panics
    ///
    /// `set_key` panics if key is out of bounds.
    /// Expects 0x0 - 0xF (0 - 15).
    pub fn set_key(&mut self, k: usize, val: bool) {
        self.keys[k] = val;
    }

    /// Clears the virtual keypad.
    pub fn clear_keys(&mut self) {
        self.keys = [false; NUM_KEYS];
    }

    /// Returns a reference to the screen.
    #[must_use]
    pub fn screen_ref(&self) -> &[bool; SCREEN_AREA] {
        &self.screen
    }

    /// Instructs the interpreter to load the fontset.
    pub fn load_font(&mut self) {
        self.ram[FONT_ADDR as usize..(FONT_ADDR as usize + FONTSET_SIZE)] //
            .copy_from_slice(&FONTSET);
    }

    /// Loads a rom given a filename.
    ///
    /// # Errors
    ///
    /// If there is any issue loading the ROM, then an error is returned.
    pub fn load_rom(&mut self, path: impl AsRef<std::path::Path>) -> io::Result<()> {
        use std::fs;

        let rom_data: Vec<u8> = fs::read(path)?;
        self.load_rom_bytes(rom_data.as_slice())
    }

    /// Loads a rom from byte array.
    ///
    /// # Errors
    ///
    /// If there is any issue loading the ROM, then an error is returned.
    pub fn load_rom_bytes(&mut self, rom_data: &[u8]) -> io::Result<()> {
        let len = rom_data.len();
        if len > (RAM_SIZE - START_ADDR as usize) {
            return Err(io::Error::new(
                io::ErrorKind::FileTooLarge,
                format!("ROM too large: {}", len),
            ));
        }

        self.ram[START_ADDR as usize..(START_ADDR as usize + len)] //
            .copy_from_slice(rom_data);

        Ok(())
    }

    /// Pushes `val` onto the program stack and increments the stack pointer.
    ///
    /// # Panics
    ///
    /// `push` panics if the stack overflows.
    fn push(&mut self, val: u16) {
        match self.sp as usize {
            0..STACK_SIZE => {
                self.stack[self.sp as usize] = val;
                self.sp += 1;
            }
            _ => panic!("ERROR::Emulator Stack Overflow"),
        };
    }

    /// Pops top value off the program stack and decrements the stack pointer.
    ///
    /// # Panics
    ///
    /// `pop` panics if the stack underflows.
    fn pop(&mut self) -> u16 {
        match self.sp as usize {
            1..=STACK_SIZE => {
                self.sp -= 1;
                self.stack[self.sp as usize]
            }
            _ => panic!("ERROR::Emulator Stack Underflow"),
        }
    }
}

impl Default for Oxid8 {
    fn default() -> Self {
        Self {
            pc: START_ADDR,
            ram: [0; RAM_SIZE],
            screen: [false; SCREEN_WIDTH * SCREEN_HEIGHT],
            v_reg: [0; NUM_REGS],
            i_reg: 0,
            sp: 0,
            stack: [0; STACK_SIZE],
            keys: [false; NUM_KEYS],
            stored_key: None,
            dt: 0,
            st: 0,
            rng: rng(),
        }
    }
}

// Cowgod's Chip-8 Technical Reference v1.0:
// http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#0.1

/// Oxid8 CPU Instructions
///
/// # Naming Conventions:
/// - n:      half-byte
/// - kk:     byte
/// - nnn:    address
/// - x,y,i:  register
/// - dt:     delay timer
/// - st:     sound timer
/// - k:      key
impl Oxid8 {
    /// 00E0 - Clear the display.
    fn cls(&mut self) {
        self.screen = [false; SCREEN_WIDTH * SCREEN_HEIGHT];
    }

    /// 00EE - Return from a subroutine.
    fn ret(&mut self) {
        self.pc = self.pop();
    }

    /// 1nnn - Jump to location nnn.
    fn jp_nnn(&mut self, nnn: u16) {
        self.pc = nnn;
    }

    /// 2nnn - Call subroutine at nnn.
    fn call(&mut self, nnn: u16) {
        self.push(self.pc);
        self.pc = nnn;
    }

    /// 3xkk - Skip next instruction if Vx = kk.
    fn se_xkk(&mut self, x: usize, kk: u8) {
        if self.v_reg[x] == kk {
            self.pc += 2;
        }
    }

    /// 4xkk - Skip next instruction if Vx != kk.
    fn sne_xkk(&mut self, x: usize, kk: u8) {
        if self.v_reg[x] != kk {
            self.pc += 2;
        }
    }

    /// 5xy0 - Skip next instruction if Vx = Vy.
    fn se_xy(&mut self, x: usize, y: usize) {
        if self.v_reg[x] == self.v_reg[y] {
            self.pc += 2;
        }
    }

    /// 6xkk - Set Vx = kk.
    fn ld_xkk(&mut self, x: usize, kk: u8) {
        self.v_reg[x] = kk;
    }

    /// 7xkk - Set Vx = Vx + kk.
    fn add_xkk(&mut self, x: usize, kk: u8) {
        self.v_reg[x] = self.v_reg[x].wrapping_add(kk);
    }

    /// 8xy0 - Set Vx = Vy.
    fn ld_xy(&mut self, x: usize, y: usize) {
        self.v_reg[x] = self.v_reg[y];
    }

    /// 8xy1 - Set Vx = Vx OR Vy.
    fn or(&mut self, x: usize, y: usize) {
        self.v_reg[x] |= self.v_reg[y];
    }

    /// 8xy2 - Set Vx = Vx AND Vy.
    fn and(&mut self, x: usize, y: usize) {
        self.v_reg[x] &= self.v_reg[y];
    }

    /// 8xy3 - Set Vx = Vx XOR Vy.
    fn xor(&mut self, x: usize, y: usize) {
        self.v_reg[x] ^= self.v_reg[y];
    }

    /// 8xy4 - Set Vx = Vx + Vy, set VF = carry.
    fn add_xy(&mut self, x: usize, y: usize) {
        let (vx, carry) = self.v_reg[x].overflowing_add(self.v_reg[y]);
        self.v_reg[x] = vx;
        self.v_reg[VF] = carry as u8;
    }

    /// 8xy5 - Set Vx = Vx - Vy, set VF = NOT borrow.
    fn sub_xy(&mut self, x: usize, y: usize) {
        let (vx, borrow) = self.v_reg[x].overflowing_sub(self.v_reg[y]);
        self.v_reg[x] = vx;
        self.v_reg[VF] = !borrow as u8;
    }

    /// 8xy6 - Set Vx = Vx SHR 1.
    fn shr(&mut self, x: usize, _y: usize) {
        let vx = self.v_reg[x];
        self.v_reg[x] = vx >> 1;
        self.v_reg[VF] = vx & 1;
    }

    /// 8xy7 - Set Vx = Vy - Vx, set VF = NOT borrow.
    fn subn_xy(&mut self, x: usize, y: usize) {
        let (vx, borrow) = self.v_reg[y].overflowing_sub(self.v_reg[x]);
        self.v_reg[x] = vx;
        self.v_reg[VF] = !borrow as u8;
    }

    /// 8xyE - Set Vx = Vx SHL 1.
    fn shl(&mut self, x: usize, _y: usize) {
        let vx = self.v_reg[x];
        self.v_reg[x] = vx << 1;
        self.v_reg[VF] = (vx >> 7) & 1;
    }

    /// 9xy0 - Skip next instruction if Vx != Vy.
    fn sne_xy(&mut self, x: usize, y: usize) {
        if self.v_reg[x] != self.v_reg[y] {
            self.pc += 2;
        }
    }

    /// Annn - Set I = nnn.
    fn ld_innn(&mut self, nnn: u16) {
        self.i_reg = nnn;
    }

    /// Bnnn - Jump to location nnn + V0.
    fn jp_0nnn(&mut self, nnn: u16) {
        self.pc = nnn + self.v_reg[0] as u16;
    }

    /// Cxkk - Set Vx = random byte AND kk.
    fn rnd(&mut self, x: usize, kk: u8) {
        self.v_reg[x] = self.rng.random_range(0..=0xFF) as u8 & kk;
    }

    /// Dxyn - Display n-byte sprite starting at memory location I at (Vx, Vy),
    /// set VF = collision.
    fn drw(&mut self, x: usize, y: usize, n: u8) {
        // a sprite is a byte wide and n in [1,15] rows where n is an integer
        let (x, y) = (
            self.v_reg[x] as usize % SCREEN_WIDTH,  // wrap
            self.v_reg[y] as usize % SCREEN_HEIGHT, // wrap
        );
        self.v_reg[VF] = 0; // turn off collision flag
        let start_pixel: usize = (y * SCREEN_WIDTH) + x;
        let start_addr: usize = self.i_reg as usize;

        // draw n bytes to the screen
        for i in 0..n as usize {
            if y + i >= SCREEN_HEIGHT {
                break; // clip
            }
            let pixel_posn: usize = start_pixel + (SCREEN_WIDTH * i);
            let sprite_row: u8 = self.ram[start_addr + i];

            // for each bit
            for j in 0..8 {
                if x + j >= SCREEN_WIDTH {
                    break; // clip
                }
                let ref mut pixel_ref = self.screen[pixel_posn + j];
                let old_pixel = *pixel_ref;

                let sprite_pixel = (sprite_row >> (0x7 - j)) & 0x1;
                *pixel_ref ^= sprite_pixel != 0;

                if !(*pixel_ref) && old_pixel {
                    self.v_reg[VF] = 1; // turn on collision flag
                }
            }
        }
    }

    /// Ex9E - Skip next instruction if key with the value of Vx is pressed.
    fn skp(&mut self, x: usize) {
        if self.keys[self.v_reg[x] as usize] {
            self.pc += 2;
        }
    }

    /// ExA1 - Skip next instruction if key with the value of Vx is not pressed.
    fn sknp(&mut self, x: usize) {
        if !self.keys[self.v_reg[x] as usize] {
            self.pc += 2;
        }
    }

    /// Fx07 - Set Vx = delay timer value.
    fn ld_xdt(&mut self, x: usize) {
        self.v_reg[x] = self.dt;
    }

    /// Fx0A - Wait for a key press, store the value of the key in Vx.
    fn ld_xk(&mut self, x: usize) {
        match self.stored_key {
            Some(k) => {
                // Wait for key release
                if !self.keys[k] {
                    self.v_reg[x] = k as u8;
                    self.stored_key = None;
                    return;
                }
            }
            None => {
                // Store key press
                for (k, &pressed) in self.keys.iter().enumerate() {
                    if pressed {
                        self.stored_key = Some(k);
                        break;
                    }
                }
            }
        }
        // Halt: set pc to previous state
        self.pc -= 2;
    }

    /// Fx15 - Set delay timer = Vx.
    fn ld_dtx(&mut self, x: usize) {
        self.dt = self.v_reg[x];
    }

    /// Fx18 - Set sound timer = Vx.
    fn ld_stx(&mut self, x: usize) {
        self.st = self.v_reg[x];
    }

    /// Fx1E - Set I = I + Vx.
    fn add_ix(&mut self, x: usize) {
        self.i_reg = self.i_reg.wrapping_add(self.v_reg[x] as u16);
    }

    /// Fx29 - Set I = location of sprite for digit Vx.
    fn ld_fx(&mut self, x: usize) {
        self.i_reg = FONT_ADDR + (self.v_reg[x] as u16 * 5);
    }

    /// Fx33 - Store BCD representation of Vx in memory locations I, I+1, and I+2.
    fn ld_bx(&mut self, x: usize) {
        let i = self.i_reg as usize;
        let v = self.v_reg[x];
        self.ram[i] = (v / 100) % 10;
        self.ram[i + 1] = (v / 10) % 10;
        self.ram[i + 2] = v % 10;
    }

    /// Fx55 - Store registers V0 through Vx in memory starting at location I.
    fn ld_ix(&mut self, x: usize) {
        let i = self.i_reg as usize;
        self.ram[i..=(i + x)].copy_from_slice(&self.v_reg[0..=x]);
    }

    /// Fx65 - Read registers V0 through Vx from memory starting at location I.
    fn ld_xi(&mut self, x: usize) {
        let i = self.i_reg as usize;
        self.v_reg[0..=x].copy_from_slice(&self.ram[i..=(i + x)]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        // for misc testing
        let a: [u8; 5] = [255, 155, 100, 55, 5];
        let i: u16 = 0;
        assert_eq!(255, a[i as usize]);
        assert_eq!(155, a[i as usize + 1]);
    }

    #[test]
    fn opcode_new() {
        let opcode = Opcode::new(0x12, 0x34);
        assert_eq!(opcode.0, 0x1);
        assert_eq!(opcode.1, 0x2);
        assert_eq!(opcode.2, 0x3);
        assert_eq!(opcode.3, 0x4);
    }

    #[test]
    fn opcode_decode() {
        let opcode = Opcode::new(0x12, 0x34);
        assert_eq!(opcode.full(), 0x1234);
        assert_eq!(opcode.nnn(), 0x234);
        assert_eq!(opcode.n(), 0x4);
        assert_eq!(opcode.x(), 0x2);
        assert_eq!(opcode.y(), 0x3);
        assert_eq!(opcode.kk(), 0x34);
    }

    #[test]
    fn invalid_opcode() {
        let mut emu = Oxid8::new();
        emu.ram[START_ADDR as usize] = 0xFF;
        emu.ram[START_ADDR as usize + 1] = 0xFF;
        assert!(emu.run_cycle().is_err_and(|msg| msg
            == format!(
                "Invalid Instruction: FFFF at {}", //
                START_ADDR                         //
            )))
    }

    #[test]
    fn push_pop() {
        let mut emu = Oxid8::new();
        assert_eq!(emu.sp, 0); // base stack pointer
        emu.push(1); // push
        assert_eq!(emu.sp, 1); // inc stack pointer
        assert_eq!(emu.stack[0], 1); // value on stack
        assert_eq!(emu.pop(), 1); // pop
        assert_eq!(emu.sp, 0); // dec stack pointer
    }

    #[test]
    #[should_panic(expected = "Stack Overflow")]
    fn push_panic() {
        let mut emu = Oxid8::new();
        for _ in 0..=STACK_SIZE {
            emu.push(1);
        }
    }

    #[test]
    #[should_panic(expected = "Stack Underflow")]
    fn pop_panic() {
        let mut emu = Oxid8::new();
        emu.pop();
    }

    #[test]
    fn load_font() {
        let mut emu = Oxid8::new();
        emu.load_font();
        assert_eq!(
            emu.ram[FONT_ADDR as usize..(FONT_ADDR as usize + FONTSET_SIZE)],
            FONTSET
        );
    }

    #[test]
    fn draw_basic() {
        // Largest drawable sprite.
        // Just two 'X' on top of each other sized 8x15.
        let sprite = [
            0x81, 0x42, 0x24, 0x18, //
            0x18, 0x24, 0x42, 0x81, //
            0x42, 0x24, 0x18, 0x18, //
            0x24, 0x42, 0x81, //
        ];

        let screen = [
            true, false, false, false, false, false, false, true, // 1
            false, true, false, false, false, false, true, false, // 2
            false, false, true, false, false, true, false, false, // 3
            false, false, false, true, true, false, false, false, // 4
            false, false, false, true, true, false, false, false, // 5
            false, false, true, false, false, true, false, false, // 6
            false, true, false, false, false, false, true, false, // 7
            true, false, false, false, false, false, false, true, // 8
            false, true, false, false, false, false, true, false, // 9
            false, false, true, false, false, true, false, false, // 10
            false, false, false, true, true, false, false, false, // 11
            false, false, false, true, true, false, false, false, // 12
            false, false, true, false, false, true, false, false, // 13
            false, true, false, false, false, false, true, false, // 14
            true, false, false, false, false, false, false, true, // 15
        ];

        let mut emu = Oxid8::new();

        emu.i_reg = START_ADDR;
        let start = START_ADDR as usize;

        emu.ram[start..start + sprite.len()].copy_from_slice(&sprite);
        emu.drw(0, 0, sprite.len() as u8);

        for i in 0..15 {
            let offset1: usize = i * SCREEN_WIDTH;
            let offset2: usize = i * 8;
            assert_eq!(
                emu.screen[offset1 + 0..offset1 + 8],
                screen[offset2 + 0..offset2 + 8]
            );
        }
    }
}