authorgravatar for hi@dnydxn.moealice <hi@dnydxn.moe> 2022-05-17 21:41:57+01:00
committergravatar for hi@dnydxn.moealice <hi@dnydxn.moe> 2022-05-17 21:41:57+01:00
logceeec8d19f36bf0a2cb132d35c0e119c4fec476d
tree840a3a71a31fbc0d2da658b0bcb2ac9c16616530
parentf3517a1aa6058e9b09d57e81ecc81f27f086d163
signaturelock-open Commit is signed but in an unrecognized format.

Simplify `signbit`


1 files changed, 12 insertions(+), 57 deletions(-)

lib/std/math/signbit.zig+12-57
......@@ -5,64 +5,19 @@ const expect = std.testing.expect;
55/// Returns whether x is negative or negative 0.
66pub fn signbit(x: anytype) bool {
77 const T = @TypeOf(x);
8 return switch (T) {
9 f16 => signbit16(x),
10 f32 => signbit32(x),
11 f64 => signbit64(x),
12 f80 => signbit80(x),
13 f128 => signbit128(x),
14 else => @compileError("signbit not implemented for " ++ @typeName(T)),
15 };
16}
17
18fn signbit16(x: f16) bool {
19 const bits = @bitCast(u16, x);
20 return bits >> 15 != 0;
21}
22
23fn signbit32(x: f32) bool {
24 const bits = @bitCast(u32, x);
25 return bits >> 31 != 0;
26}
27
28fn signbit64(x: f64) bool {
29 const bits = @bitCast(u64, x);
30 return bits >> 63 != 0;
31}
32
33fn signbit80(x: f80) bool {
34 const bits = @bitCast(u80, x);
35 return bits >> 79 != 0;
36}
37
38fn signbit128(x: f128) bool {
39 const bits = @bitCast(u128, x);
40 return bits >> 127 != 0;
8 const TBits = std.meta.Int(.unsigned, @typeInfo(T).Float.bits);
9 return @bitCast(TBits, x) >> (@bitSizeOf(T) - 1) != 0;
4110}
4211
4312test "math.signbit" {
44 try expect(signbit(@as(f16, 4.0)) == signbit16(4.0));
45 try expect(signbit(@as(f32, 4.0)) == signbit32(4.0));
46 try expect(signbit(@as(f64, 4.0)) == signbit64(4.0));
47 try expect(signbit(@as(f128, 4.0)) == signbit128(4.0));
48}
49
50test "math.signbit16" {
51 try expect(!signbit16(4.0));
52 try expect(signbit16(-3.0));
53}
54
55test "math.signbit32" {
56 try expect(!signbit32(4.0));
57 try expect(signbit32(-3.0));
58}
59
60test "math.signbit64" {
61 try expect(!signbit64(4.0));
62 try expect(signbit64(-3.0));
63}
64
65test "math.signbit128" {
66 try expect(!signbit128(4.0));
67 try expect(signbit128(-3.0));
13 inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
14 try expect(!signbit(@as(T, 0.0)));
15 try expect(!signbit(@as(T, 1.0)));
16 try expect(signbit(@as(T, -2.0)));
17 try expect(signbit(@as(T, -0.0)));
18 try expect(!signbit(math.inf(T)));
19 try expect(signbit(-math.inf(T)));
20 try expect(!signbit(math.nan(T)));
21 try expect(signbit(-math.nan(T)));
22 }
6823}