Compare commits

..
Author SHA1 Message Date
Niels Lohmann d8abf6a861 Check UTF-8 in strings 32 bytes at a time on CPUs with AVX2
The vector UTF-8 check of string runs in the lexer (vector_utf8_run) gets a
32-byte variant, compiled with a target attribute like the SSSE3 code and
chosen at run time where the CPU has AVX2 and the OS saves the YMM registers.
The CPU check sits inside the existing out-of-line 16-byte function, so it
adds no code to the lexer's string loop, and every translation unit has the
same definitions, whatever its flags. MSVC and GCC for Windows (GCC bug 54412)
keep the 16-byte code.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-25 21:41:41 +01:00
14 changed files with 517 additions and 351 deletions

No files matched your search

+1 -1
View File
@@ -40,7 +40,7 @@ header. See also the [macro overview page](../../features/macros.md).
- [**JSON_HAS_THREE_WAY_COMPARISON**](json_has_three_way_comparison.md) - control 3-way comparison support
- [**JSON_NO_AUTOMATIC_UDLS**](json_no_automatic_udls.md) - do not include the user-defined string literals (UDLs) automatically
- [**JSON_NO_IO**](json_no_io.md) - switch off functions relying on certain C++ I/O headers
- [**JSON_NO_SIMD**](json_no_simd.md) - use only portable code instead of vector instructions (SSE2, SSSE3, NEON)
- [**JSON_NO_SIMD**](json_no_simd.md) - use only portable code instead of vector instructions (SSE2, SSSE3, AVX2, NEON)
- [**JSON_NO_THREAD_LOCAL**](json_no_thread_local.md) - switch off the use of `thread_local` storage
- [**JSON_RECURSION_DEPTH_LIMIT**](json_recursion_depth_limit.md) - set how many nesting levels the operations on a value
recurse into on the call stack (default 128)
+3 -1
View File
@@ -28,7 +28,9 @@ By default, `#!cpp JSON_NO_SIMD` is not defined, and vector instructions are use
and writes the digits of floating-point numbers. The UTF-8 check of non-ASCII text needs SSSE3, which is not part
of x86-64: it is compiled for SSSE3 with a function attribute and used when the CPU has SSSE3 (every x86-64 CPU
since about 2011), else the portable check. Code compiled for SSSE3 anyway (e.g., with `-mssse3` or `-march=native`)
skips this check of the CPU. 32-bit x86 uses SSE2 for strings when the compiler targets it.
skips this check of the CPU. Where the CPU has AVX2, the UTF-8 check of strings takes 32 bytes at a time
(compiled with a function attribute as well; not with MSVC or GCC for Windows). 32-bit x86 uses SSE2 for strings
when the compiler targets it.
- **AArch64:** NEON, which every 64-bit Arm CPU has, checks UTF-8 text and long runs of plain string characters 16
bytes at a time, and writes the digits of floating-point numbers. With MSVC, only the floating-point digits use
NEON.
+1 -1
View File
@@ -176,7 +176,7 @@ See [full documentation of `JSON_NO_IO`](../api/macros/json_no_io.md).
## `JSON_NO_SIMD`
When defined, the library uses only portable code instead of vector instructions (SSE2, SSSE3, NEON) for scanning
When defined, the library uses only portable code instead of vector instructions (SSE2, SSSE3, AVX2, NEON) for scanning
strings and writing floating-point numbers. Results are the same either way. It is not defined by default.
See [full documentation of `JSON_NO_SIMD`](../api/macros/json_no_simd.md).
+2 -2
View File
@@ -109,8 +109,8 @@ follow the usual `std::streambuf` contract, and
[`JSON_DISABLE_UNLOCKED_FILE_IO`](../../api/macros/json_disable_unlocked_file_io.md) for programs in which another
thread must use the same `#!cpp FILE` object while it is parsed.
Where the target has them, strings are scanned with vector instructions: SSE2 on x86-64 (and SSSE3 for UTF-8 text, when
the CPU has it) and NEON on AArch64. [`JSON_NO_SIMD`](../../api/macros/json_no_simd.md) selects portable code instead,
Where the target has them, strings are scanned with vector instructions: SSE2 on x86-64 (and SSSE3 or AVX2 for UTF-8 text,
when the CPU has it) and NEON on AArch64. [`JSON_NO_SIMD`](../../api/macros/json_no_simd.md) selects portable code instead,
again without changing any result.
## SAX vs. DOM parsing
@@ -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.
- 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`.
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"
@@ -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
(`#!cpp float` is promoted to `#!cpp double`).
If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 or binary32 number, `dump` uses the
algorithm of Żmij, which produces the shortest representation that round-trips. Otherwise the `snprintf` fallback with
`max_digits10` digits is used.
If `#!cpp std::numeric_limits<NumberFloatType>` describes an IEEE 754 binary64 number, `dump` uses the algorithm of
Żmij, which produces the shortest representation that round-trips. For IEEE 754 binary32 numbers, it uses Grisu2,
which produces a short representation that round-trips. Otherwise the `snprintf` fallback with `max_digits10` digits is
used.
### Required for the binary formats
@@ -590,7 +591,7 @@ binary32 or binary64 field and have no encoding for `#!cpp long double`.
| Type | Support |
|--------------------------|-----------------------------------------------------------------------------------------------------------------------|
| `#!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 |
| 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 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/).
@@ -49,8 +49,8 @@ namespace detail
/*!
@brief implements binary to decimal floating-point conversion: the shortest
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
the Grisu2 algorithm for all other formats.
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
algorithm for all other formats.
The Grisu2 implementation is a slightly modified version of the reference
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
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
write_shortest(); binary32 numbers use it with format_buffer(), and all
others (e.g. the 80-bit long double of x87) use Grisu2.
These are the types the conversion of Zmij (see zmij.hpp) is used for; all
others (binary32, or a format the library does not know) use Grisu2.
*/
template<typename FloatType>
constexpr bool has_binary64_format() noexcept
@@ -1413,23 +1412,7 @@ constexpr bool has_binary64_format() noexcept
template<typename 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
/// 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()
/// a positive finite float (other than binary64): Grisu2 and format_buffer()
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
@@ -1483,79 +1466,32 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
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 double here, its bits are those of the double of the same value)
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, 1> /*binary64*/)
char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/)
{
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>
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, 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>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
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
+10 -31
View File
@@ -160,37 +160,22 @@ struct shortest_decimal
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
};
/// the bit layout of an IEEE 754 binary format: SigBits significand bits
/// (without the implicit bit) below ExpBits exponent bits
template<int SigBits, int ExpBits>
struct binary_format
{
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
/// The shortest decimal in the rounding interval of a positive finite double
/// 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 before it can be
/// converted without a multiplication by 10 first). Always inlined: GCC
/// otherwise calls it, and its result goes through memory.
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
{
constexpr int extra_shift = 9;
const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1);
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
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)
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)
{
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
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};
}
/// 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 detail
NLOHMANN_JSON_NAMESPACE_END
+181 -1
View File
@@ -79,6 +79,24 @@
#define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_SSSE3_TARGET
#endif
// The UTF-8 check of string runs (vector_utf8_run) also has a 32-byte variant
// for CPUs with AVX2 (most x86-64 CPUs since about 2015), compiled with a
// function attribute and chosen at run time inside the out-of-line 16-byte
// check, whatever the flags of the translation unit: the CPU check adds no code
// to the lexer's string loop, and every translation unit has the same
// definitions. Not with MSVC (not measured), and not with GCC for Windows,
// which does not align the stack for spilled AVX registers (GCC bug 54412).
#if JSON_SCAN_SSE2 && !defined(NLOHMANN_JSON_NO_TARGET_ATTRIBUTE) && !(defined(_WIN32) && !defined(__clang__)) && ((defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) && !defined(__cpp_modules)))
#ifndef NLOHMANN_JSON_CPUID_INCLUDED
#define NLOHMANN_JSON_CPUID_INCLUDED
#include <cpuid.h>
#endif
#include <immintrin.h>
#define JSON_SCAN_AVX2_DISPATCH 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_AVX2_TARGET __attribute__((target("avx2")))
#else
#define JSON_SCAN_AVX2_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#endif
#define JSON_SCAN_VECTOR (JSON_SCAN_NEON || JSON_SCAN_SSE2)
#define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH)
@@ -179,6 +197,55 @@ JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_ssse3() noexcept
}
#endif
/// whether the CPU has AVX2 (CPUID leaf 7, EBX bit 5) and the OS saves the
/// YMM registers (CPUID leaf 1, ECX bits 27 and 28; XCR0 bits 1 and 2); false
/// where the library has no AVX2 code
inline bool cpu_avx2() noexcept
{
#if JSON_SCAN_AVX2_DISPATCH
unsigned eax = 0;
unsigned ebx = 0;
unsigned ecx = 0;
unsigned edx = 0;
if (__get_cpuid_max(0, nullptr) < 7 || __get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0 || (ecx & (3u << 27u)) != (3u << 27u))
{
return false;
}
unsigned xcr0 = 0; // NOLINT(misc-const-correctness): written by the assembly
unsigned xcr0_high = 0; // NOLINT(misc-const-correctness)
__asm__ __volatile__("xgetbv" : "=a"(xcr0), "=d"(xcr0_high) : "c"(0)); // NOLINT(hicpp-no-assembler)
if ((xcr0 & 6u) != 6u)
{
return false;
}
__cpuid_count(7, 0, eax, ebx, ecx, edx);
return (ebx & (1u << 5u)) != 0;
#else
return false;
#endif
}
/// the answer of cpu_avx2(), asked once (0: not asked yet, 1: no, 2: yes; see
/// cpu_has_ssse3()); the tests store 1 to check the 16-byte code on CPUs with
/// AVX2, and 0 to ask again
inline std::atomic<int>& cpu_avx2_state() noexcept
{
static std::atomic<int> known{0};
return known;
}
/// whether the CPU has AVX2
JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_avx2() noexcept
{
int state = cpu_avx2_state().load(std::memory_order_relaxed);
if (JSON_HEDLEY_UNLIKELY(state == 0))
{
state = cpu_avx2() ? 2 : 1;
cpu_avx2_state().store(state, std::memory_order_relaxed);
}
return state == 2;
}
#if JSON_SCAN_VECTOR_UTF8
/// Tables of the UTF-8 check of J. Keiser and D. Lemire, "Validating UTF-8 In
/// Less Than One Instruction Per Byte" (2021), as in simdjson ("lookup4"): each
@@ -230,6 +297,112 @@ const std::array<std::uint8_t, 16> utf8_lookup4<Dummy>::byte_2_high =
}
};
#if JSON_SCAN_AVX2_DISPATCH
/// the errors of the UTF-8 check in 16 bytes @a in after @a prev (see
/// vector_utf8_run()), for the 32-byte functions
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m128i utf8_errors_avx2_16(const __m128i in, const __m128i prev, const __m128i t1h, const __m128i t1l, const __m128i t2h) noexcept
{
const __m128i nibble = _mm_set1_epi8(0x0F);
const __m128i prev1 = _mm_alignr_epi8(in, prev, 15);
const __m128i sc = _mm_and_si128(_mm_and_si128(_mm_shuffle_epi8(t1h, _mm_and_si128(_mm_srli_epi16(prev1, 4), nibble)),
_mm_shuffle_epi8(t1l, _mm_and_si128(prev1, nibble))),
_mm_shuffle_epi8(t2h, _mm_and_si128(_mm_srli_epi16(in, 4), nibble)));
const __m128i must23 = _mm_or_si128(_mm_subs_epu8(_mm_alignr_epi8(in, prev, 14), _mm_set1_epi8(0xE0 - 0x80)),
_mm_subs_epu8(_mm_alignr_epi8(in, prev, 13), _mm_set1_epi8(0xF0 - 0x80)));
return _mm_xor_si128(_mm_and_si128(must23, _mm_set1_epi8(static_cast<char>(-128))), sc);
}
/// the errors of the UTF-8 check in 32 bytes @a in after @a prev: as with 16
/// bytes, but the byte shifts work within each 16-byte lane, so the bytes
/// before each lane are put together first
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m256i utf8_errors_avx2_32(const __m256i in, const __m256i prev, const __m256i t1h, const __m256i t1l, const __m256i t2h) noexcept
{
const __m256i nibble = _mm256_set1_epi8(0x0F);
const __m256i before = _mm256_permute2x128_si256(prev, in, 0x21); // the upper half of prev, the lower half of in
const __m256i prev1 = _mm256_alignr_epi8(in, before, 15);
const __m256i sc = _mm256_and_si256(_mm256_and_si256(_mm256_shuffle_epi8(t1h, _mm256_and_si256(_mm256_srli_epi16(prev1, 4), nibble)),
_mm256_shuffle_epi8(t1l, _mm256_and_si256(prev1, nibble))),
_mm256_shuffle_epi8(t2h, _mm256_and_si256(_mm256_srli_epi16(in, 4), nibble)));
const __m256i must23 = _mm256_or_si256(_mm256_subs_epu8(_mm256_alignr_epi8(in, before, 14), _mm256_set1_epi8(0xE0 - 0x80)),
_mm256_subs_epu8(_mm256_alignr_epi8(in, before, 13), _mm256_set1_epi8(0xF0 - 0x80)));
return _mm256_xor_si256(_mm256_and_si256(must23, _mm256_set1_epi8(static_cast<char>(-128))), sc);
}
/// the quotes, backslashes, and control characters in 16 bytes (see vector_utf8_run())
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m128i string_specials_avx2_16(const __m128i in) noexcept
{
return _mm_or_si128(_mm_cmpeq_epi8(in, _mm_set1_epi8('\\')),
_mm_cmpeq_epi8(_mm_subs_epu8(_mm_xor_si128(in, _mm_set1_epi8(2)), _mm_set1_epi8(32)), _mm_setzero_si128()));
}
/// vector_utf8_run() with AVX2: 32 bytes per step, then one 16-byte step
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run_avx2(const unsigned char* p, const unsigned char* e, const unsigned char*& block_out) noexcept
{
using lookup = utf8_lookup4<>;
const unsigned char* block = p;
const __m128i t1h_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t1l_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_low.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t2h_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_2_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m256i t1h = _mm256_broadcastsi128_si256(t1h_16);
const __m256i t1l = _mm256_broadcastsi128_si256(t1l_16);
const __m256i t2h = _mm256_broadcastsi128_si256(t2h_16);
const __m256i zero = _mm256_setzero_si256();
__m256i prev = zero;
while (e - block >= 32)
{
const __m256i in = _mm256_loadu_si256(static_cast<const __m256i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void)
const __m256i special = _mm256_or_si256(_mm256_cmpeq_epi8(in, _mm256_set1_epi8('\\')),
_mm256_cmpeq_epi8(_mm256_subs_epu8(_mm256_xor_si256(in, _mm256_set1_epi8(2)), _mm256_set1_epi8(32)), zero));
const __m256i err = utf8_errors_avx2_32(in, prev, t1h, t1l, t2h);
const auto special_bits = static_cast<unsigned>(_mm256_movemask_epi8(special));
const auto err_bits = ~static_cast<unsigned>(_mm256_movemask_epi8(_mm256_cmpeq_epi8(err, zero)));
if (special_bits != 0)
{
// errors up to the special byte count (see vector_utf8_run()); for
// k = 31, 2u << k is 0 and the mask has all bits set
const auto k = static_cast<unsigned>(count_trailing_zeros(static_cast<std::uint64_t>(special_bits)));
if ((err_bits & ((2u << k) - 1u)) == 0)
{
block_out = block + k;
return true;
}
block_out = block;
return false;
}
if (err_bits != 0)
{
block_out = block;
return false;
}
prev = in;
block += 32;
}
if (e - block >= 16)
{
const __m128i in = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void)
const __m128i err = utf8_errors_avx2_16(in, _mm256_extracti128_si256(prev, 1), t1h_16, t1l_16, t2h_16);
const auto special_bits = static_cast<unsigned>(_mm_movemask_epi8(string_specials_avx2_16(in)));
const auto err_bits = ~static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(err, _mm_setzero_si128()))) & 0xFFFFu;
if (special_bits != 0)
{
const auto k = static_cast<unsigned>(count_trailing_zeros(static_cast<std::uint64_t>(special_bits)));
if ((err_bits & ((2u << k) - 1u)) == 0)
{
block_out = block + k;
return true;
}
}
else if (err_bits == 0)
{
block += 16;
}
}
block_out = block;
return false;
}
#endif
/*!
@brief the run of plain string bytes and well-formed UTF-8 at p (a character
boundary), 16 bytes per step
@@ -240,10 +413,17 @@ to it. Returns true with @a block at that byte; returns false with @a block at
the start of the 16 bytes where the check found ill-formed UTF-8 or where
fewer than 16 bytes are left, for the caller to finish one sequence at a time.
Out of line, so that no constants of the check occupy registers in the
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()), and
hands runs of 32 bytes or more to vector_utf8_run_avx2() where the CPU has AVX2.
*/
JSON_SCAN_SSSE3_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run(const unsigned char* p, const unsigned char* e, const unsigned char*& block_out) noexcept
{
#if JSON_SCAN_AVX2_DISPATCH
if (e - p >= 32 && cpu_has_avx2())
{
return vector_utf8_run_avx2(p, e, block_out);
}
#endif
using lookup = utf8_lookup4<>;
const unsigned char* block = p;
#if JSON_SCAN_NEON
@@ -28,6 +28,8 @@
#undef JSON_DTOA_NEON
#undef JSON_LITTLE_ENDIAN_TARGET
#undef JSON_BIG_ENDIAN_TARGET
#undef JSON_SCAN_AVX2_DISPATCH
#undef JSON_SCAN_AVX2_TARGET
#undef JSON_SCAN_NEON
#undef JSON_SCAN_SSE2
#undef JSON_SCAN_SSSE3
+204 -107
View File
@@ -12635,6 +12635,24 @@ NLOHMANN_JSON_NAMESPACE_END
#define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_SSSE3_TARGET
#endif
// The UTF-8 check of string runs (vector_utf8_run) also has a 32-byte variant
// for CPUs with AVX2 (most x86-64 CPUs since about 2015), compiled with a
// function attribute and chosen at run time inside the out-of-line 16-byte
// check, whatever the flags of the translation unit: the CPU check adds no code
// to the lexer's string loop, and every translation unit has the same
// definitions. Not with MSVC (not measured), and not with GCC for Windows,
// which does not align the stack for spilled AVX registers (GCC bug 54412).
#if JSON_SCAN_SSE2 && !defined(NLOHMANN_JSON_NO_TARGET_ATTRIBUTE) && !(defined(_WIN32) && !defined(__clang__)) && ((defined(__clang__) && __clang_major__ >= 4) || (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) && !defined(__cpp_modules)))
#ifndef NLOHMANN_JSON_CPUID_INCLUDED
#define NLOHMANN_JSON_CPUID_INCLUDED
#include <cpuid.h>
#endif
#include <immintrin.h>
#define JSON_SCAN_AVX2_DISPATCH 1 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_AVX2_TARGET __attribute__((target("avx2")))
#else
#define JSON_SCAN_AVX2_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#endif
#define JSON_SCAN_VECTOR (JSON_SCAN_NEON || JSON_SCAN_SSE2)
#define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH)
@@ -12735,6 +12753,55 @@ JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_ssse3() noexcept
}
#endif
/// whether the CPU has AVX2 (CPUID leaf 7, EBX bit 5) and the OS saves the
/// YMM registers (CPUID leaf 1, ECX bits 27 and 28; XCR0 bits 1 and 2); false
/// where the library has no AVX2 code
inline bool cpu_avx2() noexcept
{
#if JSON_SCAN_AVX2_DISPATCH
unsigned eax = 0;
unsigned ebx = 0;
unsigned ecx = 0;
unsigned edx = 0;
if (__get_cpuid_max(0, nullptr) < 7 || __get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0 || (ecx & (3u << 27u)) != (3u << 27u))
{
return false;
}
unsigned xcr0 = 0; // NOLINT(misc-const-correctness): written by the assembly
unsigned xcr0_high = 0; // NOLINT(misc-const-correctness)
__asm__ __volatile__("xgetbv" : "=a"(xcr0), "=d"(xcr0_high) : "c"(0)); // NOLINT(hicpp-no-assembler)
if ((xcr0 & 6u) != 6u)
{
return false;
}
__cpuid_count(7, 0, eax, ebx, ecx, edx);
return (ebx & (1u << 5u)) != 0;
#else
return false;
#endif
}
/// the answer of cpu_avx2(), asked once (0: not asked yet, 1: no, 2: yes; see
/// cpu_has_ssse3()); the tests store 1 to check the 16-byte code on CPUs with
/// AVX2, and 0 to ask again
inline std::atomic<int>& cpu_avx2_state() noexcept
{
static std::atomic<int> known{0};
return known;
}
/// whether the CPU has AVX2
JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_avx2() noexcept
{
int state = cpu_avx2_state().load(std::memory_order_relaxed);
if (JSON_HEDLEY_UNLIKELY(state == 0))
{
state = cpu_avx2() ? 2 : 1;
cpu_avx2_state().store(state, std::memory_order_relaxed);
}
return state == 2;
}
#if JSON_SCAN_VECTOR_UTF8
/// Tables of the UTF-8 check of J. Keiser and D. Lemire, "Validating UTF-8 In
/// Less Than One Instruction Per Byte" (2021), as in simdjson ("lookup4"): each
@@ -12786,6 +12853,112 @@ const std::array<std::uint8_t, 16> utf8_lookup4<Dummy>::byte_2_high =
}
};
#if JSON_SCAN_AVX2_DISPATCH
/// the errors of the UTF-8 check in 16 bytes @a in after @a prev (see
/// vector_utf8_run()), for the 32-byte functions
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m128i utf8_errors_avx2_16(const __m128i in, const __m128i prev, const __m128i t1h, const __m128i t1l, const __m128i t2h) noexcept
{
const __m128i nibble = _mm_set1_epi8(0x0F);
const __m128i prev1 = _mm_alignr_epi8(in, prev, 15);
const __m128i sc = _mm_and_si128(_mm_and_si128(_mm_shuffle_epi8(t1h, _mm_and_si128(_mm_srli_epi16(prev1, 4), nibble)),
_mm_shuffle_epi8(t1l, _mm_and_si128(prev1, nibble))),
_mm_shuffle_epi8(t2h, _mm_and_si128(_mm_srli_epi16(in, 4), nibble)));
const __m128i must23 = _mm_or_si128(_mm_subs_epu8(_mm_alignr_epi8(in, prev, 14), _mm_set1_epi8(0xE0 - 0x80)),
_mm_subs_epu8(_mm_alignr_epi8(in, prev, 13), _mm_set1_epi8(0xF0 - 0x80)));
return _mm_xor_si128(_mm_and_si128(must23, _mm_set1_epi8(static_cast<char>(-128))), sc);
}
/// the errors of the UTF-8 check in 32 bytes @a in after @a prev: as with 16
/// bytes, but the byte shifts work within each 16-byte lane, so the bytes
/// before each lane are put together first
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m256i utf8_errors_avx2_32(const __m256i in, const __m256i prev, const __m256i t1h, const __m256i t1l, const __m256i t2h) noexcept
{
const __m256i nibble = _mm256_set1_epi8(0x0F);
const __m256i before = _mm256_permute2x128_si256(prev, in, 0x21); // the upper half of prev, the lower half of in
const __m256i prev1 = _mm256_alignr_epi8(in, before, 15);
const __m256i sc = _mm256_and_si256(_mm256_and_si256(_mm256_shuffle_epi8(t1h, _mm256_and_si256(_mm256_srli_epi16(prev1, 4), nibble)),
_mm256_shuffle_epi8(t1l, _mm256_and_si256(prev1, nibble))),
_mm256_shuffle_epi8(t2h, _mm256_and_si256(_mm256_srli_epi16(in, 4), nibble)));
const __m256i must23 = _mm256_or_si256(_mm256_subs_epu8(_mm256_alignr_epi8(in, before, 14), _mm256_set1_epi8(0xE0 - 0x80)),
_mm256_subs_epu8(_mm256_alignr_epi8(in, before, 13), _mm256_set1_epi8(0xF0 - 0x80)));
return _mm256_xor_si256(_mm256_and_si256(must23, _mm256_set1_epi8(static_cast<char>(-128))), sc);
}
/// the quotes, backslashes, and control characters in 16 bytes (see vector_utf8_run())
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_ALWAYS_INLINE __m128i string_specials_avx2_16(const __m128i in) noexcept
{
return _mm_or_si128(_mm_cmpeq_epi8(in, _mm_set1_epi8('\\')),
_mm_cmpeq_epi8(_mm_subs_epu8(_mm_xor_si128(in, _mm_set1_epi8(2)), _mm_set1_epi8(32)), _mm_setzero_si128()));
}
/// vector_utf8_run() with AVX2: 32 bytes per step, then one 16-byte step
JSON_SCAN_AVX2_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run_avx2(const unsigned char* p, const unsigned char* e, const unsigned char*& block_out) noexcept
{
using lookup = utf8_lookup4<>;
const unsigned char* block = p;
const __m128i t1h_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t1l_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_low.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t2h_16 = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_2_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m256i t1h = _mm256_broadcastsi128_si256(t1h_16);
const __m256i t1l = _mm256_broadcastsi128_si256(t1l_16);
const __m256i t2h = _mm256_broadcastsi128_si256(t2h_16);
const __m256i zero = _mm256_setzero_si256();
__m256i prev = zero;
while (e - block >= 32)
{
const __m256i in = _mm256_loadu_si256(static_cast<const __m256i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void)
const __m256i special = _mm256_or_si256(_mm256_cmpeq_epi8(in, _mm256_set1_epi8('\\')),
_mm256_cmpeq_epi8(_mm256_subs_epu8(_mm256_xor_si256(in, _mm256_set1_epi8(2)), _mm256_set1_epi8(32)), zero));
const __m256i err = utf8_errors_avx2_32(in, prev, t1h, t1l, t2h);
const auto special_bits = static_cast<unsigned>(_mm256_movemask_epi8(special));
const auto err_bits = ~static_cast<unsigned>(_mm256_movemask_epi8(_mm256_cmpeq_epi8(err, zero)));
if (special_bits != 0)
{
// errors up to the special byte count (see vector_utf8_run()); for
// k = 31, 2u << k is 0 and the mask has all bits set
const auto k = static_cast<unsigned>(count_trailing_zeros(static_cast<std::uint64_t>(special_bits)));
if ((err_bits & ((2u << k) - 1u)) == 0)
{
block_out = block + k;
return true;
}
block_out = block;
return false;
}
if (err_bits != 0)
{
block_out = block;
return false;
}
prev = in;
block += 32;
}
if (e - block >= 16)
{
const __m128i in = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void)
const __m128i err = utf8_errors_avx2_16(in, _mm256_extracti128_si256(prev, 1), t1h_16, t1l_16, t2h_16);
const auto special_bits = static_cast<unsigned>(_mm_movemask_epi8(string_specials_avx2_16(in)));
const auto err_bits = ~static_cast<unsigned>(_mm_movemask_epi8(_mm_cmpeq_epi8(err, _mm_setzero_si128()))) & 0xFFFFu;
if (special_bits != 0)
{
const auto k = static_cast<unsigned>(count_trailing_zeros(static_cast<std::uint64_t>(special_bits)));
if ((err_bits & ((2u << k) - 1u)) == 0)
{
block_out = block + k;
return true;
}
}
else if (err_bits == 0)
{
block += 16;
}
}
block_out = block;
return false;
}
#endif
/*!
@brief the run of plain string bytes and well-formed UTF-8 at p (a character
boundary), 16 bytes per step
@@ -12796,10 +12969,17 @@ to it. Returns true with @a block at that byte; returns false with @a block at
the start of the 16 bytes where the check found ill-formed UTF-8 or where
fewer than 16 bytes are left, for the caller to finish one sequence at a time.
Out of line, so that no constants of the check occupy registers in the
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()), and
hands runs of 32 bytes or more to vector_utf8_run_avx2() where the CPU has AVX2.
*/
JSON_SCAN_SSSE3_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run(const unsigned char* p, const unsigned char* e, const unsigned char*& block_out) noexcept
{
#if JSON_SCAN_AVX2_DISPATCH
if (e - p >= 32 && cpu_has_avx2())
{
return vector_utf8_run_avx2(p, e, block_out);
}
#endif
using lookup = utf8_lookup4<>;
const unsigned char* block = p;
#if JSON_SCAN_NEON
@@ -36041,37 +36221,22 @@ struct shortest_decimal
bool has_digit; ///< whether the shortest decimal is integral * 10 + digit
};
/// the bit layout of an IEEE 754 binary format: SigBits significand bits
/// (without the implicit bit) below ExpBits exponent bits
template<int SigBits, int ExpBits>
struct binary_format
{
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
/// The shortest decimal in the rounding interval of a positive finite double
/// 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 before it can be
/// converted without a multiplication by 10 first). Always inlined: GCC
/// otherwise calls it, and its result goes through memory.
JSON_HEDLEY_ALWAYS_INLINE shortest_decimal to_shortest(std::uint64_t bits) noexcept
{
constexpr int extra_shift = 9;
const auto raw_exp = static_cast<int>((bits >> Format::sig_bits) & Format::exp_mask);
std::uint64_t bin_sig = bits & ((std::uint64_t{1} << Format::sig_bits) - 1);
const auto raw_exp = static_cast<int>((bits >> 52u) & 0x7FFu);
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)
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)
{
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
const int dec_exp = ((bin_exp * 315653) - (regular ? 0 : 131072)) >> 20;
@@ -36113,12 +36278,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};
}
/// 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 detail
NLOHMANN_JSON_NAMESPACE_END
@@ -36132,8 +36291,8 @@ namespace detail
/*!
@brief implements binary to decimal floating-point conversion: the shortest
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 and binary32 numbers, and
the Grisu2 algorithm for all other formats.
digits of Zmij (see zmij.hpp) for IEEE 754 binary64 numbers, and the Grisu2
algorithm for all other formats.
The Grisu2 implementation is a slightly modified version of the reference
implementation which may be obtained from
@@ -37480,9 +37639,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
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
write_shortest(); binary32 numbers use it with format_buffer(), and all
others (e.g. the 80-bit long double of x87) use Grisu2.
These are the types the conversion of Zmij (see zmij.hpp) is used for; all
others (binary32, or a format the library does not know) use Grisu2.
*/
template<typename FloatType>
constexpr bool has_binary64_format() noexcept
@@ -37496,23 +37654,7 @@ constexpr bool has_binary64_format() noexcept
template<typename 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
/// 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()
/// a positive finite float (other than binary64): Grisu2 and format_buffer()
template<typename FloatType>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
@@ -37566,79 +37708,32 @@ char* write_positive_zmij(char* first, const char* last, FloatType value)
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 double here, its bits are those of the double of the same value)
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, 1> /*binary64*/)
char* write_positive(char* first, const char* last, FloatType value, std::true_type /*is_binary64*/)
{
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>
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, 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>
JSON_HEDLEY_NON_NULL(1, 2)
JSON_HEDLEY_RETURNS_NON_NULL
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
@@ -48898,6 +48993,8 @@ struct formatter<nlohmann::NLOHMANN_BASIC_JSON_TPL, char> // NOLINT(cert-dcl58-c
#undef JSON_DTOA_NEON
#undef JSON_LITTLE_ENDIAN_TARGET
#undef JSON_BIG_ENDIAN_TARGET
#undef JSON_SCAN_AVX2_DISPATCH
#undef JSON_SCAN_AVX2_TARGET
#undef JSON_SCAN_NEON
#undef JSON_SCAN_SSE2
#undef JSON_SCAN_SSSE3
+89
View File
@@ -2044,6 +2044,95 @@ TEST_CASE("string scanning kernels")
CHECK(nlohmann::detail::read_eight_bytes(reinterpret_cast<const char*>(bytes.data()) + 3) == 0x0B0A090807060504u);
}
TEST_CASE("vector UTF-8 check with and without AVX2")
{
// on x86-64 CPUs with AVX2, the UTF-8 check takes 32 bytes per step; it
// must stop where the 16-byte check (and the byte-wise check) stops, for
// every piece at every position of every block, and both are tested there
const auto reference_bulk_run = [](const unsigned char* data, std::size_t n)
{
std::size_t i = 0;
while (i < n)
{
if (data[i] < 0x80u)
{
if (nlohmann::detail::is_string_special(data[i]))
{
break;
}
++i;
continue;
}
const std::size_t seq = nlohmann::detail::validate_one_utf8(data + i, n - i);
if (seq == 0)
{
break;
}
i += seq;
}
return i;
};
const std::vector<std::string> backgrounds = {"x", "\xC3\xA9", "\xE6\x97\xA5", "\xF0\x9F\x98\x80"};
const std::vector<std::string> pieces =
{
"", "\"", "\\", "\n", "\xC3\xA4", "\xE2\x82\xAC", "\xF0\x9F\x98\x80", "\xED\x9F\xBF",
"\x80", "\xC0\x80", "\xC3", "\xE2\x82", "\xED\xA0\x80", "\xF4\x90\x80\x80", "\xFF", "\"\xFF", "\xFF\"",
};
const auto check_all = [&]()
{
std::size_t checked = 0;
for (const auto& background : backgrounds)
{
std::string filler;
while (filler.size() < 100)
{
filler += background;
}
for (std::size_t length = 0; length <= 80; ++length)
{
for (std::size_t pos = 0; pos <= length; ++pos)
{
for (const auto& piece : pieces)
{
const std::string text = filler.substr(0, pos) + piece + filler.substr(pos, length - pos);
const auto* data = reinterpret_cast<const unsigned char*>(text.data()); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
const std::size_t run = nlohmann::detail::scalar_string_bulk_run(data, text.size());
const bool valid = nlohmann::detail::valid_utf8_string(data, text.size());
if (run != reference_bulk_run(data, text.size()) || valid != (nlohmann::detail::valid_utf8_prefix(data, text.size()) == text.size()))
{
CAPTURE(text)
CHECK(run == reference_bulk_run(data, text.size()));
CHECK(valid == (nlohmann::detail::valid_utf8_prefix(data, text.size()) == text.size()));
}
++checked;
}
}
}
}
// (one CHECK per string would make the test ten times slower)
CHECK(checked == backgrounds.size() * pieces.size() * 81 * 82 / 2);
};
// the answer of the CPU check is kept (always "no" where the library has
// no AVX2 code)
nlohmann::detail::cpu_avx2_state().store(0);
CHECK(nlohmann::detail::cpu_has_avx2() == nlohmann::detail::cpu_avx2());
CHECK(nlohmann::detail::cpu_avx2_state().load() == (nlohmann::detail::cpu_avx2() ? 2 : 1));
SECTION("16 bytes per step")
{
nlohmann::detail::cpu_avx2_state().store(1);
check_all();
nlohmann::detail::cpu_avx2_state().store(0);
}
SECTION("the widest vectors of the CPU")
{
check_all();
}
}
TEST_CASE("find_ascii_copyable_run agrees with is_ascii_copyable for every byte")
{
// the SWAR mask in find_ascii_copyable_run() encodes the predicate a
+5 -126
View File
@@ -22,7 +22,6 @@ using nlohmann::detail::bit_cast;
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <map>
#include <random>
#include <string>
#include <utility>
@@ -712,122 +711,8 @@ void check_shortest(double v)
CHECK(digits_and_exponent(std::string(std_text.data(), r.ptr)) == de);
#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
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")
{
SECTION("powers of ten")
@@ -906,16 +791,11 @@ TEST_CASE("shortest digits of doubles")
TEST_CASE("choice of the conversion")
{
using nlohmann::detail::dtoa_impl::is_binary64;
using nlohmann::detail::dtoa_impl::float_conversion;
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(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),
"double is binary64 where it is IEEE 754 with 53 digits");
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);
}
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
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);
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 = 134218208.0f;
constexpr float f = 1.1754944e-38f;
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);
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")