Debian Codegraph @

hash/hash.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use io;
5 // TODO: Use a vtable-based approach for this like io::stream
6
7 // The general purpose interface for a hashing function.
8 export type hash = struct {
9 // A stream which only supports writes and never returns errors.
10 stream: io::stream,
11
12 // Returns the current hash.
13 sum: *fn(hash: *hash, buf: []u8) void,
14
15 // Resets the hash function to its initial state.
16 reset: nullable *fn(hash: *hash) void,
17
18 // Size of the hash in bytes.
19 sz: size,
20
21 // Internal block size of the hash. Writing data to the hash
22 // function in chunks of this size will not require padding to
23 // obtain the final hash.
24 bsz: size,
25 };
26
27 // Writes an input to the hash function.
28 export fn write(h: *hash, buf: const []u8) size =
29 io::write(h, buf) as size;
30
31 // Closes a hash, freeing its resources and discarding the checksum.
32 export fn close(h: *hash) void = io::close(h)!;
33
34 // Populates the user-provided buffer with the current sum.
35 export fn sum(h: *hash, buf: []u8) void = {
36 assert(len(buf) >= h.sz, "hash::sum buffer does not meet minimum required size for this hash function");
37 h.sum(h, buf);
38 };
39
40 // Resets the hash function to its initial state.
41 export fn reset(h: *hash) void = {
42 match (h.reset) {
43 case let f: *fn(hash: *hash) void =>
44 f(h);
45 case null =>
46 abort("this hash cannot be reset");
47 };
48 };
49
50 // Returns the size of the hash in bytes. This is consistent regardless
51 // of the hash state.
52 export fn sz(h: *hash) size = h.sz;
53
54 // Returns the block size of the hash.
55 export fn bsz(h: *hash) size = h.bsz;