Detect encoding type with BOM or RFC 4627
| 169 | |
| 170 | // Detect encoding type with BOM or RFC 4627 |
| 171 | void DetectType() { |
| 172 | // BOM (Byte Order Mark): |
| 173 | // 00 00 FE FF UTF-32BE |
| 174 | // FF FE 00 00 UTF-32LE |
| 175 | // FE FF UTF-16BE |
| 176 | // FF FE UTF-16LE |
| 177 | // EF BB BF UTF-8 |
| 178 | |
| 179 | const unsigned char* c = reinterpret_cast<const unsigned char *>(is_->Peek4()); |
| 180 | if (!c) |
| 181 | return; |
| 182 | |
| 183 | unsigned bom = static_cast<unsigned>(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24)); |
| 184 | hasBOM_ = false; |
| 185 | if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } |
| 186 | else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } |
| 187 | else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); } |
| 188 | else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); } |
| 189 | else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); } |
| 190 | |
| 191 | // RFC 4627: Section 3 |
| 192 | // "Since the first two characters of a JSON text will always be ASCII |
| 193 | // characters [RFC0020], it is possible to determine whether an octet |
| 194 | // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking |
| 195 | // at the pattern of nulls in the first four octets." |
| 196 | // 00 00 00 xx UTF-32BE |
| 197 | // 00 xx 00 xx UTF-16BE |
| 198 | // xx 00 00 00 UTF-32LE |
| 199 | // xx 00 xx 00 UTF-16LE |
| 200 | // xx xx xx xx UTF-8 |
| 201 | |
| 202 | if (!hasBOM_) { |
| 203 | int pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); |
| 204 | switch (pattern) { |
| 205 | case 0x08: type_ = kUTF32BE; break; |
| 206 | case 0x0A: type_ = kUTF16BE; break; |
| 207 | case 0x01: type_ = kUTF32LE; break; |
| 208 | case 0x05: type_ = kUTF16LE; break; |
| 209 | case 0x0F: type_ = kUTF8; break; |
| 210 | default: break; // Use type defined by user. |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. |
| 215 | if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2); |
| 216 | if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4); |
| 217 | } |
| 218 | |
| 219 | typedef Ch (*TakeFunc)(InputByteStream& is); |
| 220 | InputByteStream* is_; |