Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write directly from a reader in Rust

Tags:

rust

How does one stream data from a reader to a write in Rust?

My end goal is actually to write out some gzipped data in a streaming fashion. It seems like what I am missing is a function to iterate over data from a reader and write it out to a file.

This task would be easy to accomplish with read_to_string, etc. But my requirement is to stream the data to keep memory usage down. I have not been able to find a simple way to do this that doesn't make lots of buffer allocations.

use std::io;
use std::io::prelude::*;
use std::io::{BufReader};
use std::fs::File;
use flate2::read::{GzEncoder};
use flate2::{Compression};

pub fn gzipped<R: Read>(file: String, stream: R) -> io::Result<()> {
    let file = File::create(file)?;
    let gz = BufReader::new(GzEncoder::new(stream, Compression::Default));
    read_write(gz, file)
}

pub fn read_write<R: BufRead, W: Write>(mut r: R, mut w: W) -> io::Result<()> {
  // ?
}
like image 334
Greg Weber Avatar asked Mar 01 '17 13:03

Greg Weber


People also ask

How do you write to a file in Rust?

Write to a FileThe create() method is used to create a file. The method returns a file handle if the file is created successfully. The last line write_all function will write bytes in newly created file. If any of the operations fail, the expect() function returns an error message.

What is a reader in Rust?

The Read trait allows for reading bytes from a source. Implementors of the Read trait are called 'readers'. Readers are defined by one required method, read() . Each call to read() will attempt to pull bytes from this source into a provided buffer.


1 Answers

Your read_write function sounds exactly like io::copy. So this would be

pub fn gzipped<R: Read>(file: String, stream: R) -> io::Result<u64> {
    let mut file = File::create(file)?;
    let mut gz = BufReader::new(GzEncoder::new(stream, Compression::Default));
    io::copy(&mut gz, &mut file)
}

The only difference is that io::copy takes mutable references, and returns Result<u64>.

like image 180
Chris Emerson Avatar answered Oct 16 '22 19:10

Chris Emerson