Created
July 27, 2016 06:48
-
-
Save ammojamo/1f0954c4e5b693e6315b6c689dd72543 to your computer and use it in GitHub Desktop.
Rust pipe from Read to Write
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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