Compare commits

..
Author SHA1 Message Date
Niels Lohmann a1b49b720a Name and document the 4096-byte read block in json_document input
Replace the four 4096 literals with read_block_size() and explain that it
is a conventional page-sized chunk (EOF slack and minimum read room), not a
tuned value. No behaviour change.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-25 20:14:51 +01:00
Niels Lohmann 58602b043b json_document: read files and streams in one block
parse(FILE*) and parse(std::istream&) read their input into a string that
grew by doubling, with a reallocation and copy at each step (about 16 reads
for a 0.6 MB file). On Linux, glibc then grows and trims the heap around
these blocks, so the memory faults in again on every parse.

Reserve the rest of the input first when its size is known: for a FILE* that
is a regular file, from fstat (_fstat64 on Windows) and its position; for a
stream, from in_avail() (which libstdc++ answers for files with the rest of
the file). The read loop is unchanged; the size is only a hint.

File to document on Linux (GCC 16): twitter.json -72%, canada.json -72%,
semanticscholar-corpus.json -73%, jeopardy.json -25..-29%, small files
-0..-17%.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-25 19:16:11 +01:00
10 changed files with 226 additions and 354 deletions

No files matched your search

@@ -168,7 +168,8 @@ 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 and floats are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij). Doubles are converted with the algorithm of [Żmij](https://github.com/vitaut/zmij), floats with Grisu2, which
can write more digits than necessary.
!!! hint "Notes regarding precision of floating-point numbers" !!! hint "Notes regarding precision of floating-point numbers"
@@ -575,9 +575,10 @@ 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 or binary32 number, `dump` uses the If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 number, `dump` uses the algorithm of
algorithm of Żmij, which produces the shortest representation that round-trips. Otherwise the `snprintf` fallback with Żmij, which produces the shortest representation that round-trips. For IEEE 754 binary32 numbers, it uses Grisu2,
`max_digits10` digits is used. which produces a short representation that round-trips. Otherwise the `snprintf` fallback with `max_digits10` digits is
used.
### Required for the binary formats ### Required for the binary formats
@@ -590,7 +591,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; shortest round-trip output through Żmij | | `#!cpp float` | full; short round-trip output through Grisu2 |
| `#!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- 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 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 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/).
@@ -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 and binary32 numbers, and digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
the Grisu2 algorithm for all other formats. 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,9 +1397,8 @@ 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 with These are the types the conversion of Zmij (see zmij.hpp) is used for; all
write_shortest(); binary32 numbers use it with format_buffer(), and all others (binary32, or a format the library does not know) use Grisu2.
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
@@ -1413,23 +1412,7 @@ 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>()> {};
/// whether FloatType is an IEEE 754 binary32 type (a float); these use the /// a positive finite float (other than binary64): Grisu2 and format_buffer()
/// 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
@@ -1483,79 +1466,32 @@ 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::integral_constant<int, 1> /*binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/)
{ {
return write_positive_zmij(first, last, value); return write_positive_zmij(first, last, value);
} }
/// a positive finite binary32 number: Zmij /// a positive finite float of any other format: Grisu2
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::integral_constant<int, 2> /*binary32*/) char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/)
{ {
return write_positive_zmij_binary32(first, last, value); return write_positive_grisu2(first, last, value);
} }
/// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise /// a positive finite float: Zmij for binary64 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, float_conversion<FloatType> {}); return write_positive(first, last, value, is_binary64<FloatType> {});
} }
} // namespace dtoa_impl } // namespace dtoa_impl
+10 -31
View File
@@ -160,37 +160,22 @@ 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 bit layout of an IEEE 754 binary format: SigBits significand bits /// The shortest decimal in the rounding interval of a positive finite double
/// (without the implicit bit) below ExpBits exponent bits /// given by its bits, the closest one if there are several (to_decimal of
template<int SigBits, int ExpBits> /// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be
struct binary_format /// converted without a multiplication by 10 first). Always inlined: GCC
{ /// otherwise calls it, and its result goes through memory.
static constexpr unsigned sig_bits = SigBits; JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
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 >> Format::sig_bits) & Format::exp_mask); const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1); std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 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) - Format::exp_offset; const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075;
if (raw_exp != 0) if (raw_exp != 0)
{ {
bin_sig |= std::uint64_t{1} << Format::sig_bits; bin_sig |= std::uint64_t{1} << 52u;
} }
// 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;
@@ -232,12 +217,6 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) no
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
+72 -5
View File
@@ -11,7 +11,15 @@
#include <algorithm> // max #include <algorithm> // max
#include <cstddef> // size_t #include <cstddef> // size_t
#ifndef JSON_NO_IO #ifndef JSON_NO_IO
#include <cstdio> // FILE, fread #include <cstdio> // FILE, fread, ftell
#if defined(_WIN32)
#include <stdio.h> // _fileno, _ftelli64 // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
#include <sys/types.h> // (for sys/stat.h)
#include <sys/stat.h> // _fstat64, _S_IFMT, _S_IFREG
#elif defined(__unix__) || defined(__APPLE__)
#include <stdio.h> // fileno // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
#include <sys/stat.h> // fstat, S_ISREG
#endif
#endif #endif
#include <istream> // istream, streambuf #include <istream> // istream, streambuf
#include <string> // basic_string, char_traits, string #include <string> // basic_string, char_traits, string
@@ -131,6 +139,15 @@ adapter_input<typename std::decay<Adapter>::type> make_adapter_input(Adapter&& i
return {std::forward<Adapter>(ia)}; return {std::forward<Adapter>(ia)};
} }
/// the size of a read block, and the least room offered to a read: one page,
/// the usual size of a filesystem block. It is a conventional size, not a tuned
/// one: it only has to be large enough that a read is never tiny and that the
/// read which finds the end of the input needs no regrowth of the string
constexpr std::size_t read_block_size() noexcept
{
return 4096;
}
/// append the rest of a stream: its characters need no conversion, so they are /// append the rest of a stream: its characters need no conversion, so they are
/// read in blocks from the stream buffer, straight into buf (reusing its /// read in blocks from the stream buffer, straight into buf (reusing its
/// capacity). As the library's stream adapter, this reads the stream buffer /// capacity). As the library's stream adapter, this reads the stream buffer
@@ -142,10 +159,20 @@ inline void append_stream(std::string& buf, std::istream& is)
{ {
return; return;
} }
// room for the rest when the stream buffer knows how much is left (for a
// file with libstdc++, the rest of the file), and for the read that finds
// the end: the input is then read in one block, without a reallocation and
// copy at each doubling of the string (only a hint: the loop below reads
// what is there)
const std::streamsize rest = sb->in_avail();
if (rest > 0 && static_cast<std::size_t>(rest) < buf.max_size() - buf.size() - read_block_size())
{
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + read_block_size());
}
for (;;) for (;;)
{ {
const std::size_t used = buf.size(); const std::size_t used = buf.size();
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096}); const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
buf.resize(used + room); buf.resize(used + room);
const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room)); const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room));
buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0}))); buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0})));
@@ -168,15 +195,55 @@ struct is_c_stream
{}; {};
#ifndef JSON_NO_IO #ifndef JSON_NO_IO
/// the number of bytes left in a C stream that is a regular file (from its
/// size and position), 0 for anything else and on other systems: a hint for
/// the room to reserve; f is not null
inline unsigned long long file_rest(std::FILE* f) noexcept
{
#if defined(_WIN32)
struct _stat64 st {};
if (::_fstat64(_fileno(f), &st) == 0 && (st.st_mode & _S_IFMT) == _S_IFREG)
{
const long long here = ::_ftelli64(f);
if (here >= 0 && st.st_size > here)
{
return static_cast<unsigned long long>(st.st_size - here);
}
}
#elif defined(__unix__) || defined(__APPLE__)
struct stat st {};
if (::fstat(fileno(f), &st) == 0 && S_ISREG(st.st_mode))
{
const long here = std::ftell(f);
if (here >= 0 && st.st_size > here)
{
return static_cast<unsigned long long>(st.st_size - here);
}
}
#else
static_cast<void>(f);
#endif
return 0;
}
/// append the rest of a C stream: in blocks with fread, not character by /// append the rest of a C stream: in blocks with fread, not character by
/// character (the library's file adapter reads with fgetc); /// character (the library's file adapter reads with fgetc), and in one block
/// f is not null /// when it is a regular file of known size; f is not null
inline void append_file(std::string& buf, std::FILE* f) inline void append_file(std::string& buf, std::FILE* f)
{ {
// room for the rest of a regular file and the byte that shows its end:
// the file is then read in one block, without a reallocation and copy at
// each doubling of the string (only a hint: the loop below reads what is
// there)
const unsigned long long rest = file_rest(f);
if (rest > 0 && rest < buf.max_size() - buf.size() - 1)
{
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + 1);
}
for (;;) for (;;)
{ {
const std::size_t used = buf.size(); const std::size_t used = buf.size();
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096}); const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
buf.resize(used + room); buf.resize(used + room);
const std::size_t got = std::fread(&buf[used], 1, room, f); const std::size_t got = std::fread(&buf[used], 1, room, f);
buf.resize(used + got); buf.resize(used + got);
+21 -106
View File
@@ -36041,37 +36041,22 @@ 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 bit layout of an IEEE 754 binary format: SigBits significand bits /// The shortest decimal in the rounding interval of a positive finite double
/// (without the implicit bit) below ExpBits exponent bits /// given by its bits, the closest one if there are several (to_decimal of
template<int SigBits, int ExpBits> /// Zmij, which keeps the last digit apart: the 15 or 16 digits before it can be
struct binary_format /// converted without a multiplication by 10 first). Always inlined: GCC
{ /// otherwise calls it, and its result goes through memory.
static constexpr unsigned sig_bits = SigBits; JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
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 >> Format::sig_bits) & Format::exp_mask); const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1); std::uint64_t bin_sig = bits & ((std::uint64_t{1} << 52u) - 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) - Format::exp_offset; const int bin_exp = (raw_exp == 0 ? 1 : raw_exp) - 1075;
if (raw_exp != 0) if (raw_exp != 0)
{ {
bin_sig |= std::uint64_t{1} << Format::sig_bits; bin_sig |= std::uint64_t{1} << 52u;
} }
// 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;
@@ -36113,12 +36098,6 @@ JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest_of(std::uint64_t bits) no
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
@@ -36132,8 +36111,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 and binary32 numbers, and digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
the Grisu2 algorithm for all other formats. 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
@@ -37480,9 +37459,8 @@ 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 with These are the types the conversion of Zmij (see zmij.hpp) is used for; all
write_shortest(); binary32 numbers use it with format_buffer(), and all others (binary32, or a format the library does not know) use Grisu2.
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
@@ -37496,23 +37474,7 @@ 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>()> {};
/// whether FloatType is an IEEE 754 binary32 type (a float); these use the /// a positive finite float (other than binary64): Grisu2 and format_buffer()
/// 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
@@ -37566,79 +37528,32 @@ 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::integral_constant<int, 1> /*binary64*/) char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/)
{ {
return write_positive_zmij(first, last, value); return write_positive_zmij(first, last, value);
} }
/// a positive finite binary32 number: Zmij /// a positive finite float of any other format: Grisu2
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::integral_constant<int, 2> /*binary32*/) char* write_positive(char* first, const char* last, FloatType value, std::false_type /*is_binary64*/)
{ {
return write_positive_zmij_binary32(first, last, value); return write_positive_grisu2(first, last, value);
} }
/// a positive finite float: Zmij for binary64 and binary32 numbers, Grisu2 otherwise /// a positive finite float: Zmij for binary64 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, float_conversion<FloatType> {}); return write_positive(first, last, value, is_binary64<FloatType> {});
} }
} // namespace dtoa_impl } // namespace dtoa_impl
+72 -5
View File
@@ -7957,7 +7957,15 @@ NLOHMANN_JSON_NAMESPACE_END
#include <algorithm> // max #include <algorithm> // max
#include <cstddef> // size_t #include <cstddef> // size_t
#ifndef JSON_NO_IO #ifndef JSON_NO_IO
#include <cstdio> // FILE, fread #include <cstdio> // FILE, fread, ftell
#if defined(_WIN32)
#include <stdio.h> // _fileno, _ftelli64 // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
#include <sys/types.h> // (for sys/stat.h)
#include <sys/stat.h> // _fstat64, _S_IFMT, _S_IFREG
#elif defined(__unix__) || defined(__APPLE__)
#include <stdio.h> // fileno // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
#include <sys/stat.h> // fstat, S_ISREG
#endif
#endif #endif
#include <istream> // istream, streambuf #include <istream> // istream, streambuf
#include <string> // basic_string, char_traits, string #include <string> // basic_string, char_traits, string
@@ -8078,6 +8086,15 @@ adapter_input<typename std::decay<Adapter>::type> make_adapter_input(Adapter&& i
return {std::forward<Adapter>(ia)}; return {std::forward<Adapter>(ia)};
} }
/// the size of a read block, and the least room offered to a read: one page,
/// the usual size of a filesystem block. It is a conventional size, not a tuned
/// one: it only has to be large enough that a read is never tiny and that the
/// read which finds the end of the input needs no regrowth of the string
constexpr std::size_t read_block_size() noexcept
{
return 4096;
}
/// append the rest of a stream: its characters need no conversion, so they are /// append the rest of a stream: its characters need no conversion, so they are
/// read in blocks from the stream buffer, straight into buf (reusing its /// read in blocks from the stream buffer, straight into buf (reusing its
/// capacity). As the library's stream adapter, this reads the stream buffer /// capacity). As the library's stream adapter, this reads the stream buffer
@@ -8089,10 +8106,20 @@ inline void append_stream(std::string& buf, std::istream& is)
{ {
return; return;
} }
// room for the rest when the stream buffer knows how much is left (for a
// file with libstdc++, the rest of the file), and for the read that finds
// the end: the input is then read in one block, without a reallocation and
// copy at each doubling of the string (only a hint: the loop below reads
// what is there)
const std::streamsize rest = sb->in_avail();
if (rest > 0 && static_cast<std::size_t>(rest) < buf.max_size() - buf.size() - read_block_size())
{
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + read_block_size());
}
for (;;) for (;;)
{ {
const std::size_t used = buf.size(); const std::size_t used = buf.size();
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096}); const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
buf.resize(used + room); buf.resize(used + room);
const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room)); const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room));
buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0}))); buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0})));
@@ -8115,15 +8142,55 @@ struct is_c_stream
{}; {};
#ifndef JSON_NO_IO #ifndef JSON_NO_IO
/// the number of bytes left in a C stream that is a regular file (from its
/// size and position), 0 for anything else and on other systems: a hint for
/// the room to reserve; f is not null
inline unsigned long long file_rest(std::FILE* f) noexcept
{
#if defined(_WIN32)
struct _stat64 st {};
if (::_fstat64(_fileno(f), &st) == 0 && (st.st_mode & _S_IFMT) == _S_IFREG)
{
const long long here = ::_ftelli64(f);
if (here >= 0 && st.st_size > here)
{
return static_cast<unsigned long long>(st.st_size - here);
}
}
#elif defined(__unix__) || defined(__APPLE__)
struct stat st {};
if (::fstat(fileno(f), &st) == 0 && S_ISREG(st.st_mode))
{
const long here = std::ftell(f);
if (here >= 0 && st.st_size > here)
{
return static_cast<unsigned long long>(st.st_size - here);
}
}
#else
static_cast<void>(f);
#endif
return 0;
}
/// append the rest of a C stream: in blocks with fread, not character by /// append the rest of a C stream: in blocks with fread, not character by
/// character (the library's file adapter reads with fgetc); /// character (the library's file adapter reads with fgetc), and in one block
/// f is not null /// when it is a regular file of known size; f is not null
inline void append_file(std::string& buf, std::FILE* f) inline void append_file(std::string& buf, std::FILE* f)
{ {
// room for the rest of a regular file and the byte that shows its end:
// the file is then read in one block, without a reallocation and copy at
// each doubling of the string (only a hint: the loop below reads what is
// there)
const unsigned long long rest = file_rest(f);
if (rest > 0 && rest < buf.max_size() - buf.size() - 1)
{
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + 1);
}
for (;;) for (;;)
{ {
const std::size_t used = buf.size(); const std::size_t used = buf.size();
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096}); const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
buf.resize(used + room); buf.resize(used + room);
const std::size_t got = std::fread(&buf[used], 1, room, f); const std::size_t got = std::fread(&buf[used], 1, room, f);
buf.resize(used + got); buf.resize(used + got);
+27
View File
@@ -535,6 +535,33 @@ TEST_CASE("json_view")
CHECK_THROWS_AS(from_null = json_document::parse(static_cast<std::FILE*>(nullptr)), json::parse_error&); CHECK_THROWS_AS(from_null = json_document::parse(static_cast<std::FILE*>(nullptr)), json::parse_error&);
} }
// a regular file is read in one block, from its position to its end
std::FILE* tail_file = std::tmpfile(); // NOLINT(cppcoreguidelines-owning-memory)
if (tail_file != nullptr)
{
const std::string prefix = "garbage ";
CHECK(std::fwrite(prefix.data(), 1, prefix.size(), tail_file) == prefix.size());
CHECK(std::fwrite(text.data(), 1, text.size(), tail_file) == text.size());
CHECK(std::fseek(tail_file, static_cast<long>(prefix.size()), SEEK_SET) == 0);
#if defined(_WIN32) || defined(__unix__) || defined(__APPLE__)
CHECK(nlohmann::detail::view::file_rest(tail_file) == text.size());
#endif
const json_document from_tail = json_document::parse(tail_file);
CHECK(from_tail.source() == text);
CHECK(from_tail.root().materialize() == json::parse(text));
CHECK(nlohmann::detail::view::file_rest(tail_file) == 0);
CHECK(std::fclose(tail_file) == 0); // NOLINT(cppcoreguidelines-owning-memory)
}
// a stream is read from its position to its end as well, in one block
// when its buffer knows how much is left
std::istringstream tail_stream("garbage " + text);
tail_stream.seekg(8);
const json_document from_tail_stream = json_document::parse(tail_stream);
CHECK(from_tail_stream.source() == text);
CHECK(from_tail_stream.root().materialize() == json::parse(text));
CHECK(tail_stream.eof());
// a stream without a buffer is an empty input // a stream without a buffer is an empty input
std::istream no_buffer(nullptr); std::istream no_buffer(nullptr);
CHECK(json_document::parse(no_buffer, false).is_discarded()); CHECK(json_document::parse(no_buffer, false).is_discarded());
+5 -126
View File
@@ -22,7 +22,6 @@ 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>
@@ -712,122 +711,8 @@ 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")
@@ -906,16 +791,11 @@ 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 or binary32 numbers; everything else uses Grisu2 // Zmij needs binary64 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");
@@ -925,7 +805,7 @@ TEST_CASE("choice of the conversion")
CHECK(is_binary64<double>::value); CHECK(is_binary64<double>::value);
} }
SECTION("float and double: Zmij") SECTION("float: Grisu2, 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;
@@ -937,12 +817,11 @@ 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");
// 134218208.0f is one of the floats for which Grisu2 does not find the shortest digits constexpr float f = 1.1754944e-38f;
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);
CHECK(std::string(buf.data(), end) == "1.342182e+08"); const std::string dispatched(buf.data(), end);
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(std::string(buf.data(), end) == "1.3421821e+08"); CHECK(dispatched == std::string(buf.data(), end));
} }
SECTION("long double with the format of a double: Zmij") SECTION("long double with the format of a double: Zmij")