SHARE
TWEET

Untitled

a guest Sep 15th, 2019 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::fs::File;
  2. use std::io::prelude::*;
  3. use std::io::ErrorKind;
  4. use std::io::Result;
  5. use std::time::Instant;
  6.  
  7. fn main() {
  8.     let now = Instant::now();
  9.     copy_n_bytes(
  10.         "/path/to/big/file",
  11.         "path/to/target/file",
  12.         std::usize::MAX,
  13.         1 << 5,
  14.     )
  15.     .unwrap();
  16.     println!("Time elapsed: {}ms", now.elapsed().as_millis());
  17. }
  18.  
  19. fn copy_n_bytes(source: &str, dest: &str, n: usize, cache: usize) -> Result<()> {
  20.     let mut src = File::open(source)?;
  21.     let mut dst = File::create(dest)?;
  22.  
  23.     let mut buf = vec![0; cache];
  24.     let mut bytes_read: usize = 0;
  25.     let mut k;
  26.  
  27.     while bytes_read < n {
  28.         match src.read(&mut buf) {
  29.             Ok(n) => {
  30.                 k = n;
  31.             }
  32.             Err(e) => match e.kind() {
  33.                 ErrorKind::Interrupted => {
  34.                     continue;
  35.                 }
  36.                 _ => {
  37.                     eprintln!("Error {:?}", e);
  38.                     return Err(e);
  39.                 }
  40.             },
  41.         }
  42.         if k == 0 {
  43.             println!("EOF reached");
  44.             break;
  45.         }
  46.         dst.write_all(&buf[..k])?;
  47.         bytes_read += k;
  48.     }
  49.  
  50.     Ok(())
  51. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top