master
 1const std = @import("std");
 2const popcount = @import("popcount.zig");
 3const testing = std.testing;
 4
 5fn popcountsi2Naive(a: i32) i32 {
 6    var x = a;
 7    var r: i32 = 0;
 8    while (x != 0) : (x = @as(i32, @bitCast(@as(u32, @bitCast(x)) >> 1))) {
 9        r += @as(i32, @intCast(x & 1));
10    }
11    return r;
12}
13
14fn test__popcountsi2(a: i32) !void {
15    const x = popcount.__popcountsi2(a);
16    const expected = popcountsi2Naive(a);
17    try testing.expectEqual(expected, x);
18}
19
20test "popcountsi2" {
21    try test__popcountsi2(0);
22    try test__popcountsi2(1);
23    try test__popcountsi2(2);
24    try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xfffffffd))));
25    try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xfffffffe))));
26    try test__popcountsi2(@as(i32, @bitCast(@as(u32, 0xffffffff))));
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(i32);
33        try test__popcountsi2(rand_num);
34    }
35}