File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // This example shows how to use io.cp, in combination with os.open and crypto.sha256,
2+ // to read and hash files chunk by chunk, without loading them completely in memory (which may
3+ // require too much RAM with big files).
4+ //
5+ // Usage: examples/sha256sum_with_io_cp [FILE]...
6+ //
7+ // Note: to compile the program, use:
8+ // `v -prod -cflags "-march=native -mtune=native" examples/sha256sum_with_io_cp.v`
9+ // After that, to compare it with say `sha256sum`, you can run:
10+ // `v repeat -R 5 "sha256sum v" "examples/sha256sum_with_io_cp v`
11+ import os
12+ import io
13+ import crypto.sha256
14+
15+ fn hash_file (path string ) ! string {
16+ mut file := os.open (path)!
17+ mut digest := sha256 .new ()
18+ io.cp (mut file, mut digest, buffer_size: 256 * 1024 )!
19+ file.close ()
20+ return digest.sum ([]).hex ()
21+ }
22+
23+ fn main () {
24+ for fpath in os.args#[1 ..] {
25+ h := hash_file (fpath)!
26+ println ('${h } ${fpath }' )
27+ }
28+ }
Original file line number Diff line number Diff line change 11module io
22
3- const buf_max_len = 1024
3+ // CopySettings provides additional options to io.cp
4+ @[params]
5+ pub struct CopySettings {
6+ pub mut :
7+ buffer_size int = 64 * 1024 // The buffer size used during the copying. A larger buffer is more performant, but uses more RAM.
8+ }
49
510// cp copies from `src` to `dst` by allocating
611// a maximum of 1024 bytes buffer for reading
712// until either EOF is reached on `src` or an error occurs.
813// An error is returned if an error is encountered during write.
9- pub fn cp (mut src Reader, mut dst Writer) ! {
10- mut buf := []u8 {len: buf_max_len}
11- for {
12- len := src.read (mut buf) or { break }
13- dst.write (buf[..len]) or { return err }
14+ @[manualfree]
15+ pub fn cp (mut src Reader, mut dst Writer, params CopySettings) ! {
16+ mut buf := []u8 {len: params.buffer_size}
17+ defer {
18+ unsafe {
19+ buf.free ()
20+ }
1421 }
15- unsafe {
16- buf.free ()
22+ for {
23+ bytes := src.read (mut buf) or { break }
24+ dst.write (buf[..bytes]) or { return err }
1725 }
1826}
You can’t perform that action at this time.
0 commit comments