What is the correct way to read a binary file in chunks of a fixed size and store all of those chunks into a Vec?

Read::read_to_end reads efficiently directly into a Vec. If you want it in chunks, combine it with Read::take to limit the amount of bytes that read_to_end will read.

Example:

let mut file = std::fs::File::open("your_file")?;

let mut list_of_chunks = Vec::new();

let chunk_size = 0x4000;

loop {
    let mut chunk = Vec::with_capacity(chunk_size);
    let n = file.by_ref().take(chunk_size as u64).read_to_end(&mut chunk)?;
    if n == 0 { break; }
    list_of_chunks.push(chunk);
    if n < chunk_size { break; }
}

The last if is not necessary, but it prevents an extra read call: If less than the requested amount of bytes was read by read_to_end, we can expect the next read to read nothing, since we hit the end of the file.


I think the most idiomatic way would be to use an iterator. The code below (freely inspired by M-ou-se's answer):

  • Handles many use cases by using generic types
  • Will use a pre-allocated vector
  • Hides side effect
  • Avoid copying data twice
use std::io::{self, Read, Seek, SeekFrom};

struct Chunks<R> {
    read: R,
    size: usize,
    hint: (usize, Option<usize>),
}

impl<R> Chunks<R> {
    pub fn new(read: R, size: usize) -> Self {
        Self {
            read,
            size,
            hint: (0, None),
        }
    }

    pub fn from_seek(mut read: R, size: usize) -> io::Result<Self>
    where
        R: Seek,
    {
        let old_pos = read.seek(SeekFrom::Current(0))?;
        let len = read.seek(SeekFrom::End(0))?;

        let rest = (len - old_pos) as usize; // len is always >= old_pos but they are u64
        if rest != 0 {
            read.seek(SeekFrom::Start(old_pos))?;
        }

        let min = rest / size + if rest % size != 0 { 1 } else { 0 };
        Ok(Self {
            read,
            size,
            hint: (min, None), // this could be wrong I'm unsure
        })
    }

    // This could be useful if you want to try to recover from an error
    pub fn into_inner(self) -> R {
        self.read
    }
}

impl<R> Iterator for Chunks<R>
where
    R: Read,
{
    type Item = io::Result<Vec<u8>>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut chunk = Vec::with_capacity(self.size);
        match self
            .read
            .by_ref()
            .take(chunk.capacity() as u64)
            .read_to_end(&mut chunk)
        {
            Ok(n) => {
                if n != 0 {
                    Some(Ok(chunk))
                } else {
                    None
                }
            }
            Err(e) => Some(Err(e)),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.hint
    }
}

trait ReadPlus: Read {
    fn chunks(self, size: usize) -> Chunks<Self>
    where
        Self: Sized,
    {
        Chunks::new(self, size)
    }
}

impl<T: ?Sized> ReadPlus for T where T: Read {}

fn main() -> io::Result<()> {
    let file = std::fs::File::open("src/main.rs")?;
    let iter = Chunks::from_seek(file, 0xFF)?; // replace with anything 0xFF was to test

    println!("{:?}", iter.size_hint());
    // This iterator could return Err forever be careful collect it into an Result
    let chunks = iter.collect::<Result<Vec<_>, _>>()?;
    println!("{:?}, {:?}", chunks.len(), chunks.capacity());

    Ok(())
}

Tags:

Binary

File

Rust