| 1 | const std = @import("std"); |
| 2 | const parity = @import("parity.zig"); |
| 3 | const testing = std.testing; |
| 4 | |
| 5 | fn paritysi2Naive(a: i32) i32 { |
| 6 | var x: u32 = @bitCast(a); |
| 7 | var has_parity: bool = false; |
| 8 | while (x > 0) { |
| 9 | has_parity = !has_parity; |
| 10 | x = x & (x - 1); |
| 11 | } |
| 12 | return @intCast(@intFromBool(has_parity)); |
| 13 | } |
| 14 | |
| 15 | fn test__paritysi2(a: i32) !void { |
| 16 | const x = parity.__paritysi2(a); |
| 17 | const expected: i32 = paritysi2Naive(a); |
| 18 | try testing.expectEqual(expected, x); |
| 19 | } |
| 20 | |
| 21 | test "paritysi2" { |
| 22 | try test__paritysi2(0); |
| 23 | try test__paritysi2(1); |
| 24 | try test__paritysi2(2); |
| 25 | try test__paritysi2(@bitCast(@as(u32, 0xfffffffd))); |
| 26 | try test__paritysi2(@bitCast(@as(u32, 0xfffffffe))); |
| 27 | try test__paritysi2(@bitCast(@as(u32, 0xffffffff))); |
| 28 | |
| 29 | const RndGen = std.Random.DefaultPrng; |
| 30 | var rnd = RndGen.init(42); |
| 31 | var i: u32 = 0; |
| 32 | while (i < 10_000) : (i += 1) { |
| 33 | const rand_num = rnd.random().int(i32); |
| 34 | try test__paritysi2(rand_num); |
| 35 | } |
| 36 | } |