Skip to content

Commit

Permalink
Rust: test copy reader-writer
Browse files Browse the repository at this point in the history
  • Loading branch information
ledongthuc committed Mar 15, 2023
1 parent c3de11b commit 9a5eacf
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rust/example_0003_copy_reader_to_writer/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions rust/example_0003_copy_reader_to_writer/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "example_0003_copy_reader_to_writer"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
21 changes: 21 additions & 0 deletions rust/example_0003_copy_reader_to_writer/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use std::io::{Read, Write, self, ErrorKind};

const DEFAULT_BUFFER_SIZE: usize = 8 * 1024;

pub fn copy<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W) -> io::Result<u64>
where R: Read, W: Write
{
let mut buf = [0; DEFAULT_BUFFER_SIZE];
let mut written = 0;

loop {
let len = match reader.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),
};
writer.write_all(&buf[..len])?;
written += len as u64;
}
}

0 comments on commit 9a5eacf

Please sign in to comment.