Skip to content

Commit 741551c

Browse files
mstdokumacijinzhongjia
authored andcommitted
test(PackerIO): add test for large integer float precision to ensure correct encoding
1 parent 0e229c2 commit 741551c

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

src/test.zig

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,39 @@ test "float precision" {
11291129
}
11301130
}
11311131

1132+
// Test large integer stored as float without precision loss
1133+
// Demonstrates the fix: large numbers like 1774904202196 should be encoded as f64, not f32
1134+
test "large integer float precision (issue fix)" {
1135+
var arr: [0xffff_f]u8 = std.mem.zeroes([0xffff_f]u8);
1136+
var write_buffer = fixedBufferStream(&arr);
1137+
var read_buffer = fixedBufferStream(&arr);
1138+
var p = pack.init(&write_buffer, &read_buffer);
1139+
1140+
// Test large integer that cannot fit in f32 mantissa (24 bits)
1141+
// 1774904202196 requires 41 bits, so it will lose precision if encoded as f32
1142+
const large_int: f64 = 1774904202196.0;
1143+
1144+
try p.write(.{ .float = large_int });
1145+
1146+
// Verify it was encoded as f64 (marker 0xcb) not f32 (marker 0xca)
1147+
try expect(arr[0] == 0xcb); // Should use f64 format
1148+
1149+
// Read back and verify exact match (no truncation)
1150+
read_buffer = fixedBufferStream(&arr);
1151+
p = pack.init(&write_buffer, &read_buffer);
1152+
const val = try p.read(allocator);
1153+
defer val.free(allocator);
1154+
1155+
// Should preserve the exact value with f64 encoding
1156+
try expect(val.float == large_int);
1157+
1158+
// Additional test: verify f32 would lose precision
1159+
const large_f32: f32 = @floatCast(large_int);
1160+
const large_back_to_f64: f64 = @as(f64, large_f32);
1161+
// This demonstrates why we don't use f32: precision is lost
1162+
try expect(large_int != large_back_to_f64);
1163+
}
1164+
11321165
// Test payload utility methods
11331166
test "payload utility methods" {
11341167
// Test all ToPayload methods

0 commit comments

Comments
 (0)