hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

hash.ha (1661B)


      1 // License: MPL-2.0
      2 // (c) 2021 Armin Preiml <apreiml@strohwolke.at>
      3 // (c) 2021 Drew DeVault <sir@cmpwn.com>
      4 // (c) 2021 Kiƫd Llaentenn <kiedtl@tilde.team>
      5 use io;
      6 use fmt;
      7 // TODO: Use a vtable-based approach for this like io::stream
      8 
      9 // The general purpose interface for a hashing function.
     10 export type hash = struct {
     11 	// A stream which only supports writes and never returns errors.
     12 	stream: io::stream,
     13 
     14 	// Returns the current hash.
     15 	sum: *fn(hash: *hash, buf: []u8) void,
     16 
     17 	// Resets the hash function to its initial state.
     18 	reset: nullable *fn(hash: *hash) void,
     19 
     20 	// Size of the hash in bytes.
     21 	sz: size,
     22 
     23 	// Internal block size of the hash. Writing data to the hash
     24 	// function in chunks of this size will not require padding to
     25 	// obtain the final hash.
     26 	bsz: size,
     27 };
     28 
     29 // Writes an input to the hash function.
     30 export fn write(h: *hash, buf: const []u8) size =
     31 	io::write(h, buf) as size;
     32 
     33 // Closes a hash, freeing its resources and discarding the checksum.
     34 export fn close(h: *hash) void = io::close(h)!;
     35 
     36 // Populates the user-provided buffer with the current sum.
     37 export fn sum(h: *hash, buf: []u8) void = {
     38 	assert(len(buf) >= h.sz, "hash::sum buffer does not meet minimum required size for this hash function");
     39 	h.sum(h, buf);
     40 };
     41 
     42 // Resets the hash function to its initial state.
     43 export fn reset(h: *hash) void = match (h.reset) {
     44 case let f: *fn(hash: *hash) void =>
     45 	f(h);
     46 case null =>
     47 	abort("this hash cannot be reset");
     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;