Compare commits

..
Author SHA1 Message Date
Niels Lohmann d59b7e2728 Address review comments on the JSON variants page
Align the tables, say that json_document does not keep comments either,
describe which duplicate key parse() and json_view keep, and fix the
wording of the JSON5, converters and other-standards sentences.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-24 19:01:39 +01:00
Niels Lohmann 91a03caa72 Add a documentation page on JSON variants
Add features/parsing/json_variants.md, which lists formats related to JSON
and how much of each the library supports: JSONC, JWCC/HuJSON, JSON5,
configuration languages such as Hjson and HOCON, JSON Lines/NDJSON,
concatenated JSON, JSON text sequences (RFC 7464), I-JSON (RFC 7493), the
JSON Canonicalization Scheme (RFC 8785), NaN/Infinity, and conventions on
top of JSON. Link it from the parsing overview, the features index, the
comments, trailing commas and JSON Lines pages, and the ecosystem page.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-24 10:02:13 +01:00
15 changed files with 206 additions and 464 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, 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_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)
+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
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. 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.
skips this check of the CPU. 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.
+3
View File
@@ -34,6 +34,9 @@ For products, applications, and organizations that use the library, see [Custome
## Format converters
For the formats related to JSON that the library reads itself, such as JSONC or JSON Lines, see
[JSON variants](../features/parsing/json_variants.md).
- [**tojson**](https://github.com/mircodz/tojson), a header-only converter between YAML/XML documents and
`nlohmann::json`
- [**json2xml**](https://github.com/testillano/json2xml), a header-only converter from `nlohmann::json` to XML for
+3 -1
View File
@@ -11,7 +11,8 @@ This library does not support comments *by default*. It does so for three reason
3. It is dangerous for interoperability if some libraries add comment support while others do not. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this.
However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support.
However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support. See [JSON variants](parsing/json_variants.md) for a
comparison with these and other formats.
For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html).
@@ -43,5 +44,6 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Trailing Commas](trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
+2
View File
@@ -18,6 +18,8 @@ C++ types, and finally serialize it again.
- [Editable documents](json_view/editing.md) — modify a parsed document without building a `json` tree.
- [Images](json_view/images.md) — save a parsed document and load it again without parsing it.
- [Comments](comments.md) and [trailing commas](trailing_commas.md) — opt-in relaxations of the JSON grammar.
- [JSON variants](parsing/json_variants.md) — which of JSONC, JSON5, JSON Lines, I-JSON, and other formats related to
JSON the library supports.
## Accessing and modifying values
+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, 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.
See [full documentation of `JSON_NO_SIMD`](../api/macros/json_no_simd.md).
+5 -3
View File
@@ -45,7 +45,8 @@ that arrives in chunks or contains several values is covered in
[Large, streamed, and partial input](large_and_partial_input.md).
By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the `parse`
function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md).
function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md). See
[JSON variants](json_variants.md) for how much of JSONC, JSON5, and other formats related to JSON the library supports.
[`basic_json_document::parse`](../../api/basic_json_document/parse.md) accepts the same inputs with the same options,
but keeps the result in a document rather than in a `basic_json` value; see
@@ -109,8 +110,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 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,
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,
again without changing any result.
## SAX vs. DOM parsing
@@ -169,6 +170,7 @@ options.
- [`accept`](../../api/basic_json/accept.md) - check if the input is valid JSON
- [`sax_parse`](../../api/basic_json/sax_parse.md) - generate SAX events
- [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [JSON variants](json_variants.md) - JSONC, JSON5, JSON text sequences, I-JSON, and other formats related to JSON
- [Large, streamed, and partial input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [parser callbacks](parser_callbacks.md) - influence the parsing by a callback function
- [SAX interface](sax_interface.md) - implement a custom SAX handler
@@ -68,5 +68,6 @@ JSON Lines input with more than one value is treated as invalid JSON by the [`pa
- [Parsing](index.md) - overview of the parsing functions
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [JSON variants](json_variants.md) - NDJSON, JSON text sequences, and other formats related to JSON
- [`parse`](../../api/basic_json/parse.md) - deserialize from a compatible input
- [`operator>>`](../../api/operator_gtgt.md) - deserialize from stream
@@ -0,0 +1,185 @@
# JSON Variants
This library reads and writes JSON as defined by [RFC 8259](https://tools.ietf.org/html/rfc8259) and
[ECMA-404](https://ecma-international.org/publications-and-standards/standards/ecma-404/). Many other formats are
built around JSON: some relax its syntax (for example, to allow comments), some put several JSON values into one
stream, some restrict it further, and some give certain JSON values a special meaning. This page lists the common
ones and how much of each the library supports.
## Overview
| Variant | Kind | Support |
|------------------------------------------------------------------|----------------------------|-----------------------------------------------------------------------------------------------------------|
| [JSON](https://tools.ietf.org/html/rfc8259) (RFC 8259, ECMA-404) | the standard | :white_check_mark: default |
| [JSONC](https://jsonc.org) | relaxed syntax | :white_check_mark: with `ignore_comments` (and `ignore_trailing_commas` where trailing commas are wanted) |
| [JWCC](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html) / [HuJSON](https://github.com/tailscale/hujson) | relaxed syntax | :white_check_mark: with `ignore_comments` and `ignore_trailing_commas` |
| [JSON5](https://spec.json5.org) | relaxed syntax | :warning: comments and trailing commas only |
| [Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md), [UCL](https://github.com/vstakhov/libucl), SJSON | configuration languages | :x: only input that is JSON plus `//`/`/* */` comments and trailing commas |
| [YAML](https://yaml.org), [Amazon Ion](https://amazon-ion.github.io/ion-docs/) | other languages | :x: see [converters](#other-languages-and-converters) |
| [JSON Lines](https://jsonlines.org), [NDJSON](https://github.com/ndjson/ndjson-spec) | several values | :white_check_mark: line by line, see [JSON Lines](json_lines.md) |
| concatenated JSON | several values | :white_check_mark: with `operator>>`, see [Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream) |
| [JSON text sequences](https://www.rfc-editor.org/rfc/rfc7464) (RFC 7464) | several values | :warning: split the input yourself, see [below](#json-text-sequences-rfc-7464) |
| [I-JSON](https://www.rfc-editor.org/rfc/rfc7493) (RFC 7493) | restricted profile | :warning: most rules are enforced, see [below](#i-json-rfc-7493) |
| [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (RFC 8785) | restricted output | :x: `dump()` output is close, but not canonical |
| `NaN`, `Infinity` (JavaScript, Python) | number extension | :x: rejected by the parser, written as `null` |
| [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org), [GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), [MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) | conventions on top of JSON | :white_check_mark: parsed as plain JSON; interpreting them is up to you |
Whatever was parsed, [`dump`](../../api/basic_json/dump.md) always writes standard JSON: no comments, no trailing
commas, and no `NaN` or `Infinity`.
## Standard JSON
By default, [`parse`](../../api/basic_json/parse.md) accepts exactly the JSON grammar of RFC 8259, including values
other than objects and arrays at the top level (such as `#!json 42` or `#!json "text"`). A UTF-8 byte order mark at the
very start of the input is skipped; anywhere else it is a parse error.
## Relaxed syntax
### JSONC and JWCC
**JSONC** ("JSON with comments", used, for example, by Visual Studio Code's `settings.json` and `devcontainer.json`)
adds `//` and `/* */` comments to JSON. Block comments do not nest. The [JSONC specification](https://jsonc.org) lets
parsers decide whether they accept trailing commas. **JWCC** ("JSON with commas and comments") adds the same comments
and always allows a single trailing comma in arrays and objects; [HuJSON](https://github.com/tailscale/hujson) is
Tailscale's implementation of it.
Both are fully supported by passing `ignore_comments` and `ignore_trailing_commas` to `parse`:
```cpp
json j = json::parse(input,
/* callback */ nullptr,
/* allow_exceptions */ true,
/* ignore_comments */ true,
/* ignore_trailing_commas */ true);
```
Comments are treated as whitespace and are not kept, so they are lost when the value is written again. This also holds
for a [`json_document`](../../api/basic_json_document/index.md): [`dump()`](../../api/basic_json_view/dump.md) of its
root view writes the same text as `dump()` of the parsed `json` value, even though the document keeps the source text
with the comments. See
[Comments](../comments.md) and [Trailing commas](../trailing_commas.md) for the details. The .NET options
`JsonCommentHandling.Skip` and `AllowTrailingCommas` accept the same syntax.
### JSON5
[JSON5](https://spec.json5.org) is a superset of JSON that follows the syntax of ECMAScript 5 object literals. Besides
comments and trailing commas, it allows unquoted keys, single-quoted strings, line continuations in strings, more
escape sequences (`\v`, `\0`, `\xHH`, ...), hexadecimal numbers, a leading `+`, a leading or trailing decimal point, and
`Infinity` and `NaN`. With the two options above, the library accepts JSON5 documents that only use comments and
trailing commas; using any of the other extensions is a parse error.
### Configuration languages
[Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md),
[UCL](https://github.com/vstakhov/libucl), and SJSON (from the Bitsquid/Stingray game engine) are configuration
languages that accept JSON but go much further: `#` comments, unquoted keys and values, `=` instead of `:`, optional
commas and braces, multiline strings, and, in HOCON and UCL, includes and variable substitutions. The library does not
support these extensions. A `#` comment in particular is always a parse error, even with `ignore_comments`.
### Other languages and converters
[YAML](https://yaml.org) and the text format of [Amazon Ion](https://amazon-ion.github.io/ion-docs/) are separate
languages with their own data models, and the library does not read them. The [Ecosystem](../../community/ecosystem.md)
page lists projects that convert YAML or XML to and from `nlohmann::json`.
## Several values in one input
`parse` reads exactly one value and reports anything after it as an error. Several common formats combine many values
into one input:
- **[JSON Lines](https://jsonlines.org)** and **[NDJSON](https://github.com/ndjson/ndjson-spec)** put one value on each
line. Read them line by line, as shown on the [JSON Lines](json_lines.md) page. The two formats differ in one detail:
JSON Lines does not allow empty lines, while NDJSON parsers may skip them. Passing an empty line to `parse` is an
error, so skip empty lines yourself if you read NDJSON.
- **Concatenated JSON** puts values directly after each other, optionally separated by whitespace. Read them with
[`operator>>`](../../api/operator_gtgt.md), as shown in
[Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream).
### JSON text sequences (RFC 7464)
A [JSON text sequence](https://www.rfc-editor.org/rfc/rfc7464) (media type `application/json-seq`) starts every value
with the ASCII record separator (RS, `0x1E`) and ends it with a line feed. The library does not read the record
separator, but splitting the input at it is enough. The RFC asks parsers to skip a truncated or invalid value and
continue with the next one, which parsing without exceptions does:
```cpp
std::string record;
while (std::getline(input, record, '\x1e'))
{
// the input starts with RS, and several RS in a row are allowed
if (record.find_first_not_of(" \t\r\n") == std::string::npos)
{
continue;
}
json j = json::parse(record, nullptr, /* allow_exceptions */ false);
if (j.is_discarded())
{
continue; // truncated or invalid value
}
// use j
}
```
To write a sequence, write `'\x1e'`, then `j.dump()`, then `'\n'` for every value.
## Restricted profiles
### I-JSON (RFC 7493)
[I-JSON](https://www.rfc-editor.org/rfc/rfc7493) ("Internet JSON") is a subset of JSON meant for interoperable
protocols. The table shows how the library handles each of its rules:
| I-JSON rule | Library behavior |
|-----------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| text must be UTF-8 | enforced: invalid UTF-8 is a parse error |
| no surrogate code points in strings, also not as `\u` escapes | enforced: a lone surrogate such as `"\ud800"` is a parse error |
| no noncharacters (such as U+FFFF) in strings | not enforced: they are accepted |
| no duplicate object keys | not enforced: they are accepted; `parse` keeps the last value, while lookups in a [`json_view`](../json_view/differences.md#duplicate-keys) return the first; see the [recipe for rejecting duplicate keys](parser_callbacks.md#recipe-rejecting-duplicate-object-keys) |
| numbers should fit into an IEEE 754 double | numbers that overflow a double, such as `1E400`, throw [`out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406); integers are kept exactly up to 64 bits, larger ones are stored as doubles, see [number handling](../types/number_handling.md) |
| top-level values should be objects or arrays | not enforced: any value is accepted at the top level |
### JSON Canonicalization Scheme (RFC 8785)
The [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (JCS) defines one exact text for each value,
so that it can be hashed or signed. `dump()` without indentation comes close, as it writes no whitespace and, with the
default [`std::map`](../types/index.md#objects), sorts the object keys. It is not canonical, though:
- JCS formats numbers like ECMAScript, so `#!json 1.0` is written as `1` and `#!json 0.000001` as `0.000001`, while
`dump()` writes `1.0` and `1e-06`.
- JCS sorts keys by their UTF-16 code units, while `std::map` sorts them by their UTF-8 bytes. The two orders differ
for keys that contain characters above U+FFFF.
## Non-finite numbers
`NaN`, `Infinity`, and `-Infinity` are not part of JSON, but some libraries write them, among them Python's `json`
module, which does so by default (use `allow_nan=False` there to get standard JSON). This library rejects them as
parse errors, and it writes the non-finite values that a `basic_json` value can hold as `#!json null`. See
[NaN handling](../types/number_handling.md#nan-handling).
## Conventions on top of JSON
Formats such as [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org),
[GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), and
[MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) are standard JSON with
agreed meanings for certain keys or values, such as `{"$numberLong": "42"}` or a `"$comment"` key. The library parses
and writes them like any other JSON; what the values mean is up to your code. For schema validation, see the
[Ecosystem](../../community/ecosystem.md#schema-validation) page.
A few other standards built on JSON are supported directly: [JSON Pointer](../json_pointer.md),
[JSON Patch](../json_patch.md), and [JSON Merge Patch](../merge_patch.md).
For compact binary encodings of the JSON data model, such as CBOR or MessagePack, see
[Binary formats](../binary_formats/index.md).
## See also
- [Parsing](index.md) - overview of the parsing functions
- [Comments](../comments.md) - ignore `//` and `/* */` comments while parsing
- [Trailing Commas](../trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [Number handling](../types/number_handling.md) - how numbers are parsed, stored, and written
- [Binary formats](../binary_formats/index.md) - binary encodings of the JSON data model
- [Ecosystem](../../community/ecosystem.md) - projects that build on this library, including format converters
@@ -42,5 +42,6 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Comments](comments.md) - ignore `//` and `/* */` comments while parsing
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
+1
View File
@@ -146,6 +146,7 @@ nav:
- Parsing:
- features/parsing/index.md
- features/parsing/json_lines.md
- features/parsing/json_variants.md
- features/parsing/large_and_partial_input.md
- features/parsing/parse_exceptions.md
- features/parsing/parser_callbacks.md
+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_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)
@@ -197,55 +179,6 @@ 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
@@ -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
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
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()), and
hands runs of 32 bytes or more to vector_utf8_run_avx2() where the CPU has AVX2.
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
*/
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,8 +28,6 @@
#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
+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_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)
@@ -12753,55 +12735,6 @@ 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
@@ -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
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
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()), and
hands runs of 32 bytes or more to vector_utf8_run_avx2() where the CPU has AVX2.
caller's loop. On x86-64, it is compiled for SSSE3 (see cpu_has_ssse3()).
*/
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
@@ -48993,8 +48813,6 @@ 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,95 +2044,6 @@ 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