authorgravatar for 37453713+ominitay@users.noreply.github.comominitay <37453713+ominitay@users.noreply.github.com> 2022-03-10 19:53:28+00:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2022-03-12 10:23:57+02:00
log42d75f1a254653cbd4d441b300248c37d5f8d5a2
tree92bdfd7f377304e91b72fff0dd3785ae57528039
parentb3259b47ad03592a156841c87e69421da05e37f3

std.math.lossyCast: fix integer overflow

Fixes integer overflow caused by cast from maxInt(u32) as an f32 to u32.

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

lib/std/math.zig+5-4
......@@ -1190,18 +1190,18 @@ pub fn lossyCast(comptime T: type, value: anytype) T {
11901190 .Int => {
11911191 switch (@typeInfo(@TypeOf(value))) {
11921192 .Int, .ComptimeInt => {
1193 if (value > maxInt(T)) {
1193 if (value >= maxInt(T)) {
11941194 return @as(T, maxInt(T));
1195 } else if (value < minInt(T)) {
1195 } else if (value <= minInt(T)) {
11961196 return @as(T, minInt(T));
11971197 } else {
11981198 return @intCast(T, value);
11991199 }
12001200 },
12011201 .Float, .ComptimeFloat => {
1202 if (value > maxInt(T)) {
1202 if (value >= maxInt(T)) {
12031203 return @as(T, maxInt(T));
1204 } else if (value < minInt(T)) {
1204 } else if (value <= minInt(T)) {
12051205 return @as(T, minInt(T));
12061206 } else {
12071207 return @floatToInt(T, value);
......@@ -1218,6 +1218,7 @@ test "lossyCast" {
12181218 try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
12191219 try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
12201220 try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
1221 try testing.expect(lossyCast(u32, @as(f32, maxInt(u32))) == maxInt(u32));
12211222}
12221223
12231224test "f64_min" {