Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d59b7e2728 | ||
|
|
91a03caa72 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -11,15 +11,7 @@
|
||||
#include <algorithm> // max
|
||||
#include <cstddef> // size_t
|
||||
#ifndef JSON_NO_IO
|
||||
#include <cstdio> // FILE, fread, ftell
|
||||
#if defined(_WIN32)
|
||||
#include <stdio.h> // _fileno, _ftelli64 // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
|
||||
#include <sys/types.h> // (for sys/stat.h)
|
||||
#include <sys/stat.h> // _fstat64, _S_IFMT, _S_IFREG
|
||||
#elif defined(__unix__) || defined(__APPLE__)
|
||||
#include <stdio.h> // fileno // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
|
||||
#include <sys/stat.h> // fstat, S_ISREG
|
||||
#endif
|
||||
#include <cstdio> // FILE, fread
|
||||
#endif
|
||||
#include <istream> // istream, streambuf
|
||||
#include <string> // basic_string, char_traits, string
|
||||
@@ -139,15 +131,6 @@ adapter_input<typename std::decay<Adapter>::type> make_adapter_input(Adapter&& i
|
||||
return {std::forward<Adapter>(ia)};
|
||||
}
|
||||
|
||||
/// the size of a read block, and the least room offered to a read: one page,
|
||||
/// the usual size of a filesystem block. It is a conventional size, not a tuned
|
||||
/// one: it only has to be large enough that a read is never tiny and that the
|
||||
/// read which finds the end of the input needs no regrowth of the string
|
||||
constexpr std::size_t read_block_size() noexcept
|
||||
{
|
||||
return 4096;
|
||||
}
|
||||
|
||||
/// append the rest of a stream: its characters need no conversion, so they are
|
||||
/// read in blocks from the stream buffer, straight into buf (reusing its
|
||||
/// capacity). As the library's stream adapter, this reads the stream buffer
|
||||
@@ -159,20 +142,10 @@ inline void append_stream(std::string& buf, std::istream& is)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// room for the rest when the stream buffer knows how much is left (for a
|
||||
// file with libstdc++, the rest of the file), and for the read that finds
|
||||
// the end: the input is then read in one block, without a reallocation and
|
||||
// copy at each doubling of the string (only a hint: the loop below reads
|
||||
// what is there)
|
||||
const std::streamsize rest = sb->in_avail();
|
||||
if (rest > 0 && static_cast<std::size_t>(rest) < buf.max_size() - buf.size() - read_block_size())
|
||||
{
|
||||
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + read_block_size());
|
||||
}
|
||||
for (;;)
|
||||
{
|
||||
const std::size_t used = buf.size();
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096});
|
||||
buf.resize(used + room);
|
||||
const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room));
|
||||
buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0})));
|
||||
@@ -195,55 +168,15 @@ struct is_c_stream
|
||||
{};
|
||||
|
||||
#ifndef JSON_NO_IO
|
||||
/// the number of bytes left in a C stream that is a regular file (from its
|
||||
/// size and position), 0 for anything else and on other systems: a hint for
|
||||
/// the room to reserve; f is not null
|
||||
inline unsigned long long file_rest(std::FILE* f) noexcept
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
struct _stat64 st {};
|
||||
if (::_fstat64(_fileno(f), &st) == 0 && (st.st_mode & _S_IFMT) == _S_IFREG)
|
||||
{
|
||||
const long long here = ::_ftelli64(f);
|
||||
if (here >= 0 && st.st_size > here)
|
||||
{
|
||||
return static_cast<unsigned long long>(st.st_size - here);
|
||||
}
|
||||
}
|
||||
#elif defined(__unix__) || defined(__APPLE__)
|
||||
struct stat st {};
|
||||
if (::fstat(fileno(f), &st) == 0 && S_ISREG(st.st_mode))
|
||||
{
|
||||
const long here = std::ftell(f);
|
||||
if (here >= 0 && st.st_size > here)
|
||||
{
|
||||
return static_cast<unsigned long long>(st.st_size - here);
|
||||
}
|
||||
}
|
||||
#else
|
||||
static_cast<void>(f);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// append the rest of a C stream: in blocks with fread, not character by
|
||||
/// character (the library's file adapter reads with fgetc), and in one block
|
||||
/// when it is a regular file of known size; f is not null
|
||||
/// character (the library's file adapter reads with fgetc);
|
||||
/// f is not null
|
||||
inline void append_file(std::string& buf, std::FILE* f)
|
||||
{
|
||||
// room for the rest of a regular file and the byte that shows its end:
|
||||
// the file is then read in one block, without a reallocation and copy at
|
||||
// each doubling of the string (only a hint: the loop below reads what is
|
||||
// there)
|
||||
const unsigned long long rest = file_rest(f);
|
||||
if (rest > 0 && rest < buf.max_size() - buf.size() - 1)
|
||||
{
|
||||
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + 1);
|
||||
}
|
||||
for (;;)
|
||||
{
|
||||
const std::size_t used = buf.size();
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096});
|
||||
buf.resize(used + room);
|
||||
const std::size_t got = std::fread(&buf[used], 1, room, f);
|
||||
buf.resize(used + got);
|
||||
|
||||
Generated
+5
-72
@@ -7957,15 +7957,7 @@ NLOHMANN_JSON_NAMESPACE_END
|
||||
#include <algorithm> // max
|
||||
#include <cstddef> // size_t
|
||||
#ifndef JSON_NO_IO
|
||||
#include <cstdio> // FILE, fread, ftell
|
||||
#if defined(_WIN32)
|
||||
#include <stdio.h> // _fileno, _ftelli64 // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
|
||||
#include <sys/types.h> // (for sys/stat.h)
|
||||
#include <sys/stat.h> // _fstat64, _S_IFMT, _S_IFREG
|
||||
#elif defined(__unix__) || defined(__APPLE__)
|
||||
#include <stdio.h> // fileno // NOLINT(hicpp-deprecated-headers,modernize-deprecated-headers)
|
||||
#include <sys/stat.h> // fstat, S_ISREG
|
||||
#endif
|
||||
#include <cstdio> // FILE, fread
|
||||
#endif
|
||||
#include <istream> // istream, streambuf
|
||||
#include <string> // basic_string, char_traits, string
|
||||
@@ -8086,15 +8078,6 @@ adapter_input<typename std::decay<Adapter>::type> make_adapter_input(Adapter&& i
|
||||
return {std::forward<Adapter>(ia)};
|
||||
}
|
||||
|
||||
/// the size of a read block, and the least room offered to a read: one page,
|
||||
/// the usual size of a filesystem block. It is a conventional size, not a tuned
|
||||
/// one: it only has to be large enough that a read is never tiny and that the
|
||||
/// read which finds the end of the input needs no regrowth of the string
|
||||
constexpr std::size_t read_block_size() noexcept
|
||||
{
|
||||
return 4096;
|
||||
}
|
||||
|
||||
/// append the rest of a stream: its characters need no conversion, so they are
|
||||
/// read in blocks from the stream buffer, straight into buf (reusing its
|
||||
/// capacity). As the library's stream adapter, this reads the stream buffer
|
||||
@@ -8106,20 +8089,10 @@ inline void append_stream(std::string& buf, std::istream& is)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// room for the rest when the stream buffer knows how much is left (for a
|
||||
// file with libstdc++, the rest of the file), and for the read that finds
|
||||
// the end: the input is then read in one block, without a reallocation and
|
||||
// copy at each doubling of the string (only a hint: the loop below reads
|
||||
// what is there)
|
||||
const std::streamsize rest = sb->in_avail();
|
||||
if (rest > 0 && static_cast<std::size_t>(rest) < buf.max_size() - buf.size() - read_block_size())
|
||||
{
|
||||
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + read_block_size());
|
||||
}
|
||||
for (;;)
|
||||
{
|
||||
const std::size_t used = buf.size();
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096});
|
||||
buf.resize(used + room);
|
||||
const std::streamsize got = sb->sgetn(&buf[used], static_cast<std::streamsize>(room));
|
||||
buf.resize(used + static_cast<std::size_t>((std::max)(got, std::streamsize{0})));
|
||||
@@ -8142,55 +8115,15 @@ struct is_c_stream
|
||||
{};
|
||||
|
||||
#ifndef JSON_NO_IO
|
||||
/// the number of bytes left in a C stream that is a regular file (from its
|
||||
/// size and position), 0 for anything else and on other systems: a hint for
|
||||
/// the room to reserve; f is not null
|
||||
inline unsigned long long file_rest(std::FILE* f) noexcept
|
||||
{
|
||||
#if defined(_WIN32)
|
||||
struct _stat64 st {};
|
||||
if (::_fstat64(_fileno(f), &st) == 0 && (st.st_mode & _S_IFMT) == _S_IFREG)
|
||||
{
|
||||
const long long here = ::_ftelli64(f);
|
||||
if (here >= 0 && st.st_size > here)
|
||||
{
|
||||
return static_cast<unsigned long long>(st.st_size - here);
|
||||
}
|
||||
}
|
||||
#elif defined(__unix__) || defined(__APPLE__)
|
||||
struct stat st {};
|
||||
if (::fstat(fileno(f), &st) == 0 && S_ISREG(st.st_mode))
|
||||
{
|
||||
const long here = std::ftell(f);
|
||||
if (here >= 0 && st.st_size > here)
|
||||
{
|
||||
return static_cast<unsigned long long>(st.st_size - here);
|
||||
}
|
||||
}
|
||||
#else
|
||||
static_cast<void>(f);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// append the rest of a C stream: in blocks with fread, not character by
|
||||
/// character (the library's file adapter reads with fgetc), and in one block
|
||||
/// when it is a regular file of known size; f is not null
|
||||
/// character (the library's file adapter reads with fgetc);
|
||||
/// f is not null
|
||||
inline void append_file(std::string& buf, std::FILE* f)
|
||||
{
|
||||
// room for the rest of a regular file and the byte that shows its end:
|
||||
// the file is then read in one block, without a reallocation and copy at
|
||||
// each doubling of the string (only a hint: the loop below reads what is
|
||||
// there)
|
||||
const unsigned long long rest = file_rest(f);
|
||||
if (rest > 0 && rest < buf.max_size() - buf.size() - 1)
|
||||
{
|
||||
buf.reserve(buf.size() + static_cast<std::size_t>(rest) + 1);
|
||||
}
|
||||
for (;;)
|
||||
{
|
||||
const std::size_t used = buf.size();
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, read_block_size());
|
||||
const std::size_t room = (std::max)(buf.capacity() - used, std::size_t{4096});
|
||||
buf.resize(used + room);
|
||||
const std::size_t got = std::fread(&buf[used], 1, room, f);
|
||||
buf.resize(used + got);
|
||||
|
||||
@@ -535,33 +535,6 @@ TEST_CASE("json_view")
|
||||
CHECK_THROWS_AS(from_null = json_document::parse(static_cast<std::FILE*>(nullptr)), json::parse_error&);
|
||||
}
|
||||
|
||||
// a regular file is read in one block, from its position to its end
|
||||
std::FILE* tail_file = std::tmpfile(); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
if (tail_file != nullptr)
|
||||
{
|
||||
const std::string prefix = "garbage ";
|
||||
CHECK(std::fwrite(prefix.data(), 1, prefix.size(), tail_file) == prefix.size());
|
||||
CHECK(std::fwrite(text.data(), 1, text.size(), tail_file) == text.size());
|
||||
CHECK(std::fseek(tail_file, static_cast<long>(prefix.size()), SEEK_SET) == 0);
|
||||
#if defined(_WIN32) || defined(__unix__) || defined(__APPLE__)
|
||||
CHECK(nlohmann::detail::view::file_rest(tail_file) == text.size());
|
||||
#endif
|
||||
const json_document from_tail = json_document::parse(tail_file);
|
||||
CHECK(from_tail.source() == text);
|
||||
CHECK(from_tail.root().materialize() == json::parse(text));
|
||||
CHECK(nlohmann::detail::view::file_rest(tail_file) == 0);
|
||||
CHECK(std::fclose(tail_file) == 0); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
}
|
||||
|
||||
// a stream is read from its position to its end as well, in one block
|
||||
// when its buffer knows how much is left
|
||||
std::istringstream tail_stream("garbage " + text);
|
||||
tail_stream.seekg(8);
|
||||
const json_document from_tail_stream = json_document::parse(tail_stream);
|
||||
CHECK(from_tail_stream.source() == text);
|
||||
CHECK(from_tail_stream.root().materialize() == json::parse(text));
|
||||
CHECK(tail_stream.eof());
|
||||
|
||||
// a stream without a buffer is an empty input
|
||||
std::istream no_buffer(nullptr);
|
||||
CHECK(json_document::parse(no_buffer, false).is_discarded());
|
||||
|
||||
Reference in new issue
Block a user