Compare commits

..
Author SHA1 Message Date
Niels Lohmann 5612cc3967 Drop unneeded NOLINTs and reuse the pointer from utf8_dfa_prefix()
The check cppcoreguidelines-avoid-non-const-global-variables is disabled in
.clang-tidy, and both tables are function-local constants. In
valid_utf8_prefix(), test the byte through the returned pointer instead of
indexing data again.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-30 20:02:26 +01:00
Niels Lohmann 62b238dce8 Validate runs of non-ASCII bytes with a shift-based UTF-8 DFA
The scalar bulk paths validated non-ASCII text one sequence at a time with
validate_one_utf8(). Replace these loops with a shift-based DFA (one table
load and one shift per byte, no branch on the byte):

- utf8_dfa_run() in scalar_string_bulk_run(): the lexer and the serializer
  without SSE2/NEON, and on x86 CPUs without SSSE3. On an error, the exact
  position comes from utf8_dfa_prefix(), so diagnostics are unchanged.
- utf8_dfa_prefix() in valid_utf8_prefix(): the BON8 reader (all builds),
  the BON8 writer and the BSON name check.

Both stop at the first ill-formed byte, so the serializer's error handlers
stay linear. On Apple M, CJK text (poet.json) got 30% faster in the lexer and
serializer without SIMD, and BON8 reading got 15% faster with SIMD.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-11-30 18:11:18 +01:00
12 changed files with 404 additions and 233 deletions

No files matched your search

-3
View File
@@ -34,9 +34,6 @@ For products, applications, and organizations that use the library, see [Custome
## Format converters ## Format converters
For the formats related to JSON that the library reads itself, such as JSONC or JSON Lines, see
[JSON variants](../features/parsing/json_variants.md).
- [**tojson**](https://github.com/mircodz/tojson), a header-only converter between YAML/XML documents and - [**tojson**](https://github.com/mircodz/tojson), a header-only converter between YAML/XML documents and
`nlohmann::json` `nlohmann::json`
- [**json2xml**](https://github.com/testillano/json2xml), a header-only converter from `nlohmann::json` to XML for - [**json2xml**](https://github.com/testillano/json2xml), a header-only converter from `nlohmann::json` to XML for
+1 -3
View File
@@ -11,8 +11,7 @@ This library does not support comments *by default*. It does so for three reason
3. It is dangerous for interoperability if some libraries add comment support while others do not. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this. 3. It is dangerous for interoperability if some libraries add comment support while others do not. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this.
However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support. See [JSON variants](parsing/json_variants.md) for a However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with [`ignore_trailing_commas`](trailing_commas.md) (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) — comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support.
comparison with these and other formats.
For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html). For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html).
@@ -44,6 +43,5 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Trailing Commas](trailing_commas.md) - accept trailing commas in arrays and objects - [Trailing Commas](trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions - [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control - [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
-2
View File
@@ -18,8 +18,6 @@ C++ types, and finally serialize it again.
- [Editable documents](json_view/editing.md) — modify a parsed document without building a `json` tree. - [Editable documents](json_view/editing.md) — modify a parsed document without building a `json` tree.
- [Images](json_view/images.md) — save a parsed document and load it again without parsing it. - [Images](json_view/images.md) — save a parsed document and load it again without parsing it.
- [Comments](comments.md) and [trailing commas](trailing_commas.md) — opt-in relaxations of the JSON grammar. - [Comments](comments.md) and [trailing commas](trailing_commas.md) — opt-in relaxations of the JSON grammar.
- [JSON variants](parsing/json_variants.md) — which of JSONC, JSON5, JSON Lines, I-JSON, and other formats related to
JSON the library supports.
## Accessing and modifying values ## Accessing and modifying values
+1 -3
View File
@@ -45,8 +45,7 @@ that arrives in chunks or contains several values is covered in
[Large, streamed, and partial input](large_and_partial_input.md). [Large, streamed, and partial input](large_and_partial_input.md).
By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the `parse` By default, the library rejects comments and trailing commas. Both can be enabled with parameters of the `parse`
function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md). See function — see [comments](../comments.md) and [trailing commas](../trailing_commas.md).
[JSON variants](json_variants.md) for how much of JSONC, JSON5, and other formats related to JSON the library supports.
[`basic_json_document::parse`](../../api/basic_json_document/parse.md) accepts the same inputs with the same options, [`basic_json_document::parse`](../../api/basic_json_document/parse.md) accepts the same inputs with the same options,
but keeps the result in a document rather than in a `basic_json` value; see but keeps the result in a document rather than in a `basic_json` value; see
@@ -170,7 +169,6 @@ options.
- [`accept`](../../api/basic_json/accept.md) - check if the input is valid JSON - [`accept`](../../api/basic_json/accept.md) - check if the input is valid JSON
- [`sax_parse`](../../api/basic_json/sax_parse.md) - generate SAX events - [`sax_parse`](../../api/basic_json/sax_parse.md) - generate SAX events
- [JSON Lines](json_lines.md) - parse newline-delimited JSON - [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [JSON variants](json_variants.md) - JSONC, JSON5, JSON text sequences, I-JSON, and other formats related to JSON
- [Large, streamed, and partial input](large_and_partial_input.md) - chunked, concatenated, and very large input - [Large, streamed, and partial input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [parser callbacks](parser_callbacks.md) - influence the parsing by a callback function - [parser callbacks](parser_callbacks.md) - influence the parsing by a callback function
- [SAX interface](sax_interface.md) - implement a custom SAX handler - [SAX interface](sax_interface.md) - implement a custom SAX handler
@@ -68,6 +68,5 @@ JSON Lines input with more than one value is treated as invalid JSON by the [`pa
- [Parsing](index.md) - overview of the parsing functions - [Parsing](index.md) - overview of the parsing functions
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input - [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [JSON variants](json_variants.md) - NDJSON, JSON text sequences, and other formats related to JSON
- [`parse`](../../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../../api/basic_json/parse.md) - deserialize from a compatible input
- [`operator>>`](../../api/operator_gtgt.md) - deserialize from stream - [`operator>>`](../../api/operator_gtgt.md) - deserialize from stream
@@ -1,185 +0,0 @@
# JSON Variants
This library reads and writes JSON as defined by [RFC 8259](https://tools.ietf.org/html/rfc8259) and
[ECMA-404](https://ecma-international.org/publications-and-standards/standards/ecma-404/). Many other formats are
built around JSON: some relax its syntax (for example, to allow comments), some put several JSON values into one
stream, some restrict it further, and some give certain JSON values a special meaning. This page lists the common
ones and how much of each the library supports.
## Overview
| Variant | Kind | Support |
|------------------------------------------------------------------|----------------------------|-----------------------------------------------------------------------------------------------------------|
| [JSON](https://tools.ietf.org/html/rfc8259) (RFC 8259, ECMA-404) | the standard | :white_check_mark: default |
| [JSONC](https://jsonc.org) | relaxed syntax | :white_check_mark: with `ignore_comments` (and `ignore_trailing_commas` where trailing commas are wanted) |
| [JWCC](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html) / [HuJSON](https://github.com/tailscale/hujson) | relaxed syntax | :white_check_mark: with `ignore_comments` and `ignore_trailing_commas` |
| [JSON5](https://spec.json5.org) | relaxed syntax | :warning: comments and trailing commas only |
| [Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md), [UCL](https://github.com/vstakhov/libucl), SJSON | configuration languages | :x: only input that is JSON plus `//`/`/* */` comments and trailing commas |
| [YAML](https://yaml.org), [Amazon Ion](https://amazon-ion.github.io/ion-docs/) | other languages | :x: see [converters](#other-languages-and-converters) |
| [JSON Lines](https://jsonlines.org), [NDJSON](https://github.com/ndjson/ndjson-spec) | several values | :white_check_mark: line by line, see [JSON Lines](json_lines.md) |
| concatenated JSON | several values | :white_check_mark: with `operator>>`, see [Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream) |
| [JSON text sequences](https://www.rfc-editor.org/rfc/rfc7464) (RFC 7464) | several values | :warning: split the input yourself, see [below](#json-text-sequences-rfc-7464) |
| [I-JSON](https://www.rfc-editor.org/rfc/rfc7493) (RFC 7493) | restricted profile | :warning: most rules are enforced, see [below](#i-json-rfc-7493) |
| [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (RFC 8785) | restricted output | :x: `dump()` output is close, but not canonical |
| `NaN`, `Infinity` (JavaScript, Python) | number extension | :x: rejected by the parser, written as `null` |
| [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org), [GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), [MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) | conventions on top of JSON | :white_check_mark: parsed as plain JSON; interpreting them is up to you |
Whatever was parsed, [`dump`](../../api/basic_json/dump.md) always writes standard JSON: no comments, no trailing
commas, and no `NaN` or `Infinity`.
## Standard JSON
By default, [`parse`](../../api/basic_json/parse.md) accepts exactly the JSON grammar of RFC 8259, including values
other than objects and arrays at the top level (such as `#!json 42` or `#!json "text"`). A UTF-8 byte order mark at the
very start of the input is skipped; anywhere else it is a parse error.
## Relaxed syntax
### JSONC and JWCC
**JSONC** ("JSON with comments", used, for example, by Visual Studio Code's `settings.json` and `devcontainer.json`)
adds `//` and `/* */` comments to JSON. Block comments do not nest. The [JSONC specification](https://jsonc.org) lets
parsers decide whether they accept trailing commas. **JWCC** ("JSON with commas and comments") adds the same comments
and always allows a single trailing comma in arrays and objects; [HuJSON](https://github.com/tailscale/hujson) is
Tailscale's implementation of it.
Both are fully supported by passing `ignore_comments` and `ignore_trailing_commas` to `parse`:
```cpp
json j = json::parse(input,
/* callback */ nullptr,
/* allow_exceptions */ true,
/* ignore_comments */ true,
/* ignore_trailing_commas */ true);
```
Comments are treated as whitespace and are not kept, so they are lost when the value is written again. This also holds
for a [`json_document`](../../api/basic_json_document/index.md): [`dump()`](../../api/basic_json_view/dump.md) of its
root view writes the same text as `dump()` of the parsed `json` value, even though the document keeps the source text
with the comments. See
[Comments](../comments.md) and [Trailing commas](../trailing_commas.md) for the details. The .NET options
`JsonCommentHandling.Skip` and `AllowTrailingCommas` accept the same syntax.
### JSON5
[JSON5](https://spec.json5.org) is a superset of JSON that follows the syntax of ECMAScript 5 object literals. Besides
comments and trailing commas, it allows unquoted keys, single-quoted strings, line continuations in strings, more
escape sequences (`\v`, `\0`, `\xHH`, ...), hexadecimal numbers, a leading `+`, a leading or trailing decimal point, and
`Infinity` and `NaN`. With the two options above, the library accepts JSON5 documents that only use comments and
trailing commas; using any of the other extensions is a parse error.
### Configuration languages
[Hjson](https://hjson.github.io), [HOCON](https://github.com/lightbend/config/blob/main/HOCON.md),
[UCL](https://github.com/vstakhov/libucl), and SJSON (from the Bitsquid/Stingray game engine) are configuration
languages that accept JSON but go much further: `#` comments, unquoted keys and values, `=` instead of `:`, optional
commas and braces, multiline strings, and, in HOCON and UCL, includes and variable substitutions. The library does not
support these extensions. A `#` comment in particular is always a parse error, even with `ignore_comments`.
### Other languages and converters
[YAML](https://yaml.org) and the text format of [Amazon Ion](https://amazon-ion.github.io/ion-docs/) are separate
languages with their own data models, and the library does not read them. The [Ecosystem](../../community/ecosystem.md)
page lists projects that convert YAML or XML to and from `nlohmann::json`.
## Several values in one input
`parse` reads exactly one value and reports anything after it as an error. Several common formats combine many values
into one input:
- **[JSON Lines](https://jsonlines.org)** and **[NDJSON](https://github.com/ndjson/ndjson-spec)** put one value on each
line. Read them line by line, as shown on the [JSON Lines](json_lines.md) page. The two formats differ in one detail:
JSON Lines does not allow empty lines, while NDJSON parsers may skip them. Passing an empty line to `parse` is an
error, so skip empty lines yourself if you read NDJSON.
- **Concatenated JSON** puts values directly after each other, optionally separated by whitespace. Read them with
[`operator>>`](../../api/operator_gtgt.md), as shown in
[Large, streamed, and partial input](large_and_partial_input.md#several-values-in-one-stream).
### JSON text sequences (RFC 7464)
A [JSON text sequence](https://www.rfc-editor.org/rfc/rfc7464) (media type `application/json-seq`) starts every value
with the ASCII record separator (RS, `0x1E`) and ends it with a line feed. The library does not read the record
separator, but splitting the input at it is enough. The RFC asks parsers to skip a truncated or invalid value and
continue with the next one, which parsing without exceptions does:
```cpp
std::string record;
while (std::getline(input, record, '\x1e'))
{
// the input starts with RS, and several RS in a row are allowed
if (record.find_first_not_of(" \t\r\n") == std::string::npos)
{
continue;
}
json j = json::parse(record, nullptr, /* allow_exceptions */ false);
if (j.is_discarded())
{
continue; // truncated or invalid value
}
// use j
}
```
To write a sequence, write `'\x1e'`, then `j.dump()`, then `'\n'` for every value.
## Restricted profiles
### I-JSON (RFC 7493)
[I-JSON](https://www.rfc-editor.org/rfc/rfc7493) ("Internet JSON") is a subset of JSON meant for interoperable
protocols. The table shows how the library handles each of its rules:
| I-JSON rule | Library behavior |
|-----------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| text must be UTF-8 | enforced: invalid UTF-8 is a parse error |
| no surrogate code points in strings, also not as `\u` escapes | enforced: a lone surrogate such as `"\ud800"` is a parse error |
| no noncharacters (such as U+FFFF) in strings | not enforced: they are accepted |
| no duplicate object keys | not enforced: they are accepted; `parse` keeps the last value, while lookups in a [`json_view`](../json_view/differences.md#duplicate-keys) return the first; see the [recipe for rejecting duplicate keys](parser_callbacks.md#recipe-rejecting-duplicate-object-keys) |
| numbers should fit into an IEEE 754 double | numbers that overflow a double, such as `1E400`, throw [`out_of_range.406`](../../home/exceptions.md#jsonexceptionout_of_range406); integers are kept exactly up to 64 bits, larger ones are stored as doubles, see [number handling](../types/number_handling.md) |
| top-level values should be objects or arrays | not enforced: any value is accepted at the top level |
### JSON Canonicalization Scheme (RFC 8785)
The [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785) (JCS) defines one exact text for each value,
so that it can be hashed or signed. `dump()` without indentation comes close, as it writes no whitespace and, with the
default [`std::map`](../types/index.md#objects), sorts the object keys. It is not canonical, though:
- JCS formats numbers like ECMAScript, so `#!json 1.0` is written as `1` and `#!json 0.000001` as `0.000001`, while
`dump()` writes `1.0` and `1e-06`.
- JCS sorts keys by their UTF-16 code units, while `std::map` sorts them by their UTF-8 bytes. The two orders differ
for keys that contain characters above U+FFFF.
## Non-finite numbers
`NaN`, `Infinity`, and `-Infinity` are not part of JSON, but some libraries write them, among them Python's `json`
module, which does so by default (use `allow_nan=False` there to get standard JSON). This library rejects them as
parse errors, and it writes the non-finite values that a `basic_json` value can hold as `#!json null`. See
[NaN handling](../types/number_handling.md#nan-handling).
## Conventions on top of JSON
Formats such as [JSON Schema](https://json-schema.org), [JSON-LD](https://json-ld.org),
[GeoJSON](https://www.rfc-editor.org/rfc/rfc7946), and
[MongoDB Extended JSON](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) are standard JSON with
agreed meanings for certain keys or values, such as `{"$numberLong": "42"}` or a `"$comment"` key. The library parses
and writes them like any other JSON; what the values mean is up to your code. For schema validation, see the
[Ecosystem](../../community/ecosystem.md#schema-validation) page.
A few other standards built on JSON are supported directly: [JSON Pointer](../json_pointer.md),
[JSON Patch](../json_patch.md), and [JSON Merge Patch](../merge_patch.md).
For compact binary encodings of the JSON data model, such as CBOR or MessagePack, see
[Binary formats](../binary_formats/index.md).
## See also
- [Parsing](index.md) - overview of the parsing functions
- [Comments](../comments.md) - ignore `//` and `/* */` comments while parsing
- [Trailing Commas](../trailing_commas.md) - accept trailing commas in arrays and objects
- [JSON Lines](json_lines.md) - parse newline-delimited JSON
- [Large, Streamed, and Partial Input](large_and_partial_input.md) - chunked, concatenated, and very large input
- [Number handling](../types/number_handling.md) - how numbers are parsed, stored, and written
- [Binary formats](../binary_formats/index.md) - binary encodings of the JSON data model
- [Ecosystem](../../community/ecosystem.md) - projects that build on this library, including format converters
@@ -42,6 +42,5 @@ For more information, see [JSON With Commas and Comments (JWCC)](https://nigelta
- [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input - [`parse`](../api/basic_json/parse.md) - deserialize from a compatible input
- [Comments](comments.md) - ignore `//` and `/* */` comments while parsing - [Comments](comments.md) - ignore `//` and `/* */` comments while parsing
- [JSON variants](parsing/json_variants.md) - JSONC, JWCC, JSON5, and other formats related to JSON
- [Parsing](parsing/index.md) - overview of the parsing functions - [Parsing](parsing/index.md) - overview of the parsing functions
- [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control - [Parsing Untrusted Input](parsing/untrusted_input.md) - limits and checks for input you do not control
-1
View File
@@ -146,7 +146,6 @@ nav:
- Parsing: - Parsing:
- features/parsing/index.md - features/parsing/index.md
- features/parsing/json_lines.md - features/parsing/json_lines.md
- features/parsing/json_variants.md
- features/parsing/large_and_partial_input.md - features/parsing/large_and_partial_input.md
- features/parsing/parse_exceptions.md - features/parsing/parse_exceptions.md
- features/parsing/parser_callbacks.md - features/parsing/parser_callbacks.md
+161 -14
View File
@@ -223,6 +223,157 @@ inline std::size_t validate_one_utf8(const unsigned char* data, std::size_t avai
return 0; // invalid, incomplete, or must be diagnosed by the byte path return 0; // invalid, incomplete, or must be diagnosed by the byte path
} }
/*!
@brief the transition table of the UTF-8 DFA of utf8_dfa_run() and utf8_dfa_prefix()
They accept exactly what validate_one_utf8() accepts. This is a shift-based
DFA (after Per Vognsen; see also https://orlp.net/blog/utf8-dfa/): a state is
6 times its number, and table[b] holds, for every state s, the next state on
byte b at bit offset s. One step is a load and a shift without a branch on the
byte. On CJK text, it made the lexer and the serializer without SSE2/NEON 30%
faster and the BON8 reader 15% faster than a loop over validate_one_utf8()
(Apple M, Apple Clang).
The states are 0 (error, absorbing), 6 (between sequences), 12/18/24 (1/2/3
continuation bytes of 0x80-0xBF missing), and the states after the lead bytes
that restrict the second byte: 30 (0xE0: 0xA0-0xBF), 36 (0xED: 0x80-0x9F), 42
(0xF0: 0x90-0xBF), and 48 (0xF4: 0x80-0x8F). The test "UTF-8 DFA" in
unit-class_lexer.cpp checks every entry of the table.
*/
inline const std::uint64_t* utf8_dfa_table() noexcept
{
static const std::array<std::uint64_t, 256> table =
{
{
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000780ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000900ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000A80ull, 0x0000000000000600ull, 0x0000000000000600ull, 0x0000000000000600ull,
0x0000000000000C00ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
}
};
return table.data();
}
/*!
@brief validate a run of non-ASCII bytes as UTF-8
Validates [p, e) up to the first byte below 0x80 (see utf8_dfa_table()).
@return the end of the run (@a e or a byte below 0x80) if it consists of
complete well-formed UTF-8 sequences, otherwise nullptr
It stops at the first ill-formed byte: the serializer's error handlers scan
again after every ill-formed byte, and scanning on to the end of the run would
make them quadratic. Without the position of the error, it is faster than
utf8_dfa_prefix(), which made the lexer 15% slower on CJK text.
*/
JSON_HEDLEY_NEVER_INLINE inline const unsigned char* utf8_dfa_run(const unsigned char* p, const unsigned char* e) noexcept
{
const std::uint64_t* const table = utf8_dfa_table();
std::uint64_t state = 6;
while (p != e && *p >= 0x80u)
{
// a shift uses only the low 6 bits of its count on x86-64 and ARM64, so
// the mask is free there
state = table[*p] >> (state & 63u);
++p;
if (JSON_HEDLEY_UNLIKELY((state & 63u) == 0))
{
return nullptr;
}
}
return (state & 63u) == 6 ? p : nullptr;
}
/*!
@brief the end of the longest well-formed UTF-8 prefix of a run of non-ASCII bytes
Validates [p, e) up to the first byte below 0x80 (see utf8_dfa_table()) and
returns the end of the longest prefix that consists of complete well-formed
UTF-8 sequences. The whole run was valid if the result is @a e or points to a
byte below 0x80; otherwise it points to the lead byte of the first ill-formed or
incomplete sequence. Like utf8_dfa_run(), it stops at the first ill-formed byte.
*/
JSON_HEDLEY_NEVER_INLINE inline const unsigned char* utf8_dfa_prefix(const unsigned char* p, const unsigned char* e) noexcept
{
const std::uint64_t* const table = utf8_dfa_table();
std::uint64_t state = 6;
const unsigned char* last = p; // the end of the last complete sequence
while (p != e && *p >= 0x80u)
{
// a shift uses only the low 6 bits of its count on x86-64 and ARM64, so
// the mask is free there
state = table[*p] >> (state & 63u);
++p;
const std::uint64_t current = state & 63u;
if (JSON_HEDLEY_UNLIKELY(current == 0))
{
break;
}
last = (current == 6) ? p : last;
}
return last;
}
// Return the length of the longest prefix of [data, data+n) that consists of // Return the length of the longest prefix of [data, data+n) that consists of
// ASCII characters and complete well-formed UTF-8 sequences; n if all of it is // ASCII characters and complete well-formed UTF-8 sequences; n if all of it is
// valid UTF-8. Unlike scalar_string_bulk_run(), quotes, escapes, and control // valid UTF-8. Unlike scalar_string_bulk_run(), quotes, escapes, and control
@@ -250,12 +401,12 @@ inline std::size_t valid_utf8_prefix(const unsigned char* data, std::size_t n) n
continue; continue;
} }
const std::size_t seq = validate_one_utf8(data + pos, n - pos); const unsigned char* const last = utf8_dfa_prefix(data + pos, data + n);
if (seq == 0) pos = static_cast<std::size_t>(last - data);
if (pos != n && *last >= 0x80u)
{ {
break; // ill-formed or truncated break; // ill-formed or truncated
} }
pos += seq;
} }
return pos; return pos;
} }
@@ -440,18 +591,14 @@ JSON_HEDLEY_ALWAYS_INLINE std::size_t scalar_string_bulk_run(const unsigned char
} }
#endif #endif
#if !JSON_SCAN_VECTOR_UTF8 || JSON_SCAN_SSSE3_DISPATCH #if !JSON_SCAN_VECTOR_UTF8 || JSON_SCAN_SSSE3_DISPATCH
// a run of multi-byte sequences (e.g. CJK text) is validated sequence // a run of multi-byte sequences (e.g. CJK text) is validated as a whole
// by sequence without searching for the next special byte in between const unsigned char* const run_end = utf8_dfa_run(p, e);
do if (JSON_HEDLEY_UNLIKELY(run_end == nullptr))
{ {
const std::size_t seq = validate_one_utf8(p, static_cast<std::size_t>(e - p)); // ill-formed or truncated: let the byte path diagnose it
if (seq == 0) return static_cast<std::size_t>(utf8_dfa_prefix(p, e) - data);
{
return static_cast<std::size_t>(p - data); // ill-formed or truncated: let the byte path diagnose it
}
p += seq;
} }
while (p != e && *p >= 0x80u); p = run_end;
#endif #endif
} }
return static_cast<std::size_t>(p - data); return static_cast<std::size_t>(p - data);
@@ -556,7 +703,7 @@ JSON_HEDLEY_ALWAYS_INLINE std::size_t lexer_string_bulk_run(const unsigned char*
// unaffected by this fast path. // unaffected by this fast path.
inline int hex_codepoint(const unsigned char* data) noexcept inline int hex_codepoint(const unsigned char* data) noexcept
{ {
static const std::array<std::uint8_t, 256> hex_digit_table = // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) static const std::array<std::uint8_t, 256> hex_digit_table =
{ {
{ {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 00..0F 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 00..0F
+4 -3
View File
@@ -206,9 +206,10 @@ places, which differ in speed, diagnostics, and how they read the input:
the bytes as is and leave the check to dump() and the binary writers. the bytes as is and leave the check to dump() and the binary writers.
- the per-lead-byte switch in lexer::scan_string(): JSON text, with a - the per-lead-byte switch in lexer::scan_string(): JSON text, with a
diagnostic for each kind of error. diagnostic for each kind of error.
- validate_one_utf8() and valid_utf8_prefix() in string_scan.hpp: the lexer's - validate_one_utf8(), utf8_dfa_prefix() and valid_utf8_prefix() in
bulk string scan, the bulk path of the BON8 reader, and the BON8 writer. string_scan.hpp: the lexer's bulk string scan, the bulk path of the BON8
They must accept exactly what the lexer's switch accepts. reader, and the BON8 writer. They must accept exactly what the lexer's
switch accepts.
- the byte path of binary_reader::get_bon8_string(): BON8 input without bulk - the byte path of binary_reader::get_bon8_string(): BON8 input without bulk
access, and the bytes the bulk path leaves to it. It keeps its own ranges: access, and the bytes the bulk path leaves to it. It keeps its own ranges:
taking them from utf8_shape() made BON8 decoding 2-3% slower (#5891). taking them from utf8_shape() made BON8 decoding 2-3% slower (#5891).
+165 -17
View File
@@ -7388,9 +7388,10 @@ places, which differ in speed, diagnostics, and how they read the input:
the bytes as is and leave the check to dump() and the binary writers. the bytes as is and leave the check to dump() and the binary writers.
- the per-lead-byte switch in lexer::scan_string(): JSON text, with a - the per-lead-byte switch in lexer::scan_string(): JSON text, with a
diagnostic for each kind of error. diagnostic for each kind of error.
- validate_one_utf8() and valid_utf8_prefix() in string_scan.hpp: the lexer's - validate_one_utf8(), utf8_dfa_prefix() and valid_utf8_prefix() in
bulk string scan, the bulk path of the BON8 reader, and the BON8 writer. string_scan.hpp: the lexer's bulk string scan, the bulk path of the BON8
They must accept exactly what the lexer's switch accepts. reader, and the BON8 writer. They must accept exactly what the lexer's
switch accepts.
- the byte path of binary_reader::get_bon8_string(): BON8 input without bulk - the byte path of binary_reader::get_bon8_string(): BON8 input without bulk
access, and the bytes the bulk path leaves to it. It keeps its own ranges: access, and the bytes the bulk path leaves to it. It keeps its own ranges:
taking them from utf8_shape() made BON8 decoding 2-3% slower (#5891). taking them from utf8_shape() made BON8 decoding 2-3% slower (#5891).
@@ -13171,6 +13172,157 @@ inline std::size_t validate_one_utf8(const unsigned char* data, std::size_t avai
return 0; // invalid, incomplete, or must be diagnosed by the byte path return 0; // invalid, incomplete, or must be diagnosed by the byte path
} }
/*!
@brief the transition table of the UTF-8 DFA of utf8_dfa_run() and utf8_dfa_prefix()
They accept exactly what validate_one_utf8() accepts. This is a shift-based
DFA (after Per Vognsen; see also https://orlp.net/blog/utf8-dfa/): a state is
6 times its number, and table[b] holds, for every state s, the next state on
byte b at bit offset s. One step is a load and a shift without a branch on the
byte. On CJK text, it made the lexer and the serializer without SSE2/NEON 30%
faster and the BON8 reader 15% faster than a loop over validate_one_utf8()
(Apple M, Apple Clang).
The states are 0 (error, absorbing), 6 (between sequences), 12/18/24 (1/2/3
continuation bytes of 0x80-0xBF missing), and the states after the lead bytes
that restrict the second byte: 30 (0xE0: 0xA0-0xBF), 36 (0xED: 0x80-0x9F), 42
(0xF0: 0x90-0xBF), and 48 (0xF4: 0x80-0x8F). The test "UTF-8 DFA" in
unit-class_lexer.cpp checks every entry of the table.
*/
inline const std::uint64_t* utf8_dfa_table() noexcept
{
static const std::array<std::uint64_t, 256> table =
{
{
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull, 0x0000000000000180ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull, 0x001200C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull, 0x000048C012306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull, 0x0000480312306000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull, 0x0000000000000300ull,
0x0000000000000780ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000480ull, 0x0000000000000900ull, 0x0000000000000480ull, 0x0000000000000480ull,
0x0000000000000A80ull, 0x0000000000000600ull, 0x0000000000000600ull, 0x0000000000000600ull,
0x0000000000000C00ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull, 0x0000000000000000ull,
}
};
return table.data();
}
/*!
@brief validate a run of non-ASCII bytes as UTF-8
Validates [p, e) up to the first byte below 0x80 (see utf8_dfa_table()).
@return the end of the run (@a e or a byte below 0x80) if it consists of
complete well-formed UTF-8 sequences, otherwise nullptr
It stops at the first ill-formed byte: the serializer's error handlers scan
again after every ill-formed byte, and scanning on to the end of the run would
make them quadratic. Without the position of the error, it is faster than
utf8_dfa_prefix(), which made the lexer 15% slower on CJK text.
*/
JSON_HEDLEY_NEVER_INLINE inline const unsigned char* utf8_dfa_run(const unsigned char* p, const unsigned char* e) noexcept
{
const std::uint64_t* const table = utf8_dfa_table();
std::uint64_t state = 6;
while (p != e && *p >= 0x80u)
{
// a shift uses only the low 6 bits of its count on x86-64 and ARM64, so
// the mask is free there
state = table[*p] >> (state & 63u);
++p;
if (JSON_HEDLEY_UNLIKELY((state & 63u) == 0))
{
return nullptr;
}
}
return (state & 63u) == 6 ? p : nullptr;
}
/*!
@brief the end of the longest well-formed UTF-8 prefix of a run of non-ASCII bytes
Validates [p, e) up to the first byte below 0x80 (see utf8_dfa_table()) and
returns the end of the longest prefix that consists of complete well-formed
UTF-8 sequences. The whole run was valid if the result is @a e or points to a
byte below 0x80; otherwise it points to the lead byte of the first ill-formed or
incomplete sequence. Like utf8_dfa_run(), it stops at the first ill-formed byte.
*/
JSON_HEDLEY_NEVER_INLINE inline const unsigned char* utf8_dfa_prefix(const unsigned char* p, const unsigned char* e) noexcept
{
const std::uint64_t* const table = utf8_dfa_table();
std::uint64_t state = 6;
const unsigned char* last = p; // the end of the last complete sequence
while (p != e && *p >= 0x80u)
{
// a shift uses only the low 6 bits of its count on x86-64 and ARM64, so
// the mask is free there
state = table[*p] >> (state & 63u);
++p;
const std::uint64_t current = state & 63u;
if (JSON_HEDLEY_UNLIKELY(current == 0))
{
break;
}
last = (current == 6) ? p : last;
}
return last;
}
// Return the length of the longest prefix of [data, data+n) that consists of // Return the length of the longest prefix of [data, data+n) that consists of
// ASCII characters and complete well-formed UTF-8 sequences; n if all of it is // ASCII characters and complete well-formed UTF-8 sequences; n if all of it is
// valid UTF-8. Unlike scalar_string_bulk_run(), quotes, escapes, and control // valid UTF-8. Unlike scalar_string_bulk_run(), quotes, escapes, and control
@@ -13198,12 +13350,12 @@ inline std::size_t valid_utf8_prefix(const unsigned char* data, std::size_t n) n
continue; continue;
} }
const std::size_t seq = validate_one_utf8(data + pos, n - pos); const unsigned char* const last = utf8_dfa_prefix(data + pos, data + n);
if (seq == 0) pos = static_cast<std::size_t>(last - data);
if (pos != n && *last >= 0x80u)
{ {
break; // ill-formed or truncated break; // ill-formed or truncated
} }
pos += seq;
} }
return pos; return pos;
} }
@@ -13388,18 +13540,14 @@ JSON_HEDLEY_ALWAYS_INLINE std::size_t scalar_string_bulk_run(const unsigned char
} }
#endif #endif
#if !JSON_SCAN_VECTOR_UTF8 || JSON_SCAN_SSSE3_DISPATCH #if !JSON_SCAN_VECTOR_UTF8 || JSON_SCAN_SSSE3_DISPATCH
// a run of multi-byte sequences (e.g. CJK text) is validated sequence // a run of multi-byte sequences (e.g. CJK text) is validated as a whole
// by sequence without searching for the next special byte in between const unsigned char* const run_end = utf8_dfa_run(p, e);
do if (JSON_HEDLEY_UNLIKELY(run_end == nullptr))
{ {
const std::size_t seq = validate_one_utf8(p, static_cast<std::size_t>(e - p)); // ill-formed or truncated: let the byte path diagnose it
if (seq == 0) return static_cast<std::size_t>(utf8_dfa_prefix(p, e) - data);
{
return static_cast<std::size_t>(p - data); // ill-formed or truncated: let the byte path diagnose it
}
p += seq;
} }
while (p != e && *p >= 0x80u); p = run_end;
#endif #endif
} }
return static_cast<std::size_t>(p - data); return static_cast<std::size_t>(p - data);
@@ -13504,7 +13652,7 @@ JSON_HEDLEY_ALWAYS_INLINE std::size_t lexer_string_bulk_run(const unsigned char*
// unaffected by this fast path. // unaffected by this fast path.
inline int hex_codepoint(const unsigned char* data) noexcept inline int hex_codepoint(const unsigned char* data) noexcept
{ {
static const std::array<std::uint8_t, 256> hex_digit_table = // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) static const std::array<std::uint8_t, 256> hex_digit_table =
{ {
{ {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 00..0F 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 00..0F
+72
View File
@@ -2138,6 +2138,14 @@ TEST_CASE("UTF-8 validators accept the same sequences")
CAPTURE(t) CAPTURE(t)
CHECK((dfa == expected && bulk == (expected ? length : 0) && bulk_short == 0)); CHECK((dfa == expected && bulk == (expected ? length : 0) && bulk_short == 0));
// the DFA of the bulk paths: the whole sequence or nothing
if (length >= 2)
{
const unsigned char* const run_end = nlohmann::detail::utf8_dfa_prefix(bytes.data(), bytes.data() + length);
const unsigned char* const short_end = nlohmann::detail::utf8_dfa_prefix(bytes.data(), bytes.data() + length - 1);
CHECK((run_end == bytes.data() + (expected ? length : 0) && short_end == bytes.data()));
}
if (t < 2 && length >= 2) if (t < 2 && length >= 2)
{ {
// the lexer's byte path // the lexer's byte path
@@ -2165,6 +2173,70 @@ TEST_CASE("UTF-8 validators accept the same sequences")
} }
} }
TEST_CASE("UTF-8 DFA")
{
// utf8_dfa_prefix() and utf8_dfa_run() against a loop over
// validate_one_utf8(): every byte
// after a prefix that leads to each state of the DFA checks every entry of
// its table, and the bytes after it whether it stops at the right place
const auto reference = [](const unsigned char* p, const unsigned char* e)
{
while (p != e && *p >= 0x80u)
{
const std::size_t length = nlohmann::detail::validate_one_utf8(p, static_cast<std::size_t>(e - p));
if (length == 0)
{
break;
}
p += length;
}
return p;
};
// between sequences, after a valid sequence, 1/2/3 continuation bytes
// missing, and after the lead bytes that restrict the second byte
const std::vector<std::vector<unsigned char>> prefixes =
{
{}, {0xC3, 0xA4}, {0xC3}, {0xE1}, {0xF1}, {0xE1, 0x80}, {0xF1, 0x80}, {0xF1, 0x80, 0x80},
{0xE0}, {0xED}, {0xF0}, {0xF4}
};
const std::vector<std::vector<unsigned char>> suffixes =
{
{}, {0x80}, {0xBF}, {0x41}, {0xC3, 0xA4}, {0xE4, 0xB8, 0xAD}, {0xF0, 0x9F, 0x98, 0x80}, {0xFF}
};
for (const auto& prefix : prefixes)
{
for (unsigned byte = 0; byte <= 0xFF; ++byte)
{
for (const auto& suffix : suffixes)
{
std::vector<unsigned char> input(prefix);
input.push_back(static_cast<unsigned char>(byte));
input.insert(input.end(), suffix.begin(), suffix.end());
const unsigned char* const begin = input.data();
const unsigned char* const end = begin + input.size();
CAPTURE(prefix.size())
CAPTURE(byte)
CAPTURE(suffix.size())
const unsigned char* const expected = reference(begin, end);
CHECK(nlohmann::detail::utf8_dfa_prefix(begin, end) - begin == expected - begin);
// utf8_dfa_run() only tells whether the whole run is valid
const bool whole_run = expected == end || *expected < 0x80u;
CHECK(nlohmann::detail::utf8_dfa_run(begin, end) == (whole_run ? expected : nullptr));
}
}
}
// an ill-formed byte stops the scan at once, whatever follows
std::vector<unsigned char> invalid(1000, 0xFF);
CHECK(nlohmann::detail::utf8_dfa_prefix(invalid.data(), invalid.data() + invalid.size()) == invalid.data());
CHECK(nlohmann::detail::utf8_dfa_run(invalid.data(), invalid.data() + invalid.size()) == nullptr);
invalid[0] = 0xC3;
invalid[1] = 0xA4;
CHECK(nlohmann::detail::utf8_dfa_prefix(invalid.data(), invalid.data() + invalid.size()) == invalid.data() + 2);
}
TEST_CASE("float_bigint") TEST_CASE("float_bigint")
{ {
// the big integer of the exact comparison of a float token with the // the big integer of the exact comparison of a float token with the