zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

popcountsi2_test.zig (1019B) - Raw


      1 const std = @import("std");
      2 const popcount = @import("popcount.zig");
      3 const testing = std.testing;
      4 
      5 fn 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 
     14 fn test__popcountsi2(a: i32) !void {
     15     const x = popcount.__popcountsi2(a);
     16     const expected = popcountsi2Naive(a);
     17     try testing.expectEqual(expected, x);
     18 }
     19 
     20 test "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 }