Debian Codegraph @

debian/rust-vendor/blake3/c/example_tbb.c

raw
1 #include "blake3.h"
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <sys/mman.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9
10 int main(int argc, char **argv) {
11 // For each filepath argument, memory map it and hash it.
12 for (int i = 1; i < argc; i++) {
13 // Open and memory map the file.
14 int fd = open(argv[i], O_RDONLY);
15 if (fd == -1) {
16 fprintf(stderr, "open failed: %s\n", strerror(errno));
17 return 1;
18 }
19 struct stat statbuf;
20 if (fstat(fd, &statbuf) == -1) {
21 fprintf(stderr, "stat failed: %s\n", strerror(errno));
22 return 1;
23 }
24 void *mapped = mmap(NULL, statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
25 if (mapped == MAP_FAILED) {
26 fprintf(stderr, "mmap failed: %s\n", strerror(errno));
27 return 1;
28 }
29
30 // Initialize the hasher.
31 blake3_hasher hasher;
32 blake3_hasher_init(&hasher);
33
34 // Hash the mapped file using multiple threads.
35 blake3_hasher_update_tbb(&hasher, mapped, statbuf.st_size);
36
37 // Unmap and close the file.
38 if (munmap(mapped, statbuf.st_size) == -1) {
39 fprintf(stderr, "munmap failed: %s\n", strerror(errno));
40 return 1;
41 }
42 if (close(fd) == -1) {
43 fprintf(stderr, "close failed: %s\n", strerror(errno));
44 return 1;
45 }
46
47 // Finalize the hash. BLAKE3_OUT_LEN is the default output length, 32 bytes.
48 uint8_t output[BLAKE3_OUT_LEN];
49 blake3_hasher_finalize(&hasher, output, BLAKE3_OUT_LEN);
50
51 // Print the hash as hexadecimal.
52 for (size_t i = 0; i < BLAKE3_OUT_LEN; i++) {
53 printf("%02x", output[i]);
54 }
55 printf("\n");
56 }
57 }