Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What should I use instead of copy? #25

Open
alanhoff opened this issue Jan 16, 2018 · 1 comment
Open

What should I use instead of copy? #25

alanhoff opened this issue Jan 16, 2018 · 1 comment
Labels

Comments

@alanhoff
Copy link
Contributor

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?

@Xudong-Huang
Copy link
Owner

Xudong-Huang commented Jan 16, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants