may icon indicating copy to clipboard operation
may copied to clipboard

What should I use instead of copy?

Open alanhoff opened this issue 6 years ago • 1 comments

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?

alanhoff avatar Jan 16 '18 11:01 alanhoff

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;
    }
}

Xudong-Huang avatar Jan 16 '18 14:01 Xudong-Huang