1# Encoding
2
3According to [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf),
4
5> (in Introduction) JSON text is a sequence of Unicode code points.
6
7The earlier [RFC4627](http://www.ietf.org/rfc/rfc4627.txt) stated that,
8
9> (in §3) JSON text SHALL be encoded in Unicode.  The default encoding is UTF-8.
10
11> (in §6) JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible.  When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used.
12
13RapidJSON supports various encodings. It can also validate the encodings of JSON, and transconding JSON among encodings. All these features are implemented internally, without the need for external libraries (e.g. [ICU](http://site.icu-project.org/)).
14
15[TOC]
16
17# Unicode {#Unicode}
18From [Unicode's official website](http://www.unicode.org/standard/WhatIsUnicode.html):
19> Unicode provides a unique number for every character,
20> no matter what the platform,
21> no matter what the program,
22> no matter what the language.
23
24Those unique numbers are called code points, which is in the range `0x0` to `0x10FFFF`.
25
26## Unicode Transformation Format {#UTF}
27
28There are various encodings for storing Unicode code points. These are called Unicode Transformation Format (UTF). RapidJSON supports the most commonly used UTFs, including
29
30* UTF-8: 8-bit variable-width encoding. It maps a code point to 1–4 bytes.
31* UTF-16: 16-bit variable-width encoding. It maps a code point to 1–2 16-bit code units (i.e., 2–4 bytes).
32* UTF-32: 32-bit fixed-width encoding. It directly maps a code point to a single 32-bit code unit (i.e. 4 bytes).
33
34For UTF-16 and UTF-32, the byte order (endianness) does matter. Within computer memory, they are often stored in the computer's endianness. However, when it is stored in file or transferred over network, we need to state the byte order of the byte sequence, either little-endian (LE) or big-endian (BE).
35
36RapidJSON provide these encodings via the structs in `rapidjson/encodings.h`:
37
38~~~~~~~~~~cpp
39namespace rapidjson {
40
41template<typename CharType = char>
42struct UTF8;
43
44template<typename CharType = wchar_t>
45struct UTF16;
46
47template<typename CharType = wchar_t>
48struct UTF16LE;
49
50template<typename CharType = wchar_t>
51struct UTF16BE;
52
53template<typename CharType = unsigned>
54struct UTF32;
55
56template<typename CharType = unsigned>
57struct UTF32LE;
58
59template<typename CharType = unsigned>
60struct UTF32BE;
61
62} // namespace rapidjson
63~~~~~~~~~~
64
65For processing text in memory, we normally use `UTF8`, `UTF16` or `UTF32`. For processing text via I/O, we may use `UTF8`, `UTF16LE`, `UTF16BE`, `UTF32LE` or `UTF32BE`.
66
67When using the DOM-style API, the `Encoding` template parameter in `GenericValue<Encoding>` and `GenericDocument<Encoding>` indicates the encoding to be used to represent JSON string in memory. So normally we will use `UTF8`, `UTF16` or `UTF32` for this template parameter. The choice depends on operating systems and other libraries that the application is using. For example, Windows API represents Unicode characters in UTF-16, while most Linux distributions and applications prefer UTF-8.
68
69Example of UTF-16 DOM declaration:
70
71~~~~~~~~~~cpp
72typedef GenericDocument<UTF16<> > WDocument;
73typedef GenericValue<UTF16<> > WValue;
74~~~~~~~~~~
75
76For a detail example, please check the example in [DOM's Encoding](doc/stream.md) section.
77
78## Character Type {#CharacterType}
79
80As shown in the declaration, each encoding has a `CharType` template parameter. Actually, it may be a little bit confusing, but each `CharType` stores a code unit, not a character (code point). As mentioned in previous section, a code point may be encoded to 1–4 code units for UTF-8.
81
82For `UTF16(LE|BE)`, `UTF32(LE|BE)`, the `CharType` must be integer type of at least 2 and 4 bytes  respectively.
83
84Note that C++11 introduces `char16_t` and `char32_t`, which can be used for `UTF16` and `UTF32` respectively.
85
86## AutoUTF {#AutoUTF}
87
88Previous encodings are statically bound in compile-time. In other words, user must know exactly which encodings will be used in the memory or streams. However, sometimes we may need to read/write files of different encodings. The encoding needed to be decided in runtime.
89
90`AutoUTF` is an encoding designed for this purpose. It chooses which encoding to be used according to the input or output stream. Currently, it should be used with `EncodedInputStream` and `EncodedOutputStream`.
91
92## ASCII {#ASCII}
93
94Although the JSON standards did not mention about [ASCII](http://en.wikipedia.org/wiki/ASCII), sometimes we would like to write 7-bit ASCII JSON for applications that cannot handle UTF-8. Since any JSON can represent unicode characters in escaped sequence `\uXXXX`, JSON can always be encoded in ASCII.
95
96Here is an example for writing a UTF-8 DOM into ASCII:
97
98~~~~~~~~~~cpp
99using namespace rapidjson;
100Document d; // UTF8<>
101// ...
102StringBuffer buffer;
103Writer<StringBuffer, Document::EncodingType, ASCII<> > writer(buffer);
104d.Accept(writer);
105std::cout << buffer.GetString();
106~~~~~~~~~~
107
108ASCII can be used in input stream. If the input stream contains bytes with values above 127, it will cause `kParseErrorStringInvalidEncoding` error.
109
110ASCII *cannot* be used in memory (encoding of `Document` or target encoding of `Reader`), as it cannot represent Unicode code points.
111
112# Validation & Transcoding {#ValidationTranscoding}
113
114When RapidJSON parses a JSON, it can validate the input JSON, whether it is a valid sequence of a specified encoding. This option can be turned on by adding `kParseValidateEncodingFlag` in `parseFlags` template parameter.
115
116If the input encoding and output encoding is different, `Reader` and `Writer` will automatically transcode (convert) the text. In this case, `kParseValidateEncodingFlag` is not necessary, as it must decode the input sequence. And if the sequence was unable to be decoded, it must be invalid.
117
118## Transcoder {#Transcoder}
119
120Although the encoding functions in RapidJSON are designed for JSON parsing/generation, user may abuse them for transcoding of non-JSON strings.
121
122Here is an example for transcoding a string from UTF-8 to UTF-16:
123
124~~~~~~~~~~cpp
125#include "rapidjson/encodings.h"
126
127using namespace rapidjson;
128
129const char* s = "..."; // UTF-8 string
130StringStream source(s);
131GenericStringBuffer<UTF16<> > target;
132
133bool hasError = false;
134while (source.Peak() != '\0')
135    if (!Transcoder::Transcode<UTF8<>, UTF16<> >(source, target)) {
136        hasError = true;
137        break;
138    }
139
140if (!hasError) {
141    const wchar_t* t = target.GetString();
142    // ...
143}
144~~~~~~~~~~
145
146You may also use `AutoUTF` and the associated streams for setting source/target encoding in runtime.
147