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
11 changed files with 178 additions and 472 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_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_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_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, AVX2, NEON) - [**JSON_NO_SIMD**](json_no_simd.md) - use only portable code instead of vector instructions (SSE2, SSSE3, NEON)
- [**JSON_NO_THREAD_LOCAL**](json_no_thread_local.md) - switch off the use of `thread_local` storage - [**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 - [**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) recurse into on the call stack (default 128)
+1 -3
View File
@@ -28,9 +28,7 @@ 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 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 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`) 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. Where the CPU has AVX2, the UTF-8 check of strings takes 32 bytes at a time skips this check of the CPU. 32-bit x86 uses SSE2 for strings when the compiler targets it.
(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 - **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 bytes at a time, and writes the digits of floating-point numbers. With MSVC, only the floating-point digits use
NEON. 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` ## `JSON_NO_SIMD`
When defined, the library uses only portable code instead of vector instructions (SSE2, SSSE3, AVX2, NEON) for scanning When defined, the library uses only portable code instead of vector instructions (SSE2, SSSE3, NEON) for scanning
strings and writing floating-point numbers. Results are the same either way. It is not defined by default. 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). 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 [`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. 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 or AVX2 for UTF-8 text, Where the target has them, strings are scanned with vector instructions: SSE2 on x86-64 (and SSSE3 for UTF-8 text, when
when the CPU has it) and NEON on AArch64. [`JSON_NO_SIMD`](../../api/macros/json_no_simd.md) selects portable code instead, 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. again without changing any result.
## SAX vs. DOM parsing ## SAX vs. DOM parsing
+1 -181
View File
@@ -79,24 +79,6 @@
#define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) #define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_SSSE3_TARGET #define JSON_SCAN_SSSE3_TARGET
#endif #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 (JSON_SCAN_NEON || JSON_SCAN_SSE2)
#define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH) #define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH)
@@ -197,55 +179,6 @@ JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_ssse3() noexcept
} }
#endif #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 #if JSON_SCAN_VECTOR_UTF8
/// Tables of the UTF-8 check of J. Keiser and D. Lemire, "Validating UTF-8 In /// 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 /// Less Than One Instruction Per Byte" (2021), as in simdjson ("lookup4"): each
@@ -297,112 +230,6 @@ 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 @brief the run of plain string bytes and well-formed UTF-8 at p (a character
boundary), 16 bytes per step boundary), 16 bytes per step
@@ -413,17 +240,10 @@ 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 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. 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 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()), and caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
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 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<>; using lookup = utf8_lookup4<>;
const unsigned char* block = p; const unsigned char* block = p;
#if JSON_SCAN_NEON #if JSON_SCAN_NEON
@@ -28,8 +28,6 @@
#undef JSON_DTOA_NEON #undef JSON_DTOA_NEON
#undef JSON_LITTLE_ENDIAN_TARGET #undef JSON_LITTLE_ENDIAN_TARGET
#undef JSON_BIG_ENDIAN_TARGET #undef JSON_BIG_ENDIAN_TARGET
#undef JSON_SCAN_AVX2_DISPATCH
#undef JSON_SCAN_AVX2_TARGET
#undef JSON_SCAN_NEON #undef JSON_SCAN_NEON
#undef JSON_SCAN_SSE2 #undef JSON_SCAN_SSE2
#undef JSON_SCAN_SSSE3 #undef JSON_SCAN_SSSE3
+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);
+1 -183
View File
@@ -12635,24 +12635,6 @@ NLOHMANN_JSON_NAMESPACE_END
#define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum) #define JSON_SCAN_SSSE3_DISPATCH 0 // NOLINT(cppcoreguidelines-macro-to-enum,modernize-macro-to-enum)
#define JSON_SCAN_SSSE3_TARGET #define JSON_SCAN_SSSE3_TARGET
#endif #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 (JSON_SCAN_NEON || JSON_SCAN_SSE2)
#define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH) #define JSON_SCAN_VECTOR_UTF8 (JSON_SCAN_NEON || JSON_SCAN_SSSE3 || JSON_SCAN_SSSE3_DISPATCH)
@@ -12753,55 +12735,6 @@ JSON_HEDLEY_ALWAYS_INLINE bool cpu_has_ssse3() noexcept
} }
#endif #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 #if JSON_SCAN_VECTOR_UTF8
/// Tables of the UTF-8 check of J. Keiser and D. Lemire, "Validating UTF-8 In /// 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 /// Less Than One Instruction Per Byte" (2021), as in simdjson ("lookup4"): each
@@ -12853,112 +12786,6 @@ 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 @brief the run of plain string bytes and well-formed UTF-8 at p (a character
boundary), 16 bytes per step boundary), 16 bytes per step
@@ -12969,17 +12796,10 @@ 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 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. 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 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()), and caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
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 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<>; using lookup = utf8_lookup4<>;
const unsigned char* block = p; const unsigned char* block = p;
#if JSON_SCAN_NEON #if JSON_SCAN_NEON
@@ -48993,8 +48813,6 @@ struct formatter<nlohmann::NLOHMANN_BASIC_JSON_TPL, char> // NOLINT(cert-dcl58-c
#undef JSON_DTOA_NEON #undef JSON_DTOA_NEON
#undef JSON_LITTLE_ENDIAN_TARGET #undef JSON_LITTLE_ENDIAN_TARGET
#undef JSON_BIG_ENDIAN_TARGET #undef JSON_BIG_ENDIAN_TARGET
#undef JSON_SCAN_AVX2_DISPATCH
#undef JSON_SCAN_AVX2_TARGET
#undef JSON_SCAN_NEON #undef JSON_SCAN_NEON
#undef JSON_SCAN_SSE2 #undef JSON_SCAN_SSE2
#undef JSON_SCAN_SSSE3 #undef JSON_SCAN_SSSE3
+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);
-89
View File
@@ -2044,95 +2044,6 @@ TEST_CASE("string scanning kernels")
CHECK(nlohmann::detail::read_eight_bytes(reinterpret_cast<const char*>(bytes.data()) + 3) == 0x0B0A090807060504u); 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") 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 // the SWAR mask in find_ascii_copyable_run() encodes the predicate a
+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());