Skip to content

Commit 0e229c2

Browse files
mstdokumacijinzhongjia
authored andcommitted
Improve writeFloat function for precision
Refactor writeFloat function to improve float encoding logic.
1 parent 73b174d commit 0e229c2

1 file changed

Lines changed: 5 additions & 6 deletions

File tree

src/msgpack.zig

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1819,12 +1819,11 @@ pub fn PackWithLimits(
18191819

18201820
/// write float
18211821
fn writeFloat(self: Self, val: f64) !void {
1822-
const tmp_val = if (val < 0) 0 - val else val;
1823-
const min_f32 = std.math.floatMin(f32);
1824-
const max_f32 = std.math.floatMax(f32);
1825-
1826-
if (tmp_val >= min_f32 and tmp_val <= max_f32) {
1827-
try self.writeF32(@floatCast(val));
1822+
// A value should only be encoded as f32 if it can be
1823+
// represented exactly without loss of precision.
1824+
const val_f32: f32 = @floatCast(val);
1825+
if (val == @as(f64, val_f32)) {
1826+
try self.writeF32(val_f32);
18281827
} else {
18291828
try self.writeF64(val);
18301829
}

0 commit comments

Comments
 (0)