malloc
malloc

Reputation: 313

Copy binary file in vector

I'm trying to get familiar with Rust (and learn it) by writing an emulator. I need to load a file (my rom image) into a vector, that is my emulated ram.

This is my code:

let image = std::fs::read(filepath).ok().unwrap();
let mut i = 0;
for n in image {
    self.memory[400 + i] = n;
    i += 1;
}

memory is a Vec<u8> initialized with all zeros (memory: vec![0; 4*1024]). Now with this code I'm ok, it does what I want, but do I have a better (faster/compact) way to do this?

Upvotes: 1

Views: 806

Answers (1)

user4815162342
user4815162342

Reputation: 154911

do I have a better (faster/compact) way to do this?

Yes. std::fs::read is a convenience function that allocates a buffer and reads data into it, growing it as data arrives. Since you already possess a pre-allocated vector and want no resizing, you can use BufRead::read to read directly into it without unnecessary allocations. If your ROM size is fixed you can read the data with a single call to read_exact:

let mut file = BufReader::new(File::open(filepath)?);
file.read_exact(&mut self.memory[400..400 + ROM_SIZE])?;

This will avoid unnecessary allocation and copying. Of course, in many cases it won't make a difference in practice, but since your goal is to learn, it makes sense to be aware of the most efficient approach.

Upvotes: 5

Related Questions