hare

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

utils.ha (1299B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use encoding::hex;
      5 
      6 // The caller must free the result.
      7 export fn fromhex(h: str) []word = {
      8 	let n: []u8 = hex::decodestr(h)!;
      9 	defer free(n);
     10 
     11 	let i: []word = alloc([0...], encodelen(n));
     12 	encode(i, n);
     13 	return i;
     14 };
     15 
     16 // 'h' must be lower than 'm'
     17 export fn fromhexmod(h: str, m: []word) []word = {
     18 	let r = fromhex(h);
     19 	r[0] = m[0];
     20 	return r;
     21 };
     22 
     23 // The caller must free the result.
     24 export fn tohex(x: []word) str = {
     25 	let buf: []u8 = alloc([0...], (len(x) - 1) * size(word));
     26 	defer free(buf);
     27 
     28 	decode(buf, x);
     29 
     30 	let i = 0z;
     31 	for (i < len(buf); i += 1) {
     32 		if (buf[i] != 0) {
     33 			break;
     34 		};
     35 	};
     36 
     37 	return hex::encodestr(buf[i..]);
     38 };
     39 
     40 export fn equalshex(x: []word, h: str) bool = {
     41 	let result = tohex(x);
     42 	defer free(result);
     43 	return result == h;
     44 };
     45 
     46 @test fn iszero() void = {
     47 	let x = fromhex("210032a0");
     48 	defer free(x);
     49 	let y = fromhex("00000000");
     50 	defer free(y);
     51 
     52 	assert(iszero(x) == 0);
     53 	assert(iszero(y) == 1);
     54 };
     55 
     56 @test fn zero() void = {
     57 	let w: [4]word = [0xffffffff...];
     58 
     59 	// set effective word len to 2 words.
     60 	const elen = countbits(w[1..3]);
     61 	w[0] = elen;
     62 
     63 	zero(w[..3], elen);
     64 
     65 	// check if zero does not overwrite more or less than elen
     66 	assert(w[0] == elen);
     67 	assert(w[3] == 0xffffffff);
     68 };