master
 1const std = @import("../std.zig");
 2const math = std.math;
 3const expect = std.testing.expect;
 4
 5/// Returns whether x is an infinity, ignoring sign.
 6pub inline fn isInf(x: anytype) bool {
 7    const T = @TypeOf(x);
 8    const TBits = std.meta.Int(.unsigned, @typeInfo(T).float.bits);
 9    const remove_sign = ~@as(TBits, 0) >> 1;
10    return @as(TBits, @bitCast(x)) & remove_sign == @as(TBits, @bitCast(math.inf(T)));
11}
12
13/// Returns whether x is an infinity with a positive sign.
14pub inline fn isPositiveInf(x: anytype) bool {
15    return x == math.inf(@TypeOf(x));
16}
17
18/// Returns whether x is an infinity with a negative sign.
19pub inline fn isNegativeInf(x: anytype) bool {
20    return x == -math.inf(@TypeOf(x));
21}
22
23test isInf {
24    inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
25        try expect(!isInf(@as(T, 0.0)));
26        try expect(!isInf(@as(T, -0.0)));
27        try expect(isInf(math.inf(T)));
28        try expect(isInf(-math.inf(T)));
29        try expect(!isInf(math.nan(T)));
30        try expect(!isInf(-math.nan(T)));
31    }
32}
33
34test isPositiveInf {
35    inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
36        try expect(!isPositiveInf(@as(T, 0.0)));
37        try expect(!isPositiveInf(@as(T, -0.0)));
38        try expect(isPositiveInf(math.inf(T)));
39        try expect(!isPositiveInf(-math.inf(T)));
40        try expect(!isInf(math.nan(T)));
41        try expect(!isInf(-math.nan(T)));
42    }
43}
44
45test isNegativeInf {
46    inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
47        try expect(!isNegativeInf(@as(T, 0.0)));
48        try expect(!isNegativeInf(@as(T, -0.0)));
49        try expect(!isNegativeInf(math.inf(T)));
50        try expect(isNegativeInf(-math.inf(T)));
51        try expect(!isInf(math.nan(T)));
52        try expect(!isInf(-math.nan(T)));
53    }
54}