1const builtin = @import("builtin");
2const std = @import("../std.zig");
3const math = std.math;
4const expect = std.testing.expect;
5
6/// Returns whether x is negative or negative 0.
7pub fn signbit(x: anytype) bool {
8 return switch (@typeInfo(@TypeOf(x))) {
9 .int, .comptime_int => x,
10 .float => |float| @as(@Int(.signed, float.bits), @bitCast(x)),
11 .comptime_float => @as(i128, @bitCast(@as(f128, x))), // any float type will do
12 else => @compileError("std.math.signbit does not support " ++ @typeName(@TypeOf(x))),
13 } < 0;
14}
15
16test signbit {
17 try testInts(u0);
18 try testInts(i1);
19 try testInts(u1);
20 try testInts(i2);
21 try testInts(u2);
22
23 try testFloats(f16);
24 try testFloats(f32);
25 try testFloats(f64);
26 try testFloats(f80);
27 try testFloats(f128);
28 try testFloats(c_longdouble);
29 try testFloats(comptime_float);
30}
31
32fn testInts(comptime Type: type) !void {
33 try expect((std.math.minInt(Type) < 0) == signbit(@as(Type, std.math.minInt(Type))));
34 try expect(!signbit(@as(Type, 0)));
35 try expect(!signbit(@as(Type, std.math.maxInt(Type))));
36}
37
38fn testFloats(comptime Type: type) !void {
39 try expect(!signbit(@as(Type, 0.0)));
40 try expect(!signbit(@as(Type, 1.0)));
41 try expect(signbit(@as(Type, -2.0)));
42 try expect(signbit(@as(Type, -0.0)));
43 try expect(!signbit(math.inf(Type)));
44 try expect(signbit(-math.inf(Type)));
45 try expect(!signbit(math.nan(Type)));
46 try expect(signbit(-math.nan(Type)));
47}