| 1 | const std = @import("std"); |
| 2 | const popcount = @import("popcount.zig"); |
| 3 | const testing = std.testing; |
| 4 | |
| 5 | fn popcountti2Naive(a: i128) i32 { |
| 6 | var x = a; |
| 7 | var r: i32 = 0; |
| 8 | while (x != 0) : (x = @as(i128, @bitCast(@as(u128, @bitCast(x)) >> 1))) { |
| 9 | r += @as(i32, @intCast(x & 1)); |
| 10 | } |
| 11 | return r; |
| 12 | } |
| 13 | |
| 14 | fn test__popcountti2(a: i128) !void { |
| 15 | const x = popcount.__popcountti2(a); |
| 16 | const expected = popcountti2Naive(a); |
| 17 | try testing.expectEqual(expected, x); |
| 18 | } |
| 19 | |
| 20 | test "popcountti2" { |
| 21 | try test__popcountti2(0); |
| 22 | try test__popcountti2(1); |
| 23 | try test__popcountti2(2); |
| 24 | try test__popcountti2(@as(i128, @bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_fffffffd)))); |
| 25 | try test__popcountti2(@as(i128, @bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_fffffffe)))); |
| 26 | try test__popcountti2(@as(i128, @bitCast(@as(u128, 0xffffffff_ffffffff_ffffffff_ffffffff)))); |
| 27 | |
| 28 | const RndGen = std.Random.DefaultPrng; |
| 29 | var rnd = RndGen.init(42); |
| 30 | var i: u32 = 0; |
| 31 | while (i < 10_000) : (i += 1) { |
| 32 | const rand_num = rnd.random().int(i128); |
| 33 | try test__popcountti2(rand_num); |
| 34 | } |
| 35 | } |