dom.md 15 KB
Newer Older
miloyip's avatar
miloyip committed
1
# DOM
Milo Yip's avatar
Milo Yip committed
2

3
Document Object Model(DOM) is an in-memory representation of JSON for query and manipulation. The basic usage of DOM is described in [Tutorial](doc/tutorial.md). This section will describe some details and more advanced usages.
Milo Yip's avatar
Milo Yip committed
4

5 6 7
[TOC]

# Template {#Template}
Milo Yip's avatar
Milo Yip committed
8

Milo Yip's avatar
Milo Yip committed
9 10 11
In the tutorial,  `Value` and `Document` was used. Similarly to `std::string`, these are actually `typedef` of template classes:

~~~~~~~~~~cpp
12 13
namespace rapidjson {

Milo Yip's avatar
Milo Yip committed
14 15 16 17 18 19 20 21 22 23 24 25
template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
class GenericValue {
    // ...
};

template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
class GenericDocument : public GenericValue<Encoding, Allocator> {
    // ...
};

typedef GenericValue<UTF8<> > Value;
typedef GenericDocument<UTF8<> > Document;
26 27

} // namespace rapidjson
Milo Yip's avatar
Milo Yip committed
28 29 30 31
~~~~~~~~~~

User can customize these template parameters.

32
## Encoding {#Encoding}
Milo Yip's avatar
Milo Yip committed
33

34
The `Encoding` parameter specifies the encoding of JSON String value in memory. Possible options are `UTF8`, `UTF16`, `UTF32`. Note that, these 3 types are also template class. `UTF8<>` is `UTF8<char>`, which means using char to store the characters. You may refer to [Encoding](doc/encoding.md) for details.
Milo Yip's avatar
Milo Yip committed
35 36 37 38

Suppose a Windows application would query localization strings stored in JSON files. Unicode-enabled functions in Windows use UTF-16 (wide character) encoding. No matter what encoding was used in JSON files, we can store the strings in UTF-16 in memory.

~~~~~~~~~~cpp
39 40
using namespace rapidjson;

Milo Yip's avatar
Milo Yip committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
typedef GenericDocument<UTF16<> > WDocument;
typedef GenericValue<UTF16<> > WValue;

FILE* fp = fopen("localization.json", "rb"); // non-Windows use "r"

char readBuffer[256];
FileReadStream bis(fp, readBuffer, sizeof(readBuffer));

AutoUTFInputStream<unsigned, FileReadStream> eis(bis);  // wraps bis into eis

WDocument d;
d.ParseStream<0, AutoUTF<unsigned> >(eis);

const WValue locale(L"ja"); // Japanese

MessageBoxW(hWnd, d[locale].GetString(), L"Test", MB_OK);
~~~~~~~~~~

59
## Allocator {#Allocator}
Milo Yip's avatar
Milo Yip committed
60

Milo Yip's avatar
Milo Yip committed
61 62
The `Allocator` defines which allocator class is used when allocating/deallocating memory for `Document`/`Value`. `Document` owns, or references to an `Allocator` instance. On the other hand, `Value` does not do so, in order to reduce memory consumption.

Milo Yip's avatar
Milo Yip committed
63
The default allocator used in `GenericDocument` is `MemoryPoolAllocator`. This allocator actually allocate memory sequentially, and cannot deallocate one by one. This is very suitable when parsing a JSON into a DOM tree.
Milo Yip's avatar
Milo Yip committed
64 65 66

Another allocator is `CrtAllocator`, of which CRT is short for C RunTime library. This allocator simply calls the standard `malloc()`/`realloc()`/`free()`. When there is a lot of add and remove operations, this allocator may be preferred. But this allocator is far less efficient than `MemoryPoolAllocator`.

67
# Parsing {#Parsing}
Milo Yip's avatar
Milo Yip committed
68

Milo Yip's avatar
Milo Yip committed
69 70 71
`Document` provides several functions for parsing. In below, (1) is the fundamental function, while the others are helpers which call (1).

~~~~~~~~~~cpp
72 73
using namespace rapidjson;

Milo Yip's avatar
Milo Yip committed
74 75
// (1) Fundamental
template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
76
GenericDocument& GenericDocument::ParseStream(InputStream& is);
Milo Yip's avatar
Milo Yip committed
77 78 79

// (2) Using the same Encoding for stream
template <unsigned parseFlags, typename InputStream>
80
GenericDocument& GenericDocument::ParseStream(InputStream& is);
Milo Yip's avatar
Milo Yip committed
81 82 83

// (3) Using default parse flags
template <typename InputStream>
84
GenericDocument& GenericDocument::ParseStream(InputStream& is);
Milo Yip's avatar
Milo Yip committed
85 86 87

// (4) In situ parsing
template <unsigned parseFlags>
88
GenericDocument& GenericDocument::ParseInsitu(Ch* str);
Milo Yip's avatar
Milo Yip committed
89

90
// (5) In situ parsing, using default parse flags
91
GenericDocument& GenericDocument::ParseInsitu(Ch* str);
Milo Yip's avatar
Milo Yip committed
92

93
// (6) Normal parsing of a string
Milo Yip's avatar
Milo Yip committed
94
template <unsigned parseFlags, typename SourceEncoding>
95
GenericDocument& GenericDocument::Parse(const Ch* str);
Milo Yip's avatar
Milo Yip committed
96

97
// (7) Normal parsing of a string, using same Encoding of Document
Milo Yip's avatar
Milo Yip committed
98
template <unsigned parseFlags>
99
GenericDocument& GenericDocument::Parse(const Ch* str);
Milo Yip's avatar
Milo Yip committed
100

101
// (8) Normal parsing of a string, using default parse flags
102
GenericDocument& GenericDocument::Parse(const Ch* str);
Milo Yip's avatar
Milo Yip committed
103 104
~~~~~~~~~~

105
The examples of [tutorial](doc/tutorial.md) uses (8) for normal parsing of string. The examples of [stream](doc/stream.md) uses the first three. *In situ* parsing will be described soon.
Milo Yip's avatar
Milo Yip committed
106 107 108 109 110

The `parseFlags` are combination of the following bit-flags:

Parse flags                   | Meaning
------------------------------|-----------------------------------
111 112
`kParseNoFlags`               | No flag is set.
`kParseDefaultFlags`          | Default parse flags. It is equal to macro `RAPIDJSON_PARSE_DEFAULT_FLAGS`, which is defined as `kParseNoFlags`.
Milo Yip's avatar
Milo Yip committed
113 114
`kParseInsituFlag`            | In-situ(destructive) parsing.
`kParseValidateEncodingFlag`  | Validate encoding of JSON strings.
115 116 117
`kParseIterativeFlag`         | Iterative(constant complexity in terms of function call stack size) parsing.
`kParseStopWhenDoneFlag`      | After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate `kParseErrorDocumentRootNotSingular` error. Using this flag for parsing multiple JSONs in the same stream.
`kParseFullPrecisionFlag`     | Parse number in full precision (slower). If this flag is not set, the normal precision (faster) is used. Normal precision has maximum 3 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) error.
118
`kParseCommentsFlag`          | Allow one-line `// ...` and multi-line `/* ... */` comments (relaxed JSON syntax).
119
`kParseNumbersAsStringsFlag`  | Parse numerical type values as strings.
120
`kParseTrailingCommasFlag`    | Allow trailing commas at the end of objects and arrays (relaxed JSON syntax).
121
`kParseNanAndInfFlag`         | Allow parsing `NaN`, `Inf`, `Infinity`, `-Inf` and `-Infinity` as `double` values (relaxed JSON syntax).
Milo Yip's avatar
Milo Yip committed
122 123 124

By using a non-type template parameter, instead of a function parameter, C++ compiler can generate code which is optimized for specified combinations, improving speed, and reducing code size (if only using a single specialization). The downside is the flags needed to be determined in compile-time.

125
The `SourceEncoding` parameter defines what encoding is in the stream. This can be differed to the `Encoding` of the `Document`. See [Transcoding and Validation](#TranscodingAndValidation) section for details.
Milo Yip's avatar
Milo Yip committed
126 127 128

And the `InputStream` is type of input stream.

129
## Parse Error {#ParseError}
Milo Yip's avatar
Milo Yip committed
130

131
When the parse processing succeeded, the `Document` contains the parse results. When there is an error, the original DOM is *unchanged*. And the error state of parsing can be obtained by `bool HasParseError()`,  `ParseErrorCode GetParseError()` and `size_t GetErrorOffset()`.
Milo Yip's avatar
Milo Yip committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

Parse Error Code                            | Description
--------------------------------------------|---------------------------------------------------
`kParseErrorNone`                           | No error.
`kParseErrorDocumentEmpty`                  | The document is empty.
`kParseErrorDocumentRootNotSingular`        | The document root must not follow by other values.
`kParseErrorValueInvalid`                   | Invalid value.
`kParseErrorObjectMissName`                 | Missing a name for object member.
`kParseErrorObjectMissColon`                | Missing a colon after a name of object member.
`kParseErrorObjectMissCommaOrCurlyBracket`  | Missing a comma or `}` after an object member.
`kParseErrorArrayMissCommaOrSquareBracket`  | Missing a comma or `]` after an array element.
`kParseErrorStringUnicodeEscapeInvalidHex`  | Incorrect hex digit after `\\u` escape in string.
`kParseErrorStringUnicodeSurrogateInvalid`  | The surrogate pair in string is invalid.
`kParseErrorStringEscapeInvalid`            | Invalid escape character in string.
`kParseErrorStringMissQuotationMark`        | Missing a closing quotation mark in string.
`kParseErrorStringInvalidEncoding`          | Invalid encoding in string.
`kParseErrorNumberTooBig`                   | Number too big to be stored in `double`.
`kParseErrorNumberMissFraction`             | Miss fraction part in number.
`kParseErrorNumberMissExponent`             | Miss exponent in number.

The offset of error is defined as the character number from beginning of stream. Currently RapidJSON does not keep track of line number.

To get an error message, RapidJSON provided a English messages in `rapidjson/error/en.h`. User can customize it for other locales, or use a custom localization system.

Here shows an example of parse error handling.

~~~~~~~~~~cpp
159 160 161 162 163 164 165
#include "rapidjson/document.h"
#include "rapidjson/error/en.h"

// ...
Document d;
if (d.Parse(json).HasParseError()) {
    fprintf(stderr, "\nError(offset %u): %s\n", 
Milo Yip's avatar
Milo Yip committed
166
        (unsigned)d.GetErrorOffset(),
167
        GetParseError_En(d.GetParseError()));
168 169
    // ...
}
Milo Yip's avatar
Milo Yip committed
170 171
~~~~~~~~~~

172
## In Situ Parsing {#InSituParsing}
Milo Yip's avatar
Milo Yip committed
173 174 175 176 177 178 179

From [Wikipedia](http://en.wikipedia.org/wiki/In_situ):

> *In situ* ... is a Latin phrase that translates literally to "on site" or "in position". It means "locally", "on site", "on the premises" or "in place" to describe an event where it takes place, and is used in many different contexts.
> ...
> (In computer science) An algorithm is said to be an in situ algorithm, or in-place algorithm, if the extra amount of memory required to execute the algorithm is O(1), that is, does not exceed a constant no matter how large the input. For example, heapsort is an in situ sorting algorithm.

Milo Yip's avatar
Milo Yip committed
180
In normal parsing process, a large overhead is to decode JSON strings and copy them to other buffers. *In situ* parsing decodes those JSON string at the place where it is stored. It is possible in JSON because the length of decoded string is always shorter than or equal to the one in JSON. In this context, decoding a JSON string means to process the escapes, such as `"\n"`, `"\u1234"`, etc., and add a null terminator (`'\0'`)at the end of string.
Milo Yip's avatar
Milo Yip committed
181 182 183

The following diagrams compare normal and *in situ* parsing. The JSON string values contain pointers to the decoded string.

Milo Yip's avatar
Milo Yip committed
184
![normal parsing](diagram/normalparsing.png)
Milo Yip's avatar
Milo Yip committed
185

Milo Yip's avatar
Milo Yip committed
186
In normal parsing, the decoded string are copied to freshly allocated buffers. `"\\n"` (2 characters) is decoded as `"\n"` (1 character). `"\\u0073"` (6 characters) is decoded as `"s"` (1 character).
Milo Yip's avatar
Milo Yip committed
187

Milo Yip's avatar
Milo Yip committed
188
![instiu parsing](diagram/insituparsing.png)
Milo Yip's avatar
Milo Yip committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

*In situ* parsing just modified the original JSON. Updated characters are highlighted in the diagram. If the JSON string does not contain escape character, such as `"msg"`, the parsing process merely replace the closing double quotation mark with a null character.

Since *in situ* parsing modify the input, the parsing API needs `char*` instead of `const char*`.

~~~~~~~~~~cpp
// Read whole file into a buffer
FILE* fp = fopen("test.json", "r");
fseek(fp, 0, SEEK_END);
size_t filesize = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = (char*)malloc(filesize + 1);
size_t readLength = fread(buffer, 1, filesize, fp);
buffer[readLength] = '\0';
fclose(fp);

// In situ parsing the buffer into d, buffer will also be modified
Document d;
d.ParseInsitu(buffer);

// Query/manipulate the DOM here...

free(buffer);
// Note: At this point, d may have dangling pointers pointed to the deallocated buffer.
~~~~~~~~~~

Milo Yip's avatar
Milo Yip committed
215
The JSON strings are marked as const-string. But they may not be really "constant". The life cycle of it depends on the JSON buffer.
Milo Yip's avatar
Milo Yip committed
216 217 218 219 220 221 222 223 224 225 226 227

In situ parsing minimizes allocation overheads and memory copying. Generally this improves cache coherence, which is an important factor of performance in modern computer.

There are some limitations of *in situ* parsing:

1. The whole JSON is in memory.
2. The source encoding in stream and target encoding in document must be the same.
3. The buffer need to be retained until the document is no longer used.
4. If the DOM need to be used for long period after parsing, and there are few JSON strings in the DOM, retaining the buffer may be a memory waste.

*In situ* parsing is mostly suitable for short-term JSON that only need to be processed once, and then be released from memory. In practice, these situation is very common, for example, deserializing JSON to C++ objects, processing web requests represented in JSON, etc.

228
## Transcoding and Validation {#TranscodingAndValidation}
Milo Yip's avatar
Milo Yip committed
229

miloyip's avatar
miloyip committed
230
RapidJSON supports conversion between Unicode formats (officially termed UCS Transformation Format) internally. During DOM parsing, the source encoding of the stream can be different from the encoding of the DOM. For example, the source stream contains a UTF-8 JSON, while the DOM is using UTF-16 encoding. There is an example code in [EncodedInputStream](doc/stream.md).
Milo Yip's avatar
Milo Yip committed
231

miloyip's avatar
miloyip committed
232
When writing a JSON from DOM to output stream, transcoding can also be used. An example is in [EncodedOutputStream](doc/stream.md).
Milo Yip's avatar
Milo Yip committed
233 234 235 236

During transcoding, the source string is decoded to into Unicode code points, and then the code points are encoded in the target format. During decoding, it will validate the byte sequence in the source string. If it is not a valid sequence, the parser will be stopped with `kParseErrorStringInvalidEncoding` error.

When the source encoding of stream is the same as encoding of DOM, by default, the parser will *not* validate the sequence. User may use `kParseValidateEncodingFlag` to force validation.
Milo Yip's avatar
Milo Yip committed
237

238
# Techniques {#Techniques}
Milo Yip's avatar
Milo Yip committed
239

Milo Yip's avatar
Milo Yip committed
240 241
Some techniques about using DOM API is discussed here.

Milo Yip's avatar
Milo Yip committed
242
## DOM as SAX Event Publisher
Milo Yip's avatar
Milo Yip committed
243

Martin Lindhe's avatar
Martin Lindhe committed
244
In RapidJSON, stringifying a DOM with `Writer` may be look a little bit weird.
Milo Yip's avatar
Milo Yip committed
245 246 247 248 249 250 251 252 253

~~~~~~~~~~cpp
// ...
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
~~~~~~~~~~

Actually, `Value::Accept()` is responsible for publishing SAX events about the value to the handler. With this design, `Value` and `Writer` are decoupled. `Value` can generate SAX events, and `Writer` can handle those events.

254
User may create custom handlers for transforming the DOM into other formats. For example, a handler which converts the DOM into XML.
Milo Yip's avatar
Milo Yip committed
255

256
For more about SAX events and handler, please refer to [SAX](doc/sax.md).
Milo Yip's avatar
Milo Yip committed
257

258
## User Buffer {#UserBuffer}
Milo Yip's avatar
Milo Yip committed
259 260 261 262 263 264 265

Some applications may try to avoid memory allocations whenever possible.

`MemoryPoolAllocator` can support this by letting user to provide a buffer. The buffer can be on the program stack, or a "scratch buffer" which is statically allocated (a static/global array) for storing temporary data.

`MemoryPoolAllocator` will use the user buffer to satisfy allocations. When the user buffer is used up, it will allocate a chunk of memory from the base allocator (by default the `CrtAllocator`).

Milo Yip's avatar
Milo Yip committed
266
Here is an example of using stack memory. The first allocator is for storing values, while the second allocator is for storing temporary data during parsing.
Milo Yip's avatar
Milo Yip committed
267 268

~~~~~~~~~~cpp
Milo Yip's avatar
Milo Yip committed
269 270 271 272 273 274
typedef GenericDocument<UTF8<>, MemoryPoolAllocator<>, MemoryPoolAllocator<>> DocumentType;
char valueBuffer[4096];
char parseBuffer[1024];
MemoryPoolAllocator<> valueAllocator(valueBuffer, sizeof(valueBuffer));
MemoryPoolAllocator<> parseAllocator(parseBuffer, sizeof(parseBuffer));
DocumentType d(&valueAllocator, sizeof(parseBuffer), &parseAllocator);
Milo Yip's avatar
Milo Yip committed
275 276 277
d.Parse(json);
~~~~~~~~~~

Milo Yip's avatar
Milo Yip committed
278
If the total size of allocation is less than 4096+1024 bytes during parsing, this code does not invoke any heap allocation (via `new` or `malloc()`) at all.
Milo Yip's avatar
Milo Yip committed
279

Milo Yip's avatar
Milo Yip committed
280
User can query the current memory consumption in bytes via `MemoryPoolAllocator::Size()`. And then user can determine a suitable size of user buffer.