Detect encoding type with BOM or RFC 4627
| 140 | |
| 141 | // Detect encoding type with BOM or RFC 4627 |
| 142 | void DetectType() { |
| 143 | // BOM (Byte Order Mark): |
| 144 | // 00 00 FE FF UTF-32BE |
| 145 | // FF FE 00 00 UTF-32LE |
| 146 | // FE FF UTF-16BE |
| 147 | // FF FE UTF-16LE |
| 148 | // EF BB BF UTF-8 |
| 149 | |
| 150 | const unsigned char* c = (const unsigned char *)is_->Peek4(); |
| 151 | if (!c) |
| 152 | return; |
| 153 | |
| 154 | unsigned bom = c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24); |
| 155 | hasBOM_ = false; |
| 156 | if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } |
| 157 | else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); } |
| 158 | else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); } |
| 159 | else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); } |
| 160 | else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); } |
| 161 | |
| 162 | // RFC 4627: Section 3 |
| 163 | // "Since the first two characters of a JSON text will always be ASCII |
| 164 | // characters [RFC0020], it is possible to determine whether an octet |
| 165 | // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking |
| 166 | // at the pattern of nulls in the first four octets." |
| 167 | // 00 00 00 xx UTF-32BE |
| 168 | // 00 xx 00 xx UTF-16BE |
| 169 | // xx 00 00 00 UTF-32LE |
| 170 | // xx 00 xx 00 UTF-16LE |
| 171 | // xx xx xx xx UTF-8 |
| 172 | |
| 173 | if (!hasBOM_) { |
| 174 | unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0); |
| 175 | switch (pattern) { |
| 176 | case 0x08: type_ = kUTF32BE; break; |
| 177 | case 0x0A: type_ = kUTF16BE; break; |
| 178 | case 0x01: type_ = kUTF32LE; break; |
| 179 | case 0x05: type_ = kUTF16LE; break; |
| 180 | case 0x0F: type_ = kUTF8; break; |
| 181 | default: break; // Use type defined by user. |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | // Runtime check whether the size of character type is sufficient. It only perform checks with assertion. |
| 186 | switch (type_) { |
| 187 | case kUTF8: |
| 188 | // Do nothing |
| 189 | break; |
| 190 | case kUTF16LE: |
| 191 | case kUTF16BE: |
| 192 | RAPIDJSON_ASSERT(sizeof(Ch) >= 2); |
| 193 | break; |
| 194 | case kUTF32LE: |
| 195 | case kUTF32BE: |
| 196 | RAPIDJSON_ASSERT(sizeof(Ch) >= 4); |
| 197 | break; |
| 198 | default: |
| 199 | RAPIDJSON_ASSERT(false); // Invalid type |