* Document that read() must not be given a view of the document itself basic_json_document::read() releases the previous text, the decoded strings and the edits before it parses its input. An input that points into them (source(), get_string(), number_token(), or a string of an edited document) is read after its memory was cleared or freed. A guard that copies such input costs about 1 ns per read() (5 % of a read of a 7-byte input), which this API exists to avoid, so state the precondition in read.md, lifetime.md and the pages of the views that hand out such strings instead, and show how to copy the string first. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Assert in debug builds that read() is not given its own text read() releases the document's text, decoded strings, owned image and edits before it parses, so an input that points into them is read after release. Without NDEBUG, read() now asserts that a borrowed input, a copied contiguous input and (before C++17) a string_ref input are not held by the document: its owned text, its decoded strings, an owned image, and the current buffer of edited strings. Release builds keep the documented precondition without a check, which would cost 2-4.5 % per read() of a small message. JSON_ASSERT is undefined at the end of json.hpp, so the view uses assert() through a new internal NLOHMANN_VIEW_ASSERT. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
1.4 KiB
1.4 KiB
nlohmann::basic_json_document::source
view_type::string_view_t source() const noexcept;
Returns the parsed text, whether it is borrowed from the caller or owned by the document.
Return value
A #!cpp string_view_t (#!cpp std::string_view on C++17 and newer) over the parsed text, or an empty one if the
document is discarded.
Exception safety
No-throw guarantee: this function never throws exceptions.
Complexity
Constant.
Notes
For a borrowed document, source() points directly into the caller's buffer, so it is only valid while that buffer
is; see owns_source.
The text of a document that owns it must not be passed to read() of the same document: read() releases
an owned text before it parses its input. Copy it first. (A borrowed text belongs to the caller and is not affected.)
Examples
??? example
```cpp
--8<-- "examples/basic_json_document__source.cpp"
```
Output:
```json
--8<-- "examples/basic_json_document__source.output"
```
See also
owns_source- return whether the document holds its own copy of the textsource_offset- byte offset of a value in the source text- Zero-copy JSON views - who owns the source text and for how long
Version history
- Added in version 3.13.0.