2022-06-18 02:10:00 +01:00
|
|
|
//! parity - if number of bits set is even => 0, else => 1
|
|
|
|
//! - pariytXi2_generic for big and little endian
|
|
|
|
|
2021-12-01 10:27:40 +00:00
|
|
|
const std = @import("std");
|
|
|
|
const builtin = @import("builtin");
|
2022-06-18 02:10:00 +01:00
|
|
|
const common = @import("common.zig");
|
|
|
|
|
|
|
|
pub const panic = common.panic;
|
2022-06-10 09:25:59 +01:00
|
|
|
|
|
|
|
comptime {
|
2022-12-28 13:57:17 +00:00
|
|
|
@export(__paritysi2, .{ .name = "__paritysi2", .linkage = common.linkage, .visibility = common.visibility });
|
|
|
|
@export(__paritydi2, .{ .name = "__paritydi2", .linkage = common.linkage, .visibility = common.visibility });
|
|
|
|
@export(__parityti2, .{ .name = "__parityti2", .linkage = common.linkage, .visibility = common.visibility });
|
2022-06-10 09:25:59 +01:00
|
|
|
}
|
2021-12-01 10:27:40 +00:00
|
|
|
|
2022-06-18 02:10:00 +01:00
|
|
|
pub fn __paritysi2(a: i32) callconv(.C) i32 {
|
|
|
|
return parityXi2(i32, a);
|
|
|
|
}
|
2021-12-01 10:27:40 +00:00
|
|
|
|
2022-06-18 02:10:00 +01:00
|
|
|
pub fn __paritydi2(a: i64) callconv(.C) i32 {
|
|
|
|
return parityXi2(i64, a);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn __parityti2(a: i128) callconv(.C) i32 {
|
|
|
|
return parityXi2(i128, a);
|
|
|
|
}
|
2021-12-01 10:27:40 +00:00
|
|
|
|
2022-06-18 02:10:00 +01:00
|
|
|
inline fn parityXi2(comptime T: type, a: T) i32 {
|
2022-01-02 02:49:34 +00:00
|
|
|
var x = switch (@bitSizeOf(T)) {
|
2023-06-22 18:46:56 +01:00
|
|
|
32 => @as(u32, @bitCast(a)),
|
|
|
|
64 => @as(u64, @bitCast(a)),
|
|
|
|
128 => @as(u128, @bitCast(a)),
|
2022-01-02 02:49:34 +00:00
|
|
|
else => unreachable,
|
|
|
|
};
|
|
|
|
// Bit Twiddling Hacks: Compute parity in parallel
|
|
|
|
comptime var shift: u8 = @bitSizeOf(T) / 2;
|
|
|
|
inline while (shift > 2) {
|
|
|
|
x ^= x >> shift;
|
|
|
|
shift = shift >> 1;
|
|
|
|
}
|
|
|
|
x &= 0xf;
|
2023-06-22 18:46:56 +01:00
|
|
|
return (@as(u16, @intCast(0x6996)) >> @as(u4, @intCast(x))) & 1; // optimization for >>2 and >>1
|
2021-12-01 10:27:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
test {
|
|
|
|
_ = @import("paritysi2_test.zig");
|
|
|
|
_ = @import("paritydi2_test.zig");
|
|
|
|
_ = @import("parityti2_test.zig");
|
|
|
|
}
|