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 {...@@ -1190,18 +1190,18 @@ pub fn lossyCast(comptime T: type, value: anytype) T {
1190 .Int => {1190 .Int => {
1191 switch (@typeInfo(@TypeOf(value))) {1191 switch (@typeInfo(@TypeOf(value))) {
1192 .Int, .ComptimeInt => {1192 .Int, .ComptimeInt => {
1193 if (value > maxInt(T)) {1193 if (value >= maxInt(T)) {
1194 return @as(T, maxInt(T));1194 return @as(T, maxInt(T));
1195 } else if (value < minInt(T)) {1195 } else if (value <= minInt(T)) {
1196 return @as(T, minInt(T));1196 return @as(T, minInt(T));
1197 } else {1197 } else {
1198 return @intCast(T, value);1198 return @intCast(T, value);
1199 }1199 }
1200 },1200 },
1201 .Float, .ComptimeFloat => {1201 .Float, .ComptimeFloat => {
1202 if (value > maxInt(T)) {1202 if (value >= maxInt(T)) {
1203 return @as(T, maxInt(T));1203 return @as(T, maxInt(T));
1204 } else if (value < minInt(T)) {1204 } else if (value <= minInt(T)) {
1205 return @as(T, minInt(T));1205 return @as(T, minInt(T));
1206 } else {1206 } else {
1207 return @floatToInt(T, value);1207 return @floatToInt(T, value);
...@@ -1218,6 +1218,7 @@ test "lossyCast" {...@@ -1218,6 +1218,7 @@ test "lossyCast" {
1218 try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));1218 try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
1219 try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));1219 try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
1220 try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));1220 try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
1221 try testing.expect(lossyCast(u32, @as(f32, maxInt(u32))) == maxInt(u32));
1221}1222}
12221223
1223test "f64_min" {1224test "f64_min" {