Skip to content

Commit a63ffbb

Browse files
committed
root: add rewriteFloatSm
1 parent f32db1a commit a63ffbb

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

src/io.zig

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,14 @@ pub fn writeFloat(writer: anytype, value: anytype) !usize {
9898
return wsize;
9999
}
100100

101+
pub fn writeFloatSm(writer: anytype, value: anytype) !usize {
102+
const T = @TypeOf(value);
103+
var buf: BufferForNumber(@TypeOf(value)) = undefined;
104+
const bsize = fmt.writeFloatSm(T, &buf, value);
105+
const wsize = try writer.write(buf[0..bsize]);
106+
return wsize;
107+
}
108+
101109
pub fn writeArrayPrefix(writer: anytype, length: u32) !usize {
102110
const prefix = fmt.prefixArray(length);
103111
const slice = prefix.constSlice();

src/rewriter.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ fn rewriteValue(
1414
.bool => _ = try zigpak.io.writeBool(writer, try values.bool(reader, h)),
1515
.int => _ = try zigpak.io.writeIntSm(writer, try values.int(reader, i64, h)),
1616
.uint => _ = try zigpak.io.writeIntSm(writer, try values.int(reader, u64, h)),
17-
.float => _ = try zigpak.io.writeFloat(writer, try values.float(reader, f64, h)),
17+
.float => _ = try zigpak.io.writeFloatSm(writer, try values.float(reader, f64, h)),
1818
.str => {
1919
var strReader = try values.rawReader(reader, h);
2020
var strbuf: [4096]u8 = undefined;

src/root.zig

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,20 @@ pub fn writeFloat(comptime T: type, dst: []u8, value: T) usize {
259259
return 1 + roundedBytes;
260260
}
261261

262+
/// Write the float as the smallest float type,
263+
/// as long as the precision won't lost.
264+
///
265+
/// This may introduce runtime check for certain input types.
266+
pub inline fn writeFloatSm(comptime T: type, dst: []u8, value: T) usize {
267+
const wontLosePrecision = @as(f32, @floatCast(value)) == value;
268+
269+
if (wontLosePrecision) {
270+
return writeFloat(f32, dst, @floatCast(value));
271+
} else {
272+
return writeFloat(f64, dst, @floatCast(value));
273+
}
274+
}
275+
262276
/// Write nil into the `dst`.
263277
pub fn writeNil(dst: []u8) usize {
264278
dst[0] = 0xc0;

0 commit comments

Comments
 (0)