hash.ha (1574B)
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 = match (h.reset) { 42 case let f: *fn(hash: *hash) void => 43 f(h); 44 case null => 45 abort("this hash cannot be reset"); 46 }; 47 48 // Returns the size of the hash in bytes. This is consistent regardless 49 // of the hash state. 50 export fn sz(h: *hash) size = h.sz; 51 52 // Returns the block size of the hash. 53 export fn bsz(h: *hash) size = h.bsz;