Skip to content

Instantly share code, notes, and snippets.

@ammojamo
Created July 27, 2016 06:48
Show Gist options
  • Save ammojamo/1f0954c4e5b693e6315b6c689dd72543 to your computer and use it in GitHub Desktop.
Save ammojamo/1f0954c4e5b693e6315b6c689dd72543 to your computer and use it in GitHub Desktop.
Rust pipe from Read to Write
use std::io::prelude::*;
// Feedback welcome
fn pipe(source: &mut Read, dest: &mut Write) -> std::io::Result<usize> {
let mut buf = [0; 512];
let mut bytes_read: usize = 0;
let mut bytes_written: usize = 0;
let mut total_bytes: usize = 0;
loop {
if bytes_read == 0 {
match source.read(&mut buf) {
Err(e) => return Err(e),
Ok(n) => {
if n == 0 {
break;
} else {
bytes_read = n;
}
}
}
}
if bytes_written < bytes_read {
match dest.write(&buf[bytes_written .. bytes_read]) {
Err(e) => return Err(e),
Ok(n) => {
bytes_written += n;
total_bytes += n;
}
}
}
if bytes_written == bytes_read {
bytes_read = 0;
bytes_written = 0;
}
}
return Ok(total_bytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment