addoti4_test.zig (2309B) - Raw
1 const addv = @import("addo.zig"); 2 const builtin = @import("builtin"); 3 const std = @import("std"); 4 const testing = std.testing; 5 const math = std.math; 6 7 fn test__addoti4(a: i128, b: i128) !void { 8 var result_ov: c_int = undefined; 9 var expected_ov: c_int = undefined; 10 const result = addv.__addoti4(a, b, &result_ov); 11 const expected: i128 = simple_addoti4(a, b, &expected_ov); 12 try testing.expectEqual(expected, result); 13 try testing.expectEqual(expected_ov, result_ov); 14 } 15 16 fn simple_addoti4(a: i128, b: i128, overflow: *c_int) i128 { 17 overflow.* = 0; 18 const min: i128 = math.minInt(i128); 19 const max: i128 = math.maxInt(i128); 20 if (((a > 0) and (b > max - a)) or 21 ((a < 0) and (b < min - a))) 22 overflow.* = 1; 23 return a +% b; 24 } 25 26 test "addoti4" { 27 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; 28 29 const min: i128 = math.minInt(i128); 30 const max: i128 = math.maxInt(i128); 31 var i: i128 = 1; 32 while (i < max) : (i *|= 2) { 33 try test__addoti4(i, i); 34 try test__addoti4(-i, -i); 35 try test__addoti4(i, -i); 36 try test__addoti4(-i, i); 37 } 38 39 // edge cases 40 // 0 + 0 = 0 41 // MIN + MIN overflow 42 // MAX + MAX overflow 43 // 0 + MIN MIN 44 // 0 + MAX MAX 45 // MIN + 0 MIN 46 // MAX + 0 MAX 47 // MIN + MAX -1 48 // MAX + MIN -1 49 try test__addoti4(0, 0); 50 try test__addoti4(min, min); 51 try test__addoti4(max, max); 52 try test__addoti4(0, min); 53 try test__addoti4(0, max); 54 try test__addoti4(min, 0); 55 try test__addoti4(max, 0); 56 try test__addoti4(min, max); 57 try test__addoti4(max, min); 58 59 // derived edge cases 60 // MIN+1 + MIN overflow 61 // MAX-1 + MAX overflow 62 // 1 + MIN = MIN+1 63 // -1 + MIN overflow 64 // -1 + MAX = MAX-1 65 // +1 + MAX overflow 66 // MIN + 1 = MIN+1 67 // MIN + -1 overflow 68 // MAX + 1 overflow 69 // MAX + -1 = MAX-1 70 try test__addoti4(min + 1, min); 71 try test__addoti4(max - 1, max); 72 try test__addoti4(1, min); 73 try test__addoti4(-1, min); 74 try test__addoti4(-1, max); 75 try test__addoti4(1, max); 76 try test__addoti4(min, 1); 77 try test__addoti4(min, -1); 78 try test__addoti4(max, -1); 79 try test__addoti4(max, 1); 80 }