zig

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

paritydi2_test.zig (1016B) - Raw


      1 const std = @import("std");
      2 const parity = @import("parity.zig");
      3 const testing = std.testing;
      4 
      5 fn paritydi2Naive(a: i64) i32 {
      6     var x: u64 = @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__paritydi2(a: i64) !void {
     16     const x = parity.__paritydi2(a);
     17     const expected: i64 = paritydi2Naive(a);
     18     try testing.expectEqual(expected, x);
     19 }
     20 
     21 test "paritydi2" {
     22     try test__paritydi2(0);
     23     try test__paritydi2(1);
     24     try test__paritydi2(2);
     25     try test__paritydi2(@bitCast(@as(u64, 0xffffffff_fffffffd)));
     26     try test__paritydi2(@bitCast(@as(u64, 0xffffffff_fffffffe)));
     27     try test__paritydi2(@bitCast(@as(u64, 0xffffffff_ffffffff)));
     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(i64);
     34         try test__paritydi2(rand_num);
     35     }
     36 }