From 42d75f1a254653cbd4d441b300248c37d5f8d5a2 Mon Sep 17 00:00:00 2001 From: ominitay <37453713+ominitay@users.noreply.github.com> Date: Thu, 10 Mar 2022 19:53:28 +0000 Subject: [PATCH] std.math.lossyCast: fix integer overflow Fixes integer overflow caused by cast from maxInt(u32) as an f32 to u32. --- lib/std/math.zig | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/std/math.zig b/lib/std/math.zig index c91feb5713..08019835f7 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -1190,18 +1190,18 @@ pub fn lossyCast(comptime T: type, value: anytype) T { .Int => { switch (@typeInfo(@TypeOf(value))) { .Int, .ComptimeInt => { - if (value > maxInt(T)) { + if (value >= maxInt(T)) { return @as(T, maxInt(T)); - } else if (value < minInt(T)) { + } else if (value <= minInt(T)) { return @as(T, minInt(T)); } else { return @intCast(T, value); } }, .Float, .ComptimeFloat => { - if (value > maxInt(T)) { + if (value >= maxInt(T)) { return @as(T, maxInt(T)); - } else if (value < minInt(T)) { + } else if (value <= minInt(T)) { return @as(T, minInt(T)); } else { return @floatToInt(T, value); @@ -1218,6 +1218,7 @@ test "lossyCast" { try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767)); try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0)); try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200)); + try testing.expect(lossyCast(u32, @as(f32, maxInt(u32))) == maxInt(u32)); } test "f64_min" {