diff options
| author | mlugg <mlugg@mlugg.co.uk> | 2025-07-31 10:56:49 +0100 |
|---|---|---|
| committer | mlugg <mlugg@mlugg.co.uk> | 2025-07-31 10:57:04 +0100 |
| commit | 64bf8bb146099b51d74635a1f116a913e442bcf4 (patch) | |
| tree | 2f9cba090e0fdea54b9bffdbd76e5c729756464d /lib/std/math.zig | |
| parent | e664bf4d81e9266ee4749b5da88cab4554499bf6 (diff) | |
| download | zig-64bf8bb146099b51d74635a1f116a913e442bcf4.tar.gz zig-64bf8bb146099b51d74635a1f116a913e442bcf4.zip | |
std: stop relying on precision-losing coercions
Diffstat (limited to 'lib/std/math.zig')
| -rw-r--r-- | lib/std/math.zig | 10 |
1 files changed, 7 insertions, 3 deletions
diff --git a/lib/std/math.zig b/lib/std/math.zig index 9f2d12a65e..c36f19ec85 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -1345,11 +1345,15 @@ pub fn lossyCast(comptime T: type, value: anytype) T { } }, .float, .comptime_float => { + // In extreme cases, we probably need a language enhancement to be able to + // specify a rounding mode here to prevent `@intFromFloat` panics. + const max: @TypeOf(value) = @floatFromInt(maxInt(T)); + const min: @TypeOf(value) = @floatFromInt(minInt(T)); if (isNan(value)) { return 0; - } else if (value >= maxInt(T)) { + } else if (value >= max) { return maxInt(T); - } else if (value <= minInt(T)) { + } else if (value <= min) { return minInt(T); } else { return @intFromFloat(value); @@ -1366,7 +1370,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)); + try testing.expect(lossyCast(u32, @as(f32, @floatFromInt(maxInt(u32)))) == maxInt(u32)); try testing.expect(lossyCast(u32, nan(f32)) == 0); } |
