Compare commits

..
Author SHA1 Message Date
Niels Lohmann 12a1ca5846 Write floats with the shortest digits (Zmij for binary32)
The conversion of Zmij becomes a template on the bit layout of the format,
as upstream Zmij does, and floats (IEEE 754 binary32) use it instead of
Grisu2. The layout of the text (format_buffer()) stays the same; only the
digits change, for 8,821,575 of the 2,139,095,039 positive finite floats:
4,627,275 get one digit fewer (Grisu2 leaves out decimals on the boundary of
the rounding interval), and 4,194,300 take the even one of two equally close
decimals. Every float still reads back as itself. The conversion of doubles
compiles to the same code as before.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-25 22:45:26 +01:00
15 changed files with 346 additions and 254 deletions

No files matched your search

-3
View File
@@ -34,9 +34,6 @@ For products, applications, and organizations that use the library, see [Custome
## Format converters ## Format converters
For the formats related to JSON that the library reads itself, such as JSONC or JSON Lines, see
[JSON variants](../features/parsing/json_variants.md).
- [**tojson**](https://github.com/mircodz/tojson), a header-only converter between YAML/XML documents and - [**tojson**](https://github.com/mircodz/tojson), a header-only converter between YAML/XML documents and
`nlohmann::json` `nlohmann::json`
- [**json2xml**](https://github.com/testillano/json2xml), a header-only converter from `nlohmann::json` to XML for - [**json2xml**](https://github.com/testillano/json2xml), a header-only converter from `nlohmann::json` to XML for
+1 -3
View File
@@ -11,8 +11,7 @@ This library does not support comments *by default*. It does so for three reason
3. It is dangerous for interoperability if some libraries add comment support while others do not. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this. 3. It is dangerous for interoperability if some libraries add comment support while others do not. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this.
However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support. See [JSON variants](parsing/json_variants.md) for a However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support.
comparison with these and other formats.
For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html). For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html).
@@ -44,6 +43,5 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Trailing Commas](trailing_commas.md) - accept trailing commas in arrays and objects - [Trailing Commas](trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions - [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control - [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
-2
View File
@@ -18,8 +18,6 @@ C++ types, and finally serialize it again.
- [Editable documents](json_view/editing.md) — modify a parsed document without building a `json` tree. - [Editable documents](json_view/editing.md) — modify a parsed document without building a `json` tree.
- [Images](json_view/images.md) — save a parsed document and load it again without parsing it. - [Images](json_view/images.md) — save a parsed document and load it again without parsing it.
- [Comments](comments.md) and [trailing commas](trailing_commas.md) — opt-in relaxations of the JSON grammar. - [Comments](comments.md) and [trailing commas](trailing_commas.md) — opt-in relaxations of the JSON grammar.
- [JSON variants](parsing/json_variants.md) — which of JSONC, JSON5, JSON Lines, I-JSON, and other formats related to
JSON the library supports.
## Accessing and modifying values ## Accessing and modifying values
+1 -3
View File
@@ -45,8 +45,7 @@ that arrives in chunks or contains several values is covered in
[Large, streamed, and partial input](large_and_partial_input.md). [Large, streamed, and partial input](large_and_partial_input.md).
By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the `parse` By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the `parse`
function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md). See function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md).
[JSON variants](json_variants.md) for how much of JSONC, JSON5, and other formats related to JSON the library supports.
[`basic_json_document::parse`](../../api/basic_json_document/parse.md) accepts the same inputs with the same options, [`basic_json_document::parse`](../../api/basic_json_document/parse.md) accepts the same inputs with the same options,
but keeps the result in a document rather than in a `basic_json` value; see but keeps the result in a document rather than in a `basic_json` value; see
@@ -170,7 +169,6 @@ options.
- [`accept`](../../api/basic_json/accept.md) - check if the input is valid JSON - [`accept`](../../api/basic_json/accept.md) - check if the input is valid JSON
- [`sax_parse`](../../api/basic_json/sax_parse.md) - generate SAX events - [`sax_parse`](../../api/basic_json/sax_parse.md) - generate SAX events
- [JSON Lines](json_lines.md) - parse newline-delimited JSON - [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [JSON variants](json_variants.md) - JSONC, JSON5, JSON text sequences, I-JSON, and other formats related to JSON
- [Large, streamed, and partial input](large_and_partial_input.md) - chunked, concatenated, and very large input - [Large, streamed, and partial input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [parser callbacks](parser_callbacks.md) - influence the parsing by a callback function - [parser callbacks](parser_callbacks.md) - influence the parsing by a callback function
- [SAX interface](sax_interface.md) - implement a custom SAX handler - [SAX interface](sax_interface.md) - implement a custom SAX handler
@@ -68,6 +68,5 @@ JSON Lines input with more than one value is treated as invalid JSON by the [`pa
- [Parsing](index.md) - overview of the parsing functions - [Parsing](index.md) - overview of the parsing functions
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input - [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [JSON variants](json_variants.md) - NDJSON, JSON text sequences, and other formats related to JSON
- [`parse`](../../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../../api/basic_json/parse.md) - deserialize from a compatible input
- [`operator>>`](../../api/operator_gtgt.md) - deserialize from stream - [`operator>>`](../../api/operator_gtgt.md) - deserialize from stream
@@ -1,185 +0,0 @@
# JSON Variants
This library reads and writes JSON as defined by [RFC 8259](https://tools.ietf.org/html/rfc8259) and
[ECMA-404](https://ecma-international.org/publications-and-standards/standards/ecma-404/). Many other formats are
built around JSON: some relax its syntax (for example, to allow comments), some put several JSON values into one
stream, some restrict it further, and some give certain JSON values a special meaning. This page lists the common
ones and how much of each the library supports.
## Overview
| Variant | Kind | Support |
|------------------------------------------------------------------|----------------------------|-----------------------------------------------------------------------------------------------------------|
| [JSON](https://tools.ietf.org/html/rfc8259) (RFC 8259, ECMA-404) | the standard | :white_check_mark: default |
| [JSONC](https://jsonc.org) | relaxed syntax | :white_check_mark: with `ignore_comments` (and `ignore_trailing_commas` where trailing commas are wanted) |
| [JWCC](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html) / [HuJSON](https://github.com/tailscale/hujson) | relaxed syntax | :white_check_mark: with `ignore_comments` and `ignore_trailing_commas` |
| [JSON5](https://spec.json5.org) | relaxed syntax | :warning: comments and trailing commas only |
| [Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md), [UCL](https://github.com/vstakhov/libucl), SJSON | configuration languages | :x: only input that is JSON plus `//`/`/* */` comments and trailing commas |
| [YAML](https://yaml.org), [Amazon Ion](https://amazon-ion.github.io/ion-docs/) | other languages | :x: see [converters](#other-languages-and-converters) |
| [JSON Lines](https://jsonlines.org), [NDJSON](https://github.com/ndjson/ndjson-spec) | several values | :white_check_mark: line by line, see [JSON Lines](json_lines.md) |
| concatenated JSON | several values | :white_check_mark: with `operator>>`, see [Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream) |
| [JSON text sequences](https://www.rfc-editor.org/rfc/rfc7464) (RFC 7464) | several values | :warning: split the input yourself, see [below](#json-text-sequences-rfc-7464) |
| [I-JSON](https://www.rfc-editor.org/rfc/rfc7493) (RFC 7493) | restricted profile | :warning: most rules are enforced, see [below](#i-json-rfc-7493) |
| [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (RFC 8785) | restricted output | :x: `dump()` output is close, but not canonical |
| `NaN`, `Infinity` (JavaScript, Python) | number extension | :x: rejected by the parser, written as `null` |
| [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org), [GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), [MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) | conventions on top of JSON | :white_check_mark: parsed as plain JSON; interpreting them is up to you |
Whatever was parsed, [`dump`](../../api/basic_json/dump.md) always writes standard JSON: no comments, no trailing
commas, and no `NaN` or `Infinity`.
## Standard JSON
By default, [`parse`](../../api/basic_json/parse.md) accepts exactly the JSON grammar of RFC 8259, including values
other than objects and arrays at the top level (such as `#!json 42` or `#!json "text"`). A UTF-8 byte order mark at the
very start of the input is skipped; anywhere else it is a parse error.
## Relaxed syntax
### JSONC and JWCC
**JSONC** ("JSON with comments", used, for example, by Visual Studio Code's `settings.json` and `devcontainer.json`)
adds `//` and `/* */` comments to JSON. Block comments do not nest. The [JSONC specification](https://jsonc.org) lets
parsers decide whether they accept trailing commas. **JWCC** ("JSON with commas and comments") adds the same comments
and always allows a single trailing comma in arrays and objects; [HuJSON](https://github.com/tailscale/hujson) is
Tailscale's implementation of it.
Both are fully supported by passing `ignore_comments` and `ignore_trailing_commas` to `parse`:
```cpp
json j = json::parse(input,
/* callback */ nullptr,
/* allow_exceptions */ true,
/* ignore_comments */ true,
/* ignore_trailing_commas */ true);
```
Comments are treated as whitespace and are not kept, so they are lost when the value is written again. This also holds
for a [`json_document`](../../api/basic_json_document/index.md): [`dump()`](../../api/basic_json_view/dump.md) of its
root view writes the same text as `dump()` of the parsed `json` value, even though the document keeps the source text
with the comments. See
[Comments](../comments.md) and [Trailing commas](../trailing_commas.md) for the details. The .NET options
`JsonCommentHandling.Skip` and `AllowTrailingCommas` accept the same syntax.
### JSON5
[JSON5](https://spec.json5.org) is a superset of JSON that follows the syntax of ECMAScript 5 object literals. Besides
comments and trailing commas, it allows unquoted keys, single-quoted strings, line continuations in strings, more
escape sequences (`\v`, `\0`, `\xHH`, ...), hexadecimal numbers, a leading `+`, a leading or trailing decimal point, and
`Infinity` and `NaN`. With the two options above, the library accepts JSON5 documents that only use comments and
trailing commas; using any of the other extensions is a parse error.
### Configuration languages
[Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md),
[UCL](https://github.com/vstakhov/libucl), and SJSON (from the Bitsquid/Stingray game engine) are configuration
languages that accept JSON but go much further: `#` comments, unquoted keys and values, `=` instead of `:`, optional
commas and braces, multiline strings, and, in HOCON and UCL, includes and variable substitutions. The library does not
support these extensions. A `#` comment in particular is always a parse error, even with `ignore_comments`.
### Other languages and converters
[YAML](https://yaml.org) and the text format of [Amazon Ion](https://amazon-ion.github.io/ion-docs/) are separate
languages with their own data models, and the library does not read them. The [Ecosystem](../../community/ecosystem.md)
page lists projects that convert YAML or XML to and from `nlohmann::json`.
## Several values in one input
`parse` reads exactly one value and reports anything after it as an error. Several common formats combine many values
into one input:
- **[JSON Lines](https://jsonlines.org)** and **[NDJSON](https://github.com/ndjson/ndjson-spec)** put one value on each
line. Read them line by line, as shown on the [JSON Lines](json_lines.md) page. The two formats differ in one detail:
JSON Lines does not allow empty lines, while NDJSON parsers may skip them. Passing an empty line to `parse` is an
error, so skip empty lines yourself if you read NDJSON.
- **Concatenated JSON** puts values directly after each other, optionally separated by whitespace. Read them with
[`operator>>`](../../api/operator_gtgt.md), as shown in
[Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream).
### JSON text sequences (RFC 7464)
A [JSON text sequence](https://www.rfc-editor.org/rfc/rfc7464) (media type `application/json-seq`) starts every value
with the ASCII record separator (RS, `0x1E`) and ends it with a line feed. The library does not read the record
separator, but splitting the input at it is enough. The RFC asks parsers to skip a truncated or invalid value and
continue with the next one, which parsing without exceptions does:
```cpp
std::string record;
while (std::getline(input, record, '\x1e'))
{
// the input starts with RS, and several RS in a row are allowed
if (record.find_first_not_of(" \t\r\n") == std::string::npos)
{
continue;
}
json j = json::parse(record, nullptr, /* allow_exceptions */ false);
if (j.is_discarded())
{
continue; // truncated or invalid value
}
// use j
}
```
To write a sequence, write `'\x1e'`, then `j.dump()`, then `'\n'` for every value.
## Restricted profiles
### I-JSON (RFC 7493)
[I-JSON](https://www.rfc-editor.org/rfc/rfc7493) ("Internet JSON") is a subset of JSON meant for interoperable
protocols. The table shows how the library handles each of its rules:
| I-JSON rule | Library behavior |
|-----------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| text must be UTF-8 | enforced: invalid UTF-8 is a parse error |
| no surrogate code points in strings, also not as `\u` escapes | enforced: a lone surrogate such as `"\ud800"` is a parse error |
| no noncharacters (such as U+FFFF) in strings | not enforced: they are accepted |
| no duplicate object keys | not enforced: they are accepted; `parse` keeps the last value, while lookups in a [`json_view`](../json_view/differences.md#duplicate-keys) return the first; see the [recipe for rejecting duplicate keys](parser_callbacks.md#recipe-rejecting-duplicate-object-keys) |
| numbers should fit into an IEEE 754 double | numbers that overflow a double, such as `1E400`, throw [`out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406); integers are kept exactly up to 64 bits, larger ones are stored as doubles, see [number handling](../types/number_handling.md) |
| top-level values should be objects or arrays | not enforced: any value is accepted at the top level |
### JSON Canonicalization Scheme (RFC 8785)
The [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (JCS) defines one exact text for each value,
so that it can be hashed or signed. `dump()` without indentation comes close, as it writes no whitespace and, with the
default [`std::map`](../types/index.md#objects), sorts the object keys. It is not canonical, though:
- JCS formats numbers like ECMAScript, so `#!json 1.0` is written as `1` and `#!json 0.000001` as `0.000001`, while
`dump()` writes `1.0` and `1e-06`.
- JCS sorts keys by their UTF-16 code units, while `std::map` sorts them by their UTF-8 bytes. The two orders differ
for keys that contain characters above U+FFFF.
## Non-finite numbers
`NaN`, `Infinity`, and `-Infinity` are not part of JSON, but some libraries write them, among them Python's `json`
module, which does so by default (use `allow_nan=False` there to get standard JSON). This library rejects them as
parse errors, and it writes the non-finite values that a `basic_json` value can hold as `#!json null`. See
[NaN handling](../types/number_handling.md#nan-handling).
## Conventions on top of JSON
Formats such as [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org),
[GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), and
[MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) are standard JSON with
agreed meanings for certain keys or values, such as `{"$numberLong": "42"}` or a `"$comment"` key. The library parses
and writes them like any other JSON; what the values mean is up to your code. For schema validation, see the
[Ecosystem](../../community/ecosystem.md#schema-validation) page.
A few other standards built on JSON are supported directly: [JSON Pointer](../json_pointer.md),
[JSON Patch](../json_patch.md), and [JSON Merge Patch](../merge_patch.md).
For compact binary encodings of the JSON data model, such as CBOR or MessagePack, see
[Binary formats](../binary_formats/index.md).
## See also
- [Parsing](index.md) - overview of the parsing functions
- [Comments](../comments.md) - ignore `//` and `/* */` comments while parsing
- [Trailing Commas](../trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [Number handling](../types/number_handling.md) - how numbers are parsed, stored, and written
- [Binary formats](../binary_formats/index.md) - binary encodings of the JSON data model
- [Ecosystem](../../community/ecosystem.md) - projects that build on this library, including format converters
@@ -42,6 +42,5 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Comments](comments.md) - ignore `//` and `/* */` comments while parsing - [Comments](comments.md) - ignore `//` and `/* */` comments while parsing
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions - [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control - [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
@@ -168,8 +168,7 @@ library; pick one or type it to see the row):
- Integer numbers are serialized as is; that is, no scientific notation is used. - Integer numbers are serialized as is; that is, no scientific notation is used.
- Floating-point numbers are serialized with the fewest digits that read back as the same value (the closest such - Floating-point numbers are serialized with the fewest digits that read back as the same value (the closest such
digits if there are several), in the layout of the `#!c %g` printf modifier: `#!c 1.5`, `#!c 100.0`, `#!c 1e+100`. digits if there are several), in the layout of the `#!c %g` printf modifier: `#!c 1.5`, `#!c 100.0`, `#!c 1e+100`.
Doubles are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij), floats with Grisu2, which Doubles and floats are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij).
can write more digits than necessary.
!!! hint "Notes regarding precision of floating-point numbers" !!! hint "Notes regarding precision of floating-point numbers"
@@ -575,10 +575,9 @@ therefore silently changes parse results rather than raising an error. See
specifiers, for which the library likewise provides only `#!cpp double` and `#!cpp long double` overloads specifiers, for which the library likewise provides only `#!cpp double` and `#!cpp long double` overloads
(`#!cpp float` is promoted to `#!cpp double`). (`#!cpp float` is promoted to `#!cpp double`).
If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 number, `dump` uses the algorithm of If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 or binary32 number, `dump` uses the
Żmij, which produces the shortest representation that round-trips. For IEEE 754 binary32 numbers, it uses Grisu2, algorithm of Żmij, which produces the shortest representation that round-trips. Otherwise the `snprintf` fallback with
which produces a short representation that round-trips. Otherwise the `snprintf` fallback with `max_digits10` digits is `max_digits10` digits is used.
used.
### Required for the binary formats ### Required for the binary formats
@@ -591,7 +590,7 @@ binary32 or binary64 field and have no encoding for `#!cpp long double`.
| Type | Support | | Type | Support |
|--------------------------|-----------------------------------------------------------------------------------------------------------------------| |--------------------------|-----------------------------------------------------------------------------------------------------------------------|
| `#!cpp double` (default) | full; shortest round-trip output through Żmij | | `#!cpp double` (default) | full; shortest round-trip output through Żmij |
| `#!cpp float` | full; short round-trip output through Grisu2 | | `#!cpp float` | full; shortest round-trip output through Żmij |
| `#!cpp long double` | `dump` and `parse` only; the binary format writers do not compile, as they only handle IEEE 754 binary32 and binary64 | | `#!cpp long double` | `dump` and `parse` only; the binary format writers do not compile, as they only handle IEEE 754 binary32 and binary64 |
| any other type | not usable | | any other type | not usable |
+1 -1
View File
@@ -18,7 +18,7 @@ The class contains the UTF-8 Decoder from Bjoern Hoehrmann which is licensed und
The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright &copy; 2009 [Florian Loitsch](https://florian.loitsch.com/) The class contains a slightly modified version of the Grisu2 algorithm from Florian Loitsch which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright &copy; 2009 [Florian Loitsch](https://florian.loitsch.com/)
The class contains a port of the shortest double-to-decimal conversion of [Żmij](https://github.com/vitaut/zmij) by Victor Zverovich, including the conversion of the digits to text by Xiang JunBo and the SIMD instruction sequence of Dougall Johnson, which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright &copy; 2025 [Victor Zverovich](https://github.com/vitaut) The class contains a port of the shortest double- and float-to-decimal conversion of [Żmij](https://github.com/vitaut/zmij) by Victor Zverovich, including the conversion of the digits to text by Xiang JunBo and the SIMD instruction sequence of Dougall Johnson, which is licensed under the [MIT License](https://opensource.org/licenses/MIT) (see above). Copyright &copy; 2025 [Victor Zverovich](https://github.com/vitaut)
The class contains a copy of [Hedley](https://nemequ.github.io/hedley/) from Evan Nemerson which is licensed as [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0/). The class contains a copy of [Hedley](https://nemequ.github.io/hedley/) from Evan Nemerson which is licensed as [CC0-1.0](https://creativecommons.org/publicdomain/zero/1.0/).
-1
View File
@@ -146,7 +146,6 @@ nav:
- Parsing: - Parsing:
- features/parsing/index.md - features/parsing/index.md
- features/parsing/json_lines.md - features/parsing/json_lines.md
- features/parsing/json_variants.md
- features/parsing/large_and_partial_input.md - features/parsing/large_and_partial_input.md
- features/parsing/parse_exceptions.md - features/parsing/parse_exceptions.md
- features/parsing/parser_callbacks.md - features/parsing/parser_callbacks.md
@@ -49,8 +49,8 @@ namespace detail
/*! /*!
@brief implements binary to decimal floating-point conversion: the shortest @brief implements binary to decimal floating-point conversion: the shortest
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2 digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
algorithm for all other formats. the Grisu2 algorithm for all other formats.
The Grisu2 implementation is a slightly modified version of the reference The Grisu2 implementation is a slightly modified version of the reference
implementation which may be obtained from implementation which may be obtained from
@@ -1397,8 +1397,9 @@ inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noe
@brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double @brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double
that has the same format, as with MSVC and on Apple's Arm CPUs) that has the same format, as with MSVC and on Apple's Arm CPUs)
These are the types the conversion of Zmij (see zmij.hpp) is used for; all These are the types the conversion of Zmij (see zmij.hpp) is used for with
others (binary32, or a format the library does not know) use Grisu2. write_shortest(); binary32 numbers use it with format_buffer(), and all
others (e.g. the 80-bit long double of x87) use Grisu2.
*/ */
template<typename FloatType> template<typename FloatType>
constexpr bool has_binary64_format() noexcept constexpr bool has_binary64_format() noexcept
@@ -1412,7 +1413,23 @@ constexpr bool has_binary64_format() noexcept
template<typename FloatType> template<typename FloatType>
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {}; struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
/// a positive finite float (other than binary64): Grisu2 and format_buffer() /// whether FloatType is an IEEE 754 binary32 type (a float); these use the
/// conversion of Zmij as well
template<typename FloatType>
constexpr bool has_binary32_format() noexcept
{
return std::numeric_limits<FloatType>::is_iec559
&& std::numeric_limits<FloatType>::digits == 24
&& std::numeric_limits<FloatType>::max_exponent == 128
&& sizeof(FloatType) == sizeof(std::uint32_t);
}
/// the conversion for a floating-point type: 0 for Grisu2, 1 for Zmij on
/// binary64, 2 for Zmij on binary32
template<typename FloatType>
struct float_conversion : std::integral_constant < int, (has_binary64_format<FloatType>() ? 1 : 0) + (has_binary32_format<FloatType>() ? 2 : 0) > {};
/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer()
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
@@ -1466,32 +1483,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
return first + len; return first + len;
} }
/// a positive finite binary32 number: the shortest digits (Zmij), laid out by
/// format_buffer() as the digits of Grisu2 were (only the digits differ: Grisu2
/// leaves out a decimal on the boundary of the rounding interval and may take
/// the other one of two equally close decimals)
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive_zmij_binary32(char* first, const char* last, FloatType value)
{
static_assert(has_binary32_format<FloatType>(),
"internal error: this conversion of Zmij needs IEEE 754 binary32 numbers");
const zmij::shortest_decimal d = zmij::to_shortest_of<zmij::binary32_format>(bit_cast<std::uint32_t>(value));
std::uint64_t digits = d.has_digit ? (d.integral * 10) + d.digit : d.integral;
int decimal_exponent = d.has_digit ? d.exponent : d.exponent + 1;
while (digits % 10 == 0)
{
digits /= 10;
++decimal_exponent;
}
// at most 9 digits (max_digits10), written from the end
std::array<char, 9> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read
std::size_t start = buf.size();
do
{
buf[--start] = static_cast<char>('0' + (digits % 10));
digits /= 10;
}
while (digits != 0);
const auto len = static_cast<int>(buf.size() - start);
JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits<FloatType>::max_digits10);
static_cast<void>(last); // (only used in the assertions)
std::memcpy(first, buf.data() + start, static_cast<std::size_t>(len));
// as write_positive_grisu2()
return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits<FloatType>::digits10);
}
/// a positive finite float of a format without Zmij: Grisu2
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 0> /*grisu2*/)
{
return write_positive_grisu2(first, last, value);
}
/// a positive finite binary64 number: Zmij (as a long double has the format of /// a positive finite binary64 number: Zmij (as a long double has the format of
/// a double here, its bits are those of the double of the same value) /// a double here, its bits are those of the double of the same value)
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 1> /*binary64*/)
{ {
return write_positive_zmij(first, last, value); return write_positive_zmij(first, last, value);
} }
/// a positive finite float of any other format: Grisu2 /// a positive finite binary32 number: Zmij
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 2> /*binary32*/)
{ {
return write_positive_grisu2(first, last, value); return write_positive_zmij_binary32(first, last, value);
} }
/// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise /// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value) char* write_positive(char* first, const char* last, FloatType value)
{ {
return write_positive(first, last, value, is_binary64<FloatType> {}); return write_positive(first, last, value, float_conversion<FloatType> {});
} }
} // namespace dtoa_impl } // namespace dtoa_impl
+31 -10
View File
@@ -160,22 +160,37 @@ struct shortest_decimal
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
}; };
/// The shortest decimal in the rounding interval of a positive finite double /// the bit layout of an IEEE 754 binary format: SigBits significand bits
/// given by its bits, the closest one if there are several (to_decimal of /// (without the implicit bit) below ExpBits exponent bits
/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be template<int SigBits, int ExpBits>
/// converted without a multiplication by 10 first). Always inlined: GCC struct binary_format
/// otherwise calls it, and its result goes through memory. {
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept static constexpr unsigned sig_bits = SigBits;
static constexpr unsigned exp_mask = (1u << static_cast<unsigned>(ExpBits)) - 1u;
static constexpr int exp_offset = (1 << (ExpBits - 1)) - 1 + SigBits; // the bias plus the significand bits
};
using binary64_format = binary_format<52, 11>;
using binary32_format = binary_format<23, 8>;
/// The shortest decimal in the rounding interval of a positive finite number of
/// the format Format given by its bits, the closest one if there are several
/// (to_decimal of Zmij, which keeps the last digit apart: the 15 or 16 digits
/// of a normal double before it, 6 or 7 of a float, can be converted without a
/// multiplication by 10 first). As in Zmij, the same computation serves both
/// formats; only the bit layout differs. Always inlined: GCC otherwise calls
/// it, and its result goes through memory.
template<typename Format>
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept
{ {
constexpr int extra_shift = 9; constexpr int extra_shift = 9;
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu); const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1); std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1);
// a power of two has a narrower interval below (except the smallest normal) // a power of two has a narrower interval below (except the smallest normal)
const bool regular = bin_sig != 0 || raw_exp <= 1; const bool regular = bin_sig != 0 || raw_exp <= 1;
const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075; const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - Format::exp_offset;
if (raw_exp != 0) if (raw_exp != 0)
{ {
bin_sig |= std::uint64_t{1} << 52u; bin_sig |= std::uint64_t{1} << Format::sig_bits;
} }
// floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case // floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case
const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20; const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20;
@@ -217,6 +232,12 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexc
return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down}; return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down};
} }
/// to_shortest_of() for a double given by its bits
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
{
return to_shortest_of<binary64_format>(bits);
}
} // namespace zmij } // namespace zmij
} // namespace detail } // namespace detail
NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_END
+106 -21
View File
@@ -36041,22 +36041,37 @@ struct shortest_decimal
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
}; };
/// The shortest decimal in the rounding interval of a positive finite double /// the bit layout of an IEEE 754 binary format: SigBits significand bits
/// given by its bits, the closest one if there are several (to_decimal of /// (without the implicit bit) below ExpBits exponent bits
/// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be template<int SigBits, int ExpBits>
/// converted without a multiplication by 10 first). Always inlined: GCC struct binary_format
/// otherwise calls it, and its result goes through memory. {
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept static constexpr unsigned sig_bits = SigBits;
static constexpr unsigned exp_mask = (1u << static_cast<unsigned>(ExpBits)) - 1u;
static constexpr int exp_offset = (1 << (ExpBits - 1)) - 1 + SigBits; // the bias plus the significand bits
};
using binary64_format = binary_format<52, 11>;
using binary32_format = binary_format<23, 8>;
/// The shortest decimal in the rounding interval of a positive finite number of
/// the format Format given by its bits, the closest one if there are several
/// (to_decimal of Zmij, which keeps the last digit apart: the 15 or 16 digits
/// of a normal double before it, 6 or 7 of a float, can be converted without a
/// multiplication by 10 first). As in Zmij, the same computation serves both
/// formats; only the bit layout differs. Always inlined: GCC otherwise calls
/// it, and its result goes through memory.
template<typename Format>
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) noexcept
{ {
constexpr int extra_shift = 9; constexpr int extra_shift = 9;
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu); const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 1); std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1);
// a power of two has a narrower interval below (except the smallest normal) // a power of two has a narrower interval below (except the smallest normal)
const bool regular = bin_sig != 0 || raw_exp <= 1; const bool regular = bin_sig != 0 || raw_exp <= 1;
const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075; const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - Format::exp_offset;
if (raw_exp != 0) if (raw_exp != 0)
{ {
bin_sig |= std::uint64_t{1} << 52u; bin_sig |= std::uint64_t{1} << Format::sig_bits;
} }
// floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case // floor(log10(2^bin_exp)), or floor(log10(3/4 * 2^bin_exp)) for the irregular case
const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20; const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20;
@@ -36098,6 +36113,12 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexc
return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down}; return shortest_decimal{integral, dec_exp, static_cast<unsigned char>(digit), !round_up && !round_down};
} }
/// to_shortest_of() for a double given by its bits
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
{
return to_shortest_of<binary64_format>(bits);
}
} // namespace zmij } // namespace zmij
} // namespace detail } // namespace detail
NLOHMANN_JSON_NAMESPACE_END NLOHMANN_JSON_NAMESPACE_END
@@ -36111,8 +36132,8 @@ namespace detail
/*! /*!
@brief implements binary to decimal floating-point conversion: the shortest @brief implements binary to decimal floating-point conversion: the shortest
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2 digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
algorithm for all other formats. the Grisu2 algorithm for all other formats.
The Grisu2 implementation is a slightly modified version of the reference The Grisu2 implementation is a slightly modified version of the reference
implementation which may be obtained from implementation which may be obtained from
@@ -37459,8 +37480,9 @@ inline char* write_short_decimal(char* first, std::uint64_t digits, int exp) noe
@brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double @brief whether FloatType is an IEEE 754 binary64 type (a double, or a long double
that has the same format, as with MSVC and on Apple's Arm CPUs) that has the same format, as with MSVC and on Apple's Arm CPUs)
These are the types the conversion of Zmij (see zmij.hpp) is used for; all These are the types the conversion of Zmij (see zmij.hpp) is used for with
others (binary32, or a format the library does not know) use Grisu2. write_shortest(); binary32 numbers use it with format_buffer(), and all
others (e.g. the 80-bit long double of x87) use Grisu2.
*/ */
template<typename FloatType> template<typename FloatType>
constexpr bool has_binary64_format() noexcept constexpr bool has_binary64_format() noexcept
@@ -37474,7 +37496,23 @@ constexpr bool has_binary64_format() noexcept
template<typename FloatType> template<typename FloatType>
struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {}; struct is_binary64 : std::integral_constant<bool, has_binary64_format<FloatType>()> {};
/// a positive finite float (other than binary64): Grisu2 and format_buffer() /// whether FloatType is an IEEE 754 binary32 type (a float); these use the
/// conversion of Zmij as well
template<typename FloatType>
constexpr bool has_binary32_format() noexcept
{
return std::numeric_limits<FloatType>::is_iec559
&& std::numeric_limits<FloatType>::digits == 24
&& std::numeric_limits<FloatType>::max_exponent == 128
&& sizeof(FloatType) == sizeof(std::uint32_t);
}
/// the conversion for a floating-point type: 0 for Grisu2, 1 for Zmij on
/// binary64, 2 for Zmij on binary32
template<typename FloatType>
struct float_conversion : std::integral_constant < int, (has_binary64_format<FloatType>() ? 1 : 0) + (has_binary32_format<FloatType>() ? 2 : 0) > {};
/// a positive finite float (other than binary64 and binary32): Grisu2 and format_buffer()
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
@@ -37528,32 +37566,79 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
return first + len; return first + len;
} }
/// a positive finite binary32 number: the shortest digits (Zmij), laid out by
/// format_buffer() as the digits of Grisu2 were (only the digits differ: Grisu2
/// leaves out a decimal on the boundary of the rounding interval and may take
/// the other one of two equally close decimals)
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive_zmij_binary32(char* first, const char* last, FloatType value)
{
static_assert(has_binary32_format<FloatType>(),
"internal error: this conversion of Zmij needs IEEE 754 binary32 numbers");
const zmij::shortest_decimal d = zmij::to_shortest_of<zmij::binary32_format>(bit_cast<std::uint32_t>(value));
std::uint64_t digits = d.has_digit ? (d.integral * 10) + d.digit : d.integral;
int decimal_exponent = d.has_digit ? d.exponent : d.exponent + 1;
while (digits % 10 == 0)
{
digits /= 10;
++decimal_exponent;
}
// at most 9 digits (max_digits10), written from the end
std::array<char, 9> buf; // NOLINT(cppcoreguidelines-pro-type-member-init,hicpp-member-init): written before read
std::size_t start = buf.size();
do
{
buf[--start] = static_cast<char>('0' + (digits % 10));
digits /= 10;
}
while (digits != 0);
const auto len = static_cast<int>(buf.size() - start);
JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
JSON_ASSERT(last - first >= 2 + 3 + std::numeric_limits<FloatType>::max_digits10);
static_cast<void>(last); // (only used in the assertions)
std::memcpy(first, buf.data() + start, static_cast<std::size_t>(len));
// as write_positive_grisu2()
return format_buffer(first, len, decimal_exponent, -4, std::numeric_limits<FloatType>::digits10);
}
/// a positive finite float of a format without Zmij: Grisu2
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 0> /*grisu2*/)
{
return write_positive_grisu2(first, last, value);
}
/// a positive finite binary64 number: Zmij (as a long double has the format of /// a positive finite binary64 number: Zmij (as a long double has the format of
/// a double here, its bits are those of the double of the same value) /// a double here, its bits are those of the double of the same value)
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 1> /*binary64*/)
{ {
return write_positive_zmij(first, last, value); return write_positive_zmij(first, last, value);
} }
/// a positive finite float of any other format: Grisu2 /// a positive finite binary32 number: Zmij
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::integral_constant<int, 2> /*binary32*/)
{ {
return write_positive_grisu2(first, last, value); return write_positive_zmij_binary32(first, last, value);
} }
/// a positive finite float: Zmij for binary64 numbers, Grisu2 otherwise /// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise
template<typename FloatType> template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_RETURNS_NON_NULL
char* write_positive(char* first, const char* last, FloatType value) char* write_positive(char* first, const char* last, FloatType value)
{ {
return write_positive(first, last, value, is_binary64<FloatType> {}); return write_positive(first, last, value, float_conversion<FloatType> {});
} }
} // namespace dtoa_impl } // namespace dtoa_impl
+126 -5
View File
@@ -22,6 +22,7 @@ using nlohmann::detail::bit_cast;
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <limits> #include <limits>
#include <map>
#include <random> #include <random>
#include <string> #include <string>
#include <utility> #include <utility>
@@ -711,8 +712,122 @@ void check_shortest(double v)
CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de); CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de);
#endif #endif
} }
/// a basic_json whose floating-point numbers are floats
using json_with_float = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>;
/// the correctly rounded float of a decimal text (as parse_double())
float parse_float(const std::string& text)
{
const json_with_float j = json_with_float::parse(text, nullptr, false);
return j.is_discarded() ? std::numeric_limits<float>::infinity() : j.get<float>();
}
/// Check the representation of a positive finite float as check_shortest():
/// it reads back as the same value, and no representation with fewer digits
/// does.
void check_shortest_float(float v)
{
std::array<char, 33> buf{};
char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, v);
const std::string text(buf.data(), end);
CAPTURE(text)
CHECK(bit_cast<std::uint32_t>(parse_float(text)) == bit_cast<std::uint32_t>(v));
const auto de = digits_and_exponent(text);
const std::string& digits = de.first;
if (digits.size() > 1)
{
const std::uint64_t mid = std::stoull(digits.substr(0, digits.size() - 1));
for (const std::uint64_t candidate :
{
mid - 1, mid, mid + 1
})
{
CAPTURE(candidate)
const std::string shorter = std::to_string(candidate) + "e" + std::to_string(de.second + 1);
CHECK(bit_cast<std::uint32_t>(parse_float(shorter)) != bit_cast<std::uint32_t>(v));
}
}
#if defined(JSON_HAS_CPP_17) && defined(__cpp_lib_to_chars) && !defined(__INTEL_COMPILER)
std::array<char, 64> std_text {};
const auto r = std::to_chars(std_text.data(), std_text.data() + std_text.size(), v, std::chars_format::scientific);
CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de);
#endif
}
} // namespace } // namespace
TEST_CASE("shortest digits of floats")
{
// (all 2^31 - 2^23 - 1 positive finite floats were checked against
// std::to_chars when this was written; these are the edge cases)
SECTION("boundary values")
{
for (const float v :
{
std::numeric_limits<float>::min(), std::numeric_limits<float>::max(), std::numeric_limits<float>::denorm_min(),
std::nextafter(std::numeric_limits<float>::min(), 0.0f), std::nextafter(std::numeric_limits<float>::max(), 0.0f),
1.0f, 2.0f, 0.1f, 0.3f, 1e7f, 1e-5f, 123456.7f, 16777216.0f, 16777217.0f, 7.0385307e-26f
})
{
check_shortest_float(v);
}
// all powers of two (their rounding interval is narrower below)
for (int e = -149; e <= 127; ++e)
{
check_shortest_float(std::ldexp(1.0f, e));
}
// powers of ten and their neighbors (from 1e-44: 1e-45 reads as the
// smallest float, which is in the list above, and the float below it is 0)
for (int e = -44; e <= 38; ++e)
{
const float p = parse_float("1e" + std::to_string(e));
check_shortest_float(p);
check_shortest_float(std::nextafter(p, 0.0f));
check_shortest_float(std::nextafter(p, std::numeric_limits<float>::infinity()));
}
}
SECTION("where Grisu2 wrote other digits")
{
// Grisu2 leaves out the decimals on the boundary of the rounding
// interval and may take the other one of two equally close decimals;
// both read back as the same float either way
const auto text = [](float v) -> std::string
{
std::array<char, 33> buf{};
char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, v);
return {buf.data(), end};
};
const auto grisu2_text = [](float v) -> std::string
{
std::array<char, 33> buf{};
char* end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), buf.data() + 32, v);
return {buf.data(), end};
};
// 134218208 = 2^27 + 32: 1.342182e+08 is the upper end of its rounding interval
CHECK(text(134218208.0f) == "1.342182e+08");
CHECK(grisu2_text(134218208.0f) == "1.3421821e+08");
check_shortest_float(134218208.0f);
// 2097156.25 = 2^21 + 4.25: 2097156.2 and 2097156.3 are equally close; the even digit
CHECK(text(2097156.25f) == "2.0971562e+06");
CHECK(grisu2_text(2097156.25f) == "2.0971563e+06");
check_shortest_float(2097156.25f);
}
SECTION("random floats")
{
std::mt19937 rng(5295); // NOLINT(cert-msc32-c,cert-msc51-cpp,bugprone-random-generator-seed): reproducible
for (int i = 0; i < 100000; ++i)
{
const std::uint32_t bits = static_cast<std::uint32_t>(rng()) & 0x7FFFFFFFu;
const auto v = bit_cast<float>(bits);
if (std::isfinite(v) && bits != 0)
{
check_shortest_float(v);
}
}
}
}
TEST_CASE("shortest digits of doubles") TEST_CASE("shortest digits of doubles")
{ {
SECTION("powers of ten") SECTION("powers of ten")
@@ -791,11 +906,16 @@ TEST_CASE("shortest digits of doubles")
TEST_CASE("choice of the conversion") TEST_CASE("choice of the conversion")
{ {
using nlohmann::detail::dtoa_impl::is_binary64; using nlohmann::detail::dtoa_impl::is_binary64;
using nlohmann::detail::dtoa_impl::float_conversion;
SECTION("by the format of the type") SECTION("by the format of the type")
{ {
// Zmij needs binary64 numbers; everything else uses Grisu2 // Zmij needs binary64 or binary32 numbers; everything else uses Grisu2
static_assert(!is_binary64<float>::value, "float is not binary64"); static_assert(!is_binary64<float>::value, "float is not binary64");
static_assert(float_conversion<float>::value == (std::numeric_limits<float>::is_iec559 && std::numeric_limits<float>::digits == 24 ? 2 : 0),
"float is binary32 where it is IEEE 754 with 24 digits");
static_assert(float_conversion<double>::value == (is_binary64<double>::value ? 1 : 0), "double is binary64 or uses Grisu2");
static_assert(float_conversion<int>::value == 0, "integers use Grisu2");
static_assert(is_binary64<double>::value == (std::numeric_limits<double>::is_iec559 && std::numeric_limits<double>::digits == 53), static_assert(is_binary64<double>::value == (std::numeric_limits<double>::is_iec559 && std::numeric_limits<double>::digits == 53),
"double is binary64 where it is IEEE 754 with 53 digits"); "double is binary64 where it is IEEE 754 with 53 digits");
static_assert(!is_binary64<int>::value, "integers are not binary64"); static_assert(!is_binary64<int>::value, "integers are not binary64");
@@ -805,7 +925,7 @@ TEST_CASE("choice of the conversion")
CHECK(is_binary64<double>::value); CHECK(is_binary64<double>::value);
} }
SECTION("float: Grisu2, double: Zmij") SECTION("float and double: Zmij")
{ {
// 5.3165205877497296e+16 is one of the doubles for which Grisu2 does not find the shortest digits // 5.3165205877497296e+16 is one of the doubles for which Grisu2 does not find the shortest digits
constexpr double value = 5.3165205877497296e+16; constexpr double value = 5.3165205877497296e+16;
@@ -817,11 +937,12 @@ TEST_CASE("choice of the conversion")
end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, value); end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, value);
CHECK(std::string(buf.data(), end) == "5.3165205877497296e+16"); CHECK(std::string(buf.data(), end) == "5.3165205877497296e+16");
constexpr float f = 1.1754944e-38f; // 134218208.0f is one of the floats for which Grisu2 does not find the shortest digits
constexpr float f = 134218208.0f;
end = nlohmann::detail::dtoa_impl::write_positive(buf.data(), last, f); end = nlohmann::detail::dtoa_impl::write_positive(buf.data(), last, f);
const std::string dispatched(buf.data(), end); CHECK(std::string(buf.data(), end) == "1.342182e+08");
end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, f); end = nlohmann::detail::dtoa_impl::write_positive_grisu2(buf.data(), last, f);
CHECK(dispatched == std::string(buf.data(), end)); CHECK(std::string(buf.data(), end) == "1.3421821e+08");
} }
SECTION("long double with the format of a double: Zmij") SECTION("long double with the format of a double: Zmij")