* docs: new design for the documentation site Apply the brand to the Material for MkDocs site: Inter and JetBrains Mono served by the site (upright and real italic), brand colours, blue header band with the syntax pattern, wordmark in the header, new home page (hero, cards, animated feature tour), 404 page, polish for tabs, search, footer, focus rings, tables and code blocks, and theme features (code copy, previous/next footer, TOC follow, search suggestions). Draw the number railroad diagram, the parser callback events and the iterator illustrations as inline SVGs that follow the light and dark scheme. The generator scripts are in docs/mkdocs/scripts/figures; the feature slideshow (json-light.svg, json-dark.svg, replacing json.gif on the home page) is built by docs/mkdocs/scripts/slideshow. Decision nodes in five flowcharts become hexagons, which need far less room. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: add figures, table captions and a macro chooser - Figures with numbered captions: SAX stepper, json_view layout and edit stepper, exception map, JSON pointer and patch walkers, QA pipeline, scaling and binary size charts, roadmap lanes, release timeline, integration decision tree and namespace builder - Table captions (nj-table-caption) on 9 pages - Compile times: modules and PCH charts, filesystem section, re-measured Figure 1, links between features/modules.md and compile_times.md - Interactive macro chooser for features/arbitrary_types.md - Link check: exclude URLs that answer the plugin with 400/401/419 or are dead (customers.md) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: macro chooser generates adl_serializer for non-default-constructible types Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: cross-link concept pages and API pages in See also sections Add See also links in both directions between the concept pages (features, home, integration) and the API pages, write API links in code font, give every entry a comment after a dash, and show the callback event figure on the parser callbacks page. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * docs: address review comments on the new design - Home: add a "Latest release" button - Sponsors: update the list and group it by tier - Features: list all feature pages on the index page - Releases: add highlights per release, link the 4.0 roadmap, add the first commit to the timeline - Exceptions: prefix all example messages with the exception name - API: no code font for format names in the See also links of the to_/from_ pages - Merge Patch: show the document before, the patch, and the result - Replace "--" with typographic dashes, mark external links with an icon, center Mermaid diagrams Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
8.9 KiB
nlohmann::basic_json_document::load
// (1)
static basic_json_document load(const std::uint8_t* image, std::size_t size,
const image_check check = image_check::full);
// (2)
static basic_json_document load(const std::vector<std::uint8_t>& image,
const image_check check = image_check::full);
// (3)
static basic_json_document load(std::vector<std::uint8_t>&& image,
const image_check check = image_check::full);
- Reads an image
save()wrote, from a pointer and a byte count. The image is borrowed:imagemust stay alive and unchanged for as long as the returned document, and any view taken from it, is used. - Reads an image from a
#!cpp std::vector. Also borrowed — equivalent to overload 1 called with#!cpp image.data()and#!cpp image.size(). - Reads an image, keeping the vector instead of copying it:
imageis moved into the document (no copy), which then owns it for as long as it needs the text and the decoded strings.owns_source()is#!cpp trueafterward.
In every overload, the node index is copied into storage the document itself owns — so that it is properly aligned,
and, for an editable document, can be edited — while the text and the decoded strings stay in
image. The hash indexes large objects use for lookup are rebuilt, exactly as after
parsing.
Parameters
image(in)- the image
save()wrote (overloads 1 and 2), or one to take ownership of (overload 3) size(in)- the number of bytes at
image(overload 1) check(in)- how thoroughly to validate
imagebefore trusting it; seeimage_checkbelow (optional,#!cpp image_check::fullby default)
Return value
The document read from the image.
Exception safety
Overloads 1 and 2 give the strong guarantee: image is only read, never written, so a thrown exception leaves the
caller's buffer untouched.
Overload 3 moves image into the document before validating it, so that a good image is kept without a copy. If
loading then fails, the partially built document — and the vector now inside it — is discarded along with the
exception, and image itself is left empty, not restored to what was passed in. Move a copy in instead, or
validate with overload 2 first, if the original vector must survive a failed load.
Exceptions
Throws parse_error.116 if image is not one
save() could have written, or fails the requested check:
| message | when |
|---|---|
too short |
image is #!cpp nullptr, or size is smaller than the 64-byte header |
unknown format |
the header's magic bytes or version do not match, or a reserved header field is not zero |
sizes out of range |
the node count, text size, or decoded-string size the header describes does not fit size, or the #!cpp '\0' after the text or after the decoded strings is missing |
the check failed |
check is not #!cpp image_check::none, and the image fails it — see image_check |
!!! failure "Example messages"
```
[json.exception.parse_error.116] parse error: invalid json_document image: too short
```
```
[json.exception.parse_error.116] parse error: invalid json_document image: unknown format
```
```
[json.exception.parse_error.116] parse error: invalid json_document image: sizes out of range
```
```
[json.exception.parse_error.116] parse error: invalid json_document image: the check failed
```
Complexity
Linear in the number of nodes, which are always copied into the document. #!cpp image_check::none does not read
the text or the decoded strings. #!cpp image_check::bounds reads one byte of the text for each float token (its sign,
to check the recorded digits against the token's length), and nothing else of the text or the decoded strings.
With #!cpp image_check::full, linear in the size of the image (the nodes, the text, and the decoded strings), plus
sorting the ranges of the strings and of the float tokens (at most one per node): the contents of each distinct range
are checked once, however many nodes refer to it.
Notes
Little-endian targets only. On a big-endian target, load() does not exist, just like
save(): the image format is little-endian, so a call fails to compile.
image_check
using image_check = detail::view::image_check;
enum class image_check
{
full,
bounds,
none
};
How thoroughly load() validates image before trusting it.
full(the default)- Checks everything the parser itself guarantees: structure and bounds; that every string is valid UTF-8 (and, for a string still in the source text, that it contains no quote, backslash, or control character); and that every number token is well-formed and matches the value stored for it. Strings and float tokens may share a range only if the ranges are identical (as nodes that share a value do), and never overlap otherwise. Reading and serializing a checked image is safe and always produces valid JSON, exactly as for a parsed document. This is the right choice for an image from anything you do not fully control — a file, a cache shared with other processes, a peer on the network.
bounds- Checks structure and bounds only: that every offset and count in the node index stays inside the image. So
load(),root(), element access, andmaterialize()can never read outside the image, even on a damaged one. It does not guarantee that the image describes valid JSON: a string that afullcheck would have rejected can makedump()write invalid UTF-8 or invalid JSON, or throwtype_error.316, and a number can read back with a value that does not match how it is spelled. An editable document does not take such a string over:set,push_backandinsertthrowtype_error.316when they copy it from a view of the loaded document, and leave the editable document unchanged.boundsskips scanning the text and the decoded strings, so it fits a cache your own process just wrote and reads straight back, where damage would mean a bug or a hardware fault rather than adversarial input. none- Checks nothing. Reading a damaged image is undefined behavior, so use it only for an image you trust as much as your own memory.
Lifetime. Overloads 1 and 2 borrow image: it must stay alive and byte-for-byte unchanged for as long as the
returned document, and any view taken from it, is used — exactly like a document
parse() borrowed its input for. Overload 3 avoids this by keeping the vector itself; see
owns_source.
!!! warning "Experimental"
The image format is versioned but not yet stable, and may change in an incompatible way before it is declared
stable; `load()` already rejects an image written by a different format version with `parse_error.116`
("unknown format"). Use images to cache a document within one build of the library, or to hand one to another
process running the *same* build on the *same* (little-endian) machine — not as a long-term storage format.
Examples
??? example "Caching a document, ownership, and a rejected image"
The example below saves a parsed document as an image, checks that `load()` reproduces the original
[`dump()`](../basic_json_view/dump.md) without parsing, and shows the difference between
`load(std::move(image))` (owned) and `load(image)` (borrowed). It then damages one byte of the image and shows
`image_check::full` rejecting it with `parse_error.116`, while `image_check::bounds` — meant for a cache the
process already trusts — still reads it without going out of bounds.
```cpp
--8<-- "examples/basic_json_document__load.cpp"
```
Output:
```json
--8<-- "examples/basic_json_document__load.output"
```
See also
save- write the document as an imageowns_source- return whether the document holds its own copy of the textparse- deserialize from JSON text instead of an image- Images - why and when to use images
Version history
- Added in version 3.13.0.