| 1 | const std = @import("../std.zig"); |
| 2 | const builtin = @import("builtin"); |
| 3 | const math = std.math; |
| 4 | const expect = std.testing.expect; |
| 5 | |
| 6 | pub fn isNan(x: anytype) bool { |
| 7 | return x != x; |
| 8 | } |
| 9 | |
| 10 | /// TODO: LLVM is known to miscompile on some architectures to quiet NaN - |
| 11 | /// this is tracked by https://github.com/ziglang/zig/issues/14366 |
| 12 | pub fn isSignalNan(x: anytype) bool { |
| 13 | const T = @TypeOf(x); |
| 14 | const U = @Int(.unsigned, @bitSizeOf(T)); |
| 15 | const quiet_signal_bit_mask = 1 << (math.floatFractionalBits(T) - 1); |
| 16 | return isNan(x) and (@as(U, @bitCast(x)) & quiet_signal_bit_mask == 0); |
| 17 | } |
| 18 | |
| 19 | test isNan { |
| 20 | inline for ([_]type{ f16, f32, f64, f80, f128, c_longdouble }) |T| { |
| 21 | try expect(isNan(math.nan(T))); |
| 22 | try expect(isNan(-math.nan(T))); |
| 23 | try expect(isNan(math.snan(T))); |
| 24 | try expect(!isNan(@as(T, 1.0))); |
| 25 | try expect(!isNan(@as(T, math.inf(T)))); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | test isSignalNan { |
| 30 | inline for ([_]type{ f16, f32, f64, f80, f128, c_longdouble }) |T| { |
| 31 | // TODO: Signalling NaN values get converted to quiet NaN values in |
| 32 | // some cases where they shouldn't such that this can fail. |
| 33 | // See https://github.com/ziglang/zig/issues/14366 |
| 34 | if (!builtin.cpu.arch.isArm() and |
| 35 | !builtin.cpu.arch.isAARCH64() and |
| 36 | builtin.cpu.arch != .hexagon and |
| 37 | !builtin.cpu.arch.isMIPS32() and |
| 38 | !builtin.cpu.arch.isPowerPC() and |
| 39 | !(builtin.cpu.arch.isX86() and builtin.os.tag == .windows and builtin.abi == .msvc) and // https://codeberg.org/ziglang/zig/issues/35519 |
| 40 | builtin.zig_backend != .stage2_c) |
| 41 | { |
| 42 | try expect(isSignalNan(math.snan(T))); |
| 43 | } |
| 44 | try expect(!isSignalNan(math.nan(T))); |
| 45 | try expect(!isSignalNan(@as(T, 1.0))); |
| 46 | try expect(!isSignalNan(math.inf(T))); |
| 47 | } |
| 48 | } |