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
use crate::trace::{CpuTrace, TraceHandler};
use std::{
  fs::File,
  io::{BufWriter, Write},
};

pub struct FileTraceHandler {
  file: BufWriter<File>,
}

impl FileTraceHandler {
  pub fn new(filename: String) -> Self {
    Self {
      file: BufWriter::new(File::create(filename).expect("Invalid filename")),
    }
  }
}

impl TraceHandler for FileTraceHandler {
  fn handle(&mut self, trace: &CpuTrace) {
    self
      .file
      .write_all(format!("{:04X}: {:02X}\n", trace.address, trace.opcode).as_bytes())
      .unwrap();
  }

  fn flush(&mut self) -> Result<(), &str> {
    self.file.flush().map_err(|_| "failed to flush file")
  }
}