Skip to content

Commit e7604bb

Browse files
committed
Serialize float options using the hexadecimal format
This ensures no information is lost when the value is round-tripped.
1 parent 5380e81 commit e7604bb

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

lib/std/Build.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ fn addUserInputOptionFromArg(
507507
.comptime_float, .float => return if (maybe_value) |v| {
508508
map.put(field.name, .{
509509
.name = field.name,
510-
.value = .{ .scalar = std.fmt.allocPrint(arena, "{e}", .{v}) catch @panic("OOM") },
510+
.value = .{ .scalar = std.fmt.allocPrint(arena, "{x}", .{v}) catch @panic("OOM") },
511511
.used = false,
512512
}) catch @panic("OOM");
513513
},

lib/std/Io/Writer.zig

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1563,17 +1563,23 @@ pub fn printFloatHexOptions(w: *Writer, value: anytype, options: std.fmt.Number)
15631563
}
15641564

15651565
pub fn printFloatHex(w: *Writer, value: anytype, case: std.fmt.Case, opt_precision: ?usize) Error!void {
1566-
if (std.math.signbit(value)) try w.writeByte('-');
1567-
if (std.math.isNan(value)) return w.writeAll(switch (case) {
1566+
const v = switch (@TypeOf(value)) {
1567+
// comptime_float internally is a f128; this preserves precision.
1568+
comptime_float => @as(f128, value),
1569+
else => value,
1570+
};
1571+
1572+
if (std.math.signbit(v)) try w.writeByte('-');
1573+
if (std.math.isNan(v)) return w.writeAll(switch (case) {
15681574
.lower => "nan",
15691575
.upper => "NAN",
15701576
});
1571-
if (std.math.isInf(value)) return w.writeAll(switch (case) {
1577+
if (std.math.isInf(v)) return w.writeAll(switch (case) {
15721578
.lower => "inf",
15731579
.upper => "INF",
15741580
});
15751581

1576-
const T = @TypeOf(value);
1582+
const T = @TypeOf(v);
15771583
const TU = std.meta.Int(.unsigned, @bitSizeOf(T));
15781584

15791585
const mantissa_bits = std.math.floatMantissaBits(T);
@@ -1583,7 +1589,7 @@ pub fn printFloatHex(w: *Writer, value: anytype, case: std.fmt.Case, opt_precisi
15831589
const exponent_mask = (1 << exponent_bits) - 1;
15841590
const exponent_bias = (1 << (exponent_bits - 1)) - 1;
15851591

1586-
const as_bits: TU = @bitCast(value);
1592+
const as_bits: TU = @bitCast(v);
15871593
var mantissa = as_bits & mantissa_mask;
15881594
var exponent: i32 = @as(u16, @truncate((as_bits >> mantissa_bits) & exponent_mask));
15891595

0 commit comments

Comments
 (0)