neser 0.1.1

NESER - NES Emulator in Rust - is a NES emulator written in Rust. It aims to be a high-quality, hardware-accurate emulator that is also easy to use and extend. It supports a wide range of NES games and features, including various mappers, audio processing, and input handling. NESER is designed to be modular and extensible, allowing developers to easily add new features or support for additional hardware. It can be run using one of two frontends: a native desktop application using SDL2, or a web application using WebAssembly. The desktop application provides a high-performance, feature-rich experience with support for various input devices and display options, while the web application allows users to play NES games directly in their browsers without needing to install any software in a BYOR manner (Bring Your Own Roms).
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
//! Breakpoint engine for the NES debugger.
//!
//! Supports four condition types: PC match, CPU cycle count, CPU frame count, and CPU write-address.

use std::fmt;

/// The condition that triggers a breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakpointKind {
    /// Break when the program counter reaches the given address.
    Pc(u16),
    /// Break when the CPU cycle count equals the given value.
    Cycle(u64),
    /// Break when execution reaches the first instruction boundary on the given frame.
    Frame(u64),
    /// Break when the CPU writes to the given address (non-dummy write).
    WriteAddress(u16),
}

impl fmt::Display for BreakpointKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BreakpointKind::Pc(addr) => write!(f, "PC={:04X}", addr),
            BreakpointKind::Cycle(n) => write!(f, "CYC={}", n),
            BreakpointKind::Frame(n) => write!(f, "FRM={}", n),
            BreakpointKind::WriteAddress(addr) => write!(f, "WR={:04X}", addr),
        }
    }
}

/// A single breakpoint with a condition and an enabled state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Breakpoint {
    pub kind: BreakpointKind,
    pub enabled: bool,
}

impl Breakpoint {
    pub fn new(kind: BreakpointKind) -> Self {
        Self {
            kind,
            enabled: true,
        }
    }

    /// Returns true if this breakpoint is enabled and its condition matches `ctx`.
    pub fn is_hit(&self, ctx: &EvalContext) -> bool {
        if !self.enabled {
            return false;
        }
        match self.kind {
            BreakpointKind::Pc(addr) => ctx.pc == addr,
            BreakpointKind::Cycle(target) => {
                ctx.prev_cpu_cycles < target && ctx.cpu_cycles >= target
            }
            BreakpointKind::Frame(target) => ctx.prev_frame < target && ctx.frame >= target,
            BreakpointKind::WriteAddress(addr) => ctx.write_addr == Some(addr),
        }
    }

    /// Serialize to a plain-text line suitable for a `.debug` file.
    pub fn serialize(&self) -> String {
        let state = if self.enabled { "enabled" } else { "disabled" };
        match self.kind {
            BreakpointKind::Pc(addr) => format!("pc {:#06X} {}", addr, state),
            BreakpointKind::Cycle(n) => format!("cycle {} {}", n, state),
            BreakpointKind::Frame(n) => format!("frame {} {}", n, state),
            BreakpointKind::WriteAddress(addr) => format!("write {:#06X} {}", addr, state),
        }
    }

    /// Parse a plain-text line from a `.debug` file. Returns `None` for comments/blank lines.
    pub fn parse(line: &str) -> Option<Self> {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            return None;
        }
        let parts: Vec<&str> = line.splitn(3, ' ').collect();
        if parts.len() != 3 {
            return None;
        }
        let enabled = parts[2] != "disabled";
        let kind = match parts[0] {
            "pc" => {
                let addr = parse_u16(parts[1])?;
                BreakpointKind::Pc(addr)
            }
            "cycle" => {
                let n: u64 = parts[1].parse().ok()?;
                BreakpointKind::Cycle(n)
            }
            "frame" => {
                let n: u64 = parts[1].parse().ok()?;
                BreakpointKind::Frame(n)
            }
            "write" => {
                let addr = parse_u16(parts[1])?;
                BreakpointKind::WriteAddress(addr)
            }
            _ => return None,
        };
        Some(Self { kind, enabled })
    }
}

/// Parses a `u16` from either a hex string (`0x`/`0X` prefix) or a decimal string.
fn parse_u16(s: &str) -> Option<u16> {
    if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        u16::from_str_radix(hex, 16).ok()
    } else {
        s.parse().ok()
    }
}

/// Execution context passed to breakpoint evaluation after each CPU instruction.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct EvalContext {
    /// Current program counter value.
    pub pc: u16,
    /// Total CPU cycles before this instruction executed.
    pub prev_cpu_cycles: u64,
    /// Total CPU cycles after this instruction executed.
    pub cpu_cycles: u64,
    /// PPU frame counter value before this instruction executed.
    pub prev_frame: u64,
    /// PPU frame counter value after this instruction executed.
    pub frame: u64,
    /// Address written during this instruction (non-dummy write), if any.
    pub write_addr: Option<u16>,
}

/// An ordered list of persistent breakpoints.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct BreakpointList {
    items: Vec<Breakpoint>,
}

impl BreakpointList {
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of breakpoints.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns `true` if there are no breakpoints.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Add a breakpoint. Deduplicates by kind — if the kind already exists, the add is a no-op.
    pub fn add(&mut self, kind: BreakpointKind) {
        if !self.items.iter().any(|b| b.kind == kind) {
            self.items.push(Breakpoint::new(kind));
        }
    }

    /// Remove the breakpoint at the given index. No-op if out of bounds.
    pub fn remove(&mut self, index: usize) {
        if index < self.items.len() {
            self.items.remove(index);
        }
    }

    /// Enable the breakpoint at the given index. No-op if out of bounds.
    pub fn enable(&mut self, index: usize) {
        self.set_enabled(index, true);
    }

    /// Disable the breakpoint at the given index. No-op if out of bounds.
    pub fn disable(&mut self, index: usize) {
        self.set_enabled(index, false);
    }

    fn set_enabled(&mut self, index: usize, enabled: bool) {
        if let Some(bp) = self.items.get_mut(index) {
            bp.enabled = enabled;
        }
    }

    /// Returns an iterator over all breakpoints.
    pub fn iter(&self) -> std::slice::Iter<'_, Breakpoint> {
        self.items.iter()
    }

    /// Returns `true` if there is any PC breakpoint at `addr`, regardless of enabled state.
    /// Useful for checking pre-existence before conditionally adding a temporary breakpoint.
    pub fn has_pc_breakpoint_at(&self, addr: u16) -> bool {
        self.items
            .iter()
            .any(|b| b.kind == BreakpointKind::Pc(addr))
    }

    /// Returns `true` if there is an enabled PC breakpoint at `addr`.
    pub fn has_enabled_pc_breakpoint_at(&self, addr: u16) -> bool {
        self.items
            .iter()
            .any(|b| b.kind == BreakpointKind::Pc(addr) && b.enabled)
    }

    /// Serialize all breakpoints to a multi-line string for `.debug` file storage.
    pub fn save_to_string(&self) -> String {
        self.items
            .iter()
            .map(|bp| bp.serialize())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Parse breakpoints from a `.debug` file string, skipping blank/comment lines.
    pub fn load_from_str(text: &str) -> Self {
        let items = text.lines().filter_map(Breakpoint::parse).collect();
        Self { items }
    }
}

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

    // --- BreakpointKind display ---

    #[test]
    fn test_breakpoint_kind_pc_displays_as_hex() {
        assert_eq!(format!("{}", BreakpointKind::Pc(0xC000)), "PC=C000");
    }

    #[test]
    fn test_breakpoint_kind_cycle_displays_with_count() {
        assert_eq!(format!("{}", BreakpointKind::Cycle(12345)), "CYC=12345");
    }

    #[test]
    fn test_breakpoint_kind_frame_displays_with_count() {
        assert_eq!(format!("{}", BreakpointKind::Frame(42)), "FRM=42");
    }

    #[test]
    fn test_breakpoint_kind_write_address_displays_as_hex() {
        assert_eq!(
            format!("{}", BreakpointKind::WriteAddress(0x2006)),
            "WR=2006"
        );
    }

    // --- PC breakpoint evaluation ---

    #[test]
    fn test_pc_breakpoint_hits_when_pc_matches() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_pc_breakpoint_does_not_hit_when_pc_differs() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC001,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_pc_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- Cycle breakpoint evaluation ---

    #[test]
    fn test_cycle_breakpoint_hits_when_cycle_crosses_threshold() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 998,
            cpu_cycles: 1002,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_hits_when_cycle_matches_exactly() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 999,
            cpu_cycles: 1000,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_hit_before_target_cycle() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 999,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_fire_again_after_threshold_crossed() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        // Both prev and current are past the target — threshold already crossed, should not re-fire.
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 1001,
            cpu_cycles: 1003,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 999,
            cpu_cycles: 1002,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- Frame breakpoint evaluation ---

    #[test]
    fn test_frame_breakpoint_hits_when_frame_crosses_threshold() {
        let bp = Breakpoint::new(BreakpointKind::Frame(5));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 4,
            frame: 5,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_frame_breakpoint_does_not_hit_before_target_frame() {
        let bp = Breakpoint::new(BreakpointKind::Frame(5));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 4,
            frame: 4,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- WriteAddress breakpoint evaluation ---

    #[test]
    fn test_write_address_breakpoint_hits_when_write_matches() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_on_read() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_on_different_address_write() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2007),
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- BreakpointList management ---

    #[test]
    fn test_breakpoint_list_starts_empty() {
        let list = BreakpointList::new();
        assert_eq!(list.len(), 0);
    }

    #[test]
    fn test_breakpoint_list_add_pc_breakpoint() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_pc() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Pc(0xC000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_cycle() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Cycle(1000));
        list.add(BreakpointKind::Cycle(1000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_frame() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Frame(60));
        list.add(BreakpointKind::Frame(60));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_write_address() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::WriteAddress(0x2006));
        list.add(BreakpointKind::WriteAddress(0x2006));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_remove_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Cycle(500));
        list.remove(0);
        assert_eq!(list.len(), 1);
        assert!(matches!(
            list.iter().next().map(|b| &b.kind),
            Some(BreakpointKind::Cycle(500))
        ));
    }

    #[test]
    fn test_breakpoint_list_remove_out_of_bounds_is_noop() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.remove(5); // no-op
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_enable_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        list.enable(0);
        assert!(list.iter().next().map(|b| b.enabled).unwrap_or(false));
    }

    #[test]
    fn test_breakpoint_list_disable_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        assert!(!list.iter().next().map(|b| b.enabled).unwrap_or(true));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_pc() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_cycle() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Cycle(500));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 498,
            cpu_cycles: 501,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_write_address() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_no_match() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xD000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_disabled() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_empty() {
        let list = BreakpointList::new();
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 498,
            cpu_cycles: 501,
            write_addr: Some(0x2006),
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    // --- Serialization (plain text .debug format) ---

    #[test]
    fn test_breakpoint_kind_serialize_pc() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        assert_eq!(bp.serialize(), "pc 0xC000 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_cycle() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(12345));
        assert_eq!(bp.serialize(), "cycle 12345 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_frame() {
        let bp = Breakpoint::new(BreakpointKind::Frame(42));
        assert_eq!(bp.serialize(), "frame 42 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_write_address() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        assert_eq!(bp.serialize(), "write 0x2006 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        bp.enabled = false;
        assert_eq!(bp.serialize(), "pc 0xC000 disabled");
    }

    #[test]
    fn test_breakpoint_list_parse_pc_line() {
        let bp = Breakpoint::parse("pc 0xC000 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Pc(0xC000)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_cycle_line() {
        let bp = Breakpoint::parse("cycle 12345 disabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Cycle(12345)));
        assert!(!bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_frame_line() {
        let bp = Breakpoint::parse("frame 42 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Frame(42)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_write_line() {
        let bp = Breakpoint::parse("write 0x2006 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::WriteAddress(0x2006)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_ignores_comment_lines() {
        assert!(Breakpoint::parse("# this is a comment").is_none());
    }

    #[test]
    fn test_breakpoint_list_parse_ignores_empty_lines() {
        assert!(Breakpoint::parse("").is_none());
    }

    #[test]
    fn test_breakpoint_list_roundtrip_serialize_parse() {
        let original = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let serialized = original.serialize();
        let parsed = Breakpoint::parse(&serialized).unwrap();
        assert_eq!(parsed.kind, original.kind);
        assert_eq!(parsed.enabled, original.enabled);
    }

    #[test]
    fn test_breakpoint_list_save_and_load_roundtrip() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Cycle(500));
        list.add(BreakpointKind::WriteAddress(0x2006));
        list.disable(1);

        let text = list.save_to_string();
        let loaded = BreakpointList::load_from_str(&text);

        assert_eq!(loaded.len(), 3);
        assert!(matches!(
            loaded.iter().next().map(|b| &b.kind),
            Some(BreakpointKind::Pc(0xC000))
        ));
        assert!(loaded.iter().next().map(|b| b.enabled).unwrap_or(false));
        assert!(matches!(
            loaded.iter().nth(1).map(|b| &b.kind),
            Some(BreakpointKind::Cycle(500))
        ));
        assert!(!loaded.iter().nth(1).map(|b| b.enabled).unwrap_or(true));
        assert!(matches!(
            loaded.iter().nth(2).map(|b| &b.kind),
            Some(BreakpointKind::WriteAddress(0x2006))
        ));
    }
}