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