diff options
| author | ominitay <37453713+ominitay@users.noreply.github.com> | 2022-03-10 19:53:28 +0000 |
|---|---|---|
| committer | Veikka Tuominen <git@vexu.eu> | 2022-03-12 10:23:57 +0200 |
| commit | 42d75f1a254653cbd4d441b300248c37d5f8d5a2 (patch) | |
| tree | 92bdfd7f377304e91b72fff0dd3785ae57528039 /lib/std/math.zig | |
| parent | b3259b47ad03592a156841c87e69421da05e37f3 (diff) | |
| download | zig-42d75f1a254653cbd4d441b300248c37d5f8d5a2.tar.gz zig-42d75f1a254653cbd4d441b300248c37d5f8d5a2.zip | |
std.math.lossyCast: fix integer overflow
Fixes integer overflow caused by cast from maxInt(u32) as an f32 to u32.
Diffstat (limited to 'lib/std/math.zig')
| -rw-r--r-- | lib/std/math.zig | 9 |
1 files 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" { |
