popcountdi2_test.zig (1046B) - Raw
1 const std = @import("std"); 2 const popcount = @import("popcount.zig"); 3 const testing = std.testing; 4 5 fn popcountdi2Naive(a: i64) i32 { 6 var x = a; 7 var r: i32 = 0; 8 while (x != 0) : (x = @as(i64, @bitCast(@as(u64, @bitCast(x)) >> 1))) { 9 r += @as(i32, @intCast(x & 1)); 10 } 11 return r; 12 } 13 14 fn test__popcountdi2(a: i64) !void { 15 const x = popcount.__popcountdi2(a); 16 const expected = popcountdi2Naive(a); 17 try testing.expectEqual(expected, x); 18 } 19 20 test "popcountdi2" { 21 try test__popcountdi2(0); 22 try test__popcountdi2(1); 23 try test__popcountdi2(2); 24 try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_fffffffd)))); 25 try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_fffffffe)))); 26 try test__popcountdi2(@as(i64, @bitCast(@as(u64, 0xffffffff_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(i64); 33 try test__popcountdi2(rand_num); 34 } 35 }