may
may copied to clipboard
What should I use instead of copy?
The caveats mention that one should not use copy
since it can easily blow up the stack size. What's the recommended method for passing bytes from one stream into another?
we can impl a copy fn simply like this
fn copy<R: Read, W: Write>(from: &mut R, to: &mut W) -> io::Result<u64> {
use std::io::ErrorKind;
// use buf from heap instead of stack
let mut buf = Vec::with_capacity(8192);
let mut written = 0;
loop {
let len = match from.read(&mut buf) {
Ok(0) => return Ok(written),
Ok(len) => len,
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
to.write_all(&buf[..len])?;
written += len as u64;
}
}