code wiki / (root) / nx_u384_test.nx

nx_u384_test.nx source

↩ module page · 83 lines · 2424 B

1// nx_u384_test.nx -- KAT for the 384-bit big-int primitives. 2// 3// expect_exit: 0 4// license_tier: ORIGINAL 5 6import "nx_syscalls.nx" 7import "nx_u384.nx" 8 9func main() -> i64 { 10 // ---- Test A: zero / one ---- 11 let z: *i64 = u384_alloc() 12 u384_zero(z) 13 if u384_is_zero(z) != 1 { return 1 } 14 u384_one(z) 15 if z[0] != 1 { return 2 } 16 if u384_is_zero(z) != 0 { return 3 } 17 var i: i64 = 1 18 while i < NX_U384_LIMBS { 19 if z[i] != 0 { return 4 } 20 i = i + 1 21 } 22 23 // ---- Test B: load_be / store_be round-trip ---- 24 let pat: *u8 = sys_mmap(NX_U384_BYTES) 25 i = 0 26 while i < NX_U384_BYTES { 27 pat[i] = (i + 1) as u8 // 0x01..0x30 28 i = i + 1 29 } 30 let a: *i64 = u384_alloc() 31 u384_load_be(a, pat) 32 // High limb should hold bytes 0..3 BE = 0x01020304 33 if a[11] != 0x01020304 { return 10 } 34 // Low limb should hold bytes 44..47 BE = 0x2d2e2f30 35 if a[0] != 0x2d2e2f30 { return 11 } 36 37 let pat2: *u8 = sys_mmap(NX_U384_BYTES) 38 u384_store_be(pat2, a) 39 i = 0 40 while i < NX_U384_BYTES { 41 if (pat2[i] & 0xff) != (pat[i] & 0xff) { return 20 + i } 42 i = i + 1 43 } 44 45 // ---- Test C: add / sub round-trip ---- 46 // c = a + 1; d = c - 1; d == a 47 let one_v: *i64 = u384_alloc() 48 u384_one(one_v) 49 let c: *i64 = u384_alloc() 50 let carry: i64 = u384_add_with_carry(c, a, one_v) 51 if carry != 0 { return 50 } 52 let d: *i64 = u384_alloc() 53 let borrow: i64 = u384_sub_with_borrow(d, c, one_v) 54 if borrow != 0 { return 51 } 55 if u384_eq(d, a) != 1 { return 52 } 56 57 // ---- Test D: carry propagation across all 12 limbs ---- 58 // 0xFF..FF + 1 = 0 with carry-out 1 59 let all_ones: *i64 = u384_alloc() 60 i = 0 61 while i < NX_U384_LIMBS { 62 all_ones[i] = NX_U384_LIMB_MASK 63 i = i + 1 64 } 65 let e: *i64 = u384_alloc() 66 let carry2: i64 = u384_add_with_carry(e, all_ones, one_v) 67 if carry2 != 1 { return 60 } 68 if u384_is_zero(e) != 1 { return 61 } 69 70 // 0 - 1 = 0xFF..FF with borrow-out 1 71 let f: *i64 = u384_alloc() 72 let z2: *i64 = u384_alloc() 73 let borrow2: i64 = u384_sub_with_borrow(f, z2, one_v) 74 if borrow2 != 1 { return 70 } 75 if u384_eq(f, all_ones) != 1 { return 71 } 76 77 // ---- Test E: cmp ---- 78 if u384_cmp(z2, one_v) != 0 - 1 { return 80 } 79 if u384_cmp(one_v, z2) != 1 { return 81 } 80 if u384_cmp(one_v, one_v) != 0 { return 82 } 81 82 return 0 83}