std.json: josh review fixes

* renamed enum_big_numbers_quoted option to enum_nonportable_numbers_as_strings
* updated stringify doc to mention the option

I also reversed the logic to determine whether an integer is nonportable,
it seemed easier to reason about.

I also took a stab at applying the new option to floats, but, I got stuck
at trying to print large floats, not sure if Zig supports that yet.
This commit is contained in:
Jonathan Marler 2023-08-06 09:25:21 -06:00
parent 1cce539ddc
commit 2046880de8
2 changed files with 8 additions and 8 deletions

View File

@ -35,7 +35,7 @@ pub const StringifyOptions = struct {
escape_unicode: bool = false,
/// When true, renders numbers outside the range `+-1<<53` (the precise integer range of f64) as JSON strings in base 10.
emit_big_numbers_quoted: bool = false,
emit_nonportable_numbers_as_strings: bool = false,
};
/// Writes the given value to the `std.io.Writer` stream.
@ -164,7 +164,7 @@ pub fn writeStreamArbitraryDepth(
/// * Zig `bool` -> JSON `true` or `false`.
/// * Zig `?T` -> `null` or the rendering of `T`.
/// * Zig `i32`, `u64`, etc. -> JSON number or string.
/// * If the value is outside the range `+-1<<53` (the precise integer range of f64), it is rendered as a JSON string in base 10. Otherwise, it is rendered as JSON number.
/// * When option `emit_nonportable_numbers_as_strings` is true, if the value is outside the range `+-1<<53` (the precise integer range of f64), it is rendered as a JSON string in base 10. Otherwise, it is rendered as JSON number.
/// * Zig floats -> JSON number or string.
/// * If the value cannot be precisely represented by an f64, it is rendered as a JSON string. Otherwise, it is rendered as JSON number.
/// * TODO: Float rendering will likely change in the future, e.g. to remove the unnecessary "e+00".
@ -404,12 +404,12 @@ pub fn WriteStream(
switch (@typeInfo(T)) {
.Int => {
try self.valueStart();
if (!self.options.emit_big_numbers_quoted or
(value > -(1 << 53) and value < (1 << 53)))
if (self.options.emit_nonportable_numbers_as_strings and
(value <= -(1 << 53) or value >= (1 << 53)))
{
try self.stream.print("{}", .{value});
} else {
try self.stream.print("\"{}\"", .{value});
} else {
try self.stream.print("{}", .{value});
}
self.valueDone();
return;

View File

@ -434,7 +434,7 @@ test "print" {
try std.testing.expectEqualStrings(expected, result);
}
test "big integers" {
test "nonportable numbers" {
try testStringify("9999999999999999", 9999999999999999, .{});
try testStringify("\"9999999999999999\"", 9999999999999999, .{ .emit_big_numbers_quoted = true });
try testStringify("\"9999999999999999\"", 9999999999999999, .{ .emit_nonportable_numbers_as_strings = true });
}