mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
55 lines
1.9 KiB
Zig
55 lines
1.9 KiB
Zig
const std = @import("../std.zig");
|
|
const math = std.math;
|
|
const expect = std.testing.expect;
|
|
|
|
/// Returns whether x is positive zero.
|
|
pub inline fn isPositiveZero(x: anytype) bool {
|
|
const T = @TypeOf(x);
|
|
const bit_count, const F = switch (@typeInfo(T)) {
|
|
.float => |float| .{ float.bits, T },
|
|
.comptime_float => .{ 128, f128 },
|
|
else => @compileError("unknown floating point type " ++ @typeName(T)),
|
|
};
|
|
const TBits = std.meta.Int(.unsigned, bit_count);
|
|
return @as(TBits, @bitCast(@as(F, x))) == @as(TBits, 0);
|
|
}
|
|
|
|
/// Returns whether x is negative zero.
|
|
pub inline fn isNegativeZero(x: anytype) bool {
|
|
const T = @TypeOf(x);
|
|
const bit_count, const F = switch (@typeInfo(T)) {
|
|
.float => |float| .{ float.bits, T },
|
|
.comptime_float => .{ 128, f128 },
|
|
else => @compileError("unknown floating point type " ++ @typeName(T)),
|
|
};
|
|
const TBits = std.meta.Int(.unsigned, bit_count);
|
|
return @as(TBits, @bitCast(@as(F, x))) == @as(TBits, 1) << (bit_count - 1);
|
|
}
|
|
|
|
test isPositiveZero {
|
|
inline for ([_]type{ f16, f32, f64, f80, f128, comptime_float }) |T| {
|
|
try expect(isPositiveZero(@as(T, 0.0)));
|
|
try expect(!isPositiveZero(@as(T, -0.0)));
|
|
try expect(!isPositiveZero(math.floatMin(T)));
|
|
try expect(!isPositiveZero(math.floatMax(T)));
|
|
|
|
if (T == comptime_float) return;
|
|
|
|
try expect(!isPositiveZero(math.inf(T)));
|
|
try expect(!isPositiveZero(-math.inf(T)));
|
|
}
|
|
}
|
|
|
|
test isNegativeZero {
|
|
inline for ([_]type{ f16, f32, f64, f80, f128, comptime_float }) |T| {
|
|
try expect(isNegativeZero(@as(T, -0.0)));
|
|
try expect(!isNegativeZero(@as(T, 0.0)));
|
|
try expect(!isNegativeZero(math.floatMin(T)));
|
|
try expect(!isNegativeZero(math.floatMax(T)));
|
|
|
|
if (T == comptime_float) return;
|
|
|
|
try expect(!isNegativeZero(math.inf(T)));
|
|
try expect(!isNegativeZero(-math.inf(T)));
|
|
}
|
|
}
|