authorgravatar for gereeter+code@gmail.comJonathan S <gereeter+code@gmail.com> 2022-01-29 10:11:49-06:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-01-29 18:11:49+02:00
logaca665cebd2b6ec9ec3db669cf5446ee45bbb5d0
treed06c19e46393f5ec0ae7a700cf5eb2e3507fbf21
parentba445013c472abd874f7b041d9ad8f3c72197807
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Fix overflow in std.math.isNormal when applied to -Inf or a negative NaN


1 files changed, 16 insertions(+), 4 deletions(-)

lib/std/math/isnormal.zig+16-4
...@@ -9,19 +9,19 @@ pub fn isNormal(x: anytype) bool {...@@ -9,19 +9,19 @@ pub fn isNormal(x: anytype) bool {
9 switch (T) {9 switch (T) {
10 f16 => {10 f16 => {
11 const bits = @bitCast(u16, x);11 const bits = @bitCast(u16, x);
12 return (bits + (1 << 10)) & (maxInt(u16) >> 1) >= (1 << 11);12 return (bits +% (1 << 10)) & (maxInt(u16) >> 1) >= (1 << 11);
13 },13 },
14 f32 => {14 f32 => {
15 const bits = @bitCast(u32, x);15 const bits = @bitCast(u32, x);
16 return (bits + (1 << 23)) & (maxInt(u32) >> 1) >= (1 << 24);16 return (bits +% (1 << 23)) & (maxInt(u32) >> 1) >= (1 << 24);
17 },17 },
18 f64 => {18 f64 => {
19 const bits = @bitCast(u64, x);19 const bits = @bitCast(u64, x);
20 return (bits + (1 << 52)) & (maxInt(u64) >> 1) >= (1 << 53);20 return (bits +% (1 << 52)) & (maxInt(u64) >> 1) >= (1 << 53);
21 },21 },
22 f128 => {22 f128 => {
23 const bits = @bitCast(u128, x);23 const bits = @bitCast(u128, x);
24 return (bits + (1 << 112)) & (maxInt(u128) >> 1) >= (1 << 113);24 return (bits +% (1 << 112)) & (maxInt(u128) >> 1) >= (1 << 113);
25 },25 },
26 else => {26 else => {
27 @compileError("isNormal not implemented for " ++ @typeName(T));27 @compileError("isNormal not implemented for " ++ @typeName(T));
...@@ -34,6 +34,18 @@ test "math.isNormal" {...@@ -34,6 +34,18 @@ test "math.isNormal" {
34 try expect(!isNormal(math.nan(f32)));34 try expect(!isNormal(math.nan(f32)));
35 try expect(!isNormal(math.nan(f64)));35 try expect(!isNormal(math.nan(f64)));
36 try expect(!isNormal(math.nan(f128)));36 try expect(!isNormal(math.nan(f128)));
37 try expect(!isNormal(-math.nan(f16)));
38 try expect(!isNormal(-math.nan(f32)));
39 try expect(!isNormal(-math.nan(f64)));
40 try expect(!isNormal(-math.nan(f128)));
41 try expect(!isNormal(math.inf(f16)));
42 try expect(!isNormal(math.inf(f32)));
43 try expect(!isNormal(math.inf(f64)));
44 try expect(!isNormal(math.inf(f128)));
45 try expect(!isNormal(-math.inf(f16)));
46 try expect(!isNormal(-math.inf(f32)));
47 try expect(!isNormal(-math.inf(f64)));
48 try expect(!isNormal(-math.inf(f128)));
37 try expect(!isNormal(@as(f16, 0)));49 try expect(!isNormal(@as(f16, 0)));
38 try expect(!isNormal(@as(f32, 0)));50 try expect(!isNormal(@as(f32, 0)));
39 try expect(!isNormal(@as(f64, 0)));51 try expect(!isNormal(@as(f64, 0)));