arithm_test.ha (2153B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use bytes; 5 6 @test fn add() void = { 7 let result: [4]u8 = [0...]; 8 9 let bx = fromhex("002132a0"); 10 defer free(bx); 11 let by = fromhex("00ff3201"); 12 defer free(by); 13 14 let carry = add(bx, by, 0); 15 16 assert(carry == 0); 17 18 decode(result, bx); 19 assert(bytes::equal([0x00, 0x21, 0x32, 0xa0], result)); 20 21 let carry = add(bx, by, 1); 22 23 assert(carry == 0); 24 decode(result, bx); 25 assert(bytes::equal([0x01, 0x20, 0x64, 0xa1], result)); 26 }; 27 28 @test fn muladd_small() void = { 29 const mod = fromhex("0100"); 30 defer free(mod); 31 let x = fromhex("0100"); 32 defer free(x); 33 34 muladd_small(x, 3, mod); 35 assert(equalshex(x, "03")); 36 37 const mod = fromhex("1000000000"); 38 defer free(mod); 39 let x = fromhexmod("0000000001", mod); 40 defer free(x); 41 muladd_small(x, 27, mod); 42 assert(equalshex(x, "8000001b")); 43 }; 44 45 @test fn mulacc() void = { 46 let d = fromhex("0000000000000000"); 47 defer free(d); 48 let a = fromhex("0010"); 49 defer free(a); 50 let b = fromhex("0014"); 51 defer free(b); 52 53 mulacc(d, a, b); 54 assert(equalshex(d, "0140")); 55 56 mulacc(d, a, b); 57 assert(equalshex(d, "0280")); 58 }; 59 60 @test fn rshift() void = { 61 let x = fromhex("1020304050"); 62 defer free(x); 63 rshift(x, 1); 64 assert(equalshex(x, "0810182028")); 65 66 let x = fromhex("00"); 67 defer free(x); 68 rshift(x, 1); 69 assert(equalshex(x, "")); 70 }; 71 72 @test fn reduce() void = { 73 let m = fromhex("87654321"); 74 defer free(m); 75 76 let a = fromhex("1234"); 77 defer free(a); 78 let x = fromhex("00000000"); 79 defer free(x); 80 reduce(x, a, m); 81 assert(equalshex(x, "1234")); 82 83 let a = fromhex("0123456789abcdef"); 84 defer free(a); 85 let x = fromhex("00000000"); 86 defer free(x); 87 reduce(x, a, m); 88 assert(equalshex(x, "14786ead")); 89 }; 90 91 @test fn modpow() void = { 92 let m = fromhex("87654321"); 93 defer free(m); 94 let x = fromhexmod("00f03202", m); 95 defer free(x); 96 97 let e: [_]u8 = [0x00, 0x00, 0xc1, 0xf4]; 98 const m0i = ninv31(m[1]); 99 100 let tmp: [10]word = [0...]; 101 modpow(x, e, m, m0i, tmp); 102 103 assert(equalshex(x, "3de073fc")); 104 105 let x = fromhexmod("00f03202", m); 106 defer free(x); 107 let tmp: [20]word = [0...]; 108 109 modpow(x, e, m, m0i, tmp); 110 assert(equalshex(x, "3de073fc")); 111 };