| 37 | */ |
| 38 | |
| 39 | char32_t decodeUtf8(const char* s, size_t len, size_t& idx) |
| 40 | { |
| 41 | assert(idx < len); |
| 42 | |
| 43 | char32_t V; |
| 44 | size_t i = idx; |
| 45 | char u = s[i]; |
| 46 | |
| 47 | if (u & 0x80) |
| 48 | { |
| 49 | size_t n; |
| 50 | char u2; |
| 51 | |
| 52 | /* The following encodings are valid, except for the 5 and 6 byte |
| 53 | * combinations: |
| 54 | * 0xxxxxxx |
| 55 | * 110xxxxx 10xxxxxx |
| 56 | * 1110xxxx 10xxxxxx 10xxxxxx |
| 57 | * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 58 | * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 59 | * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
| 60 | */ |
| 61 | for (n = 1; ; n++) |
| 62 | { |
| 63 | if (n > 4) |
| 64 | goto Lerr; // only do the first 4 of 6 encodings |
| 65 | if (((u << n) & 0x80) == 0) |
| 66 | { |
| 67 | if (n == 1) |
| 68 | goto Lerr; |
| 69 | break; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // Pick off (7 - n) significant bits of B from first byte of octet |
| 74 | V = static_cast<char32_t>(u & ((1 << (7 - n)) - 1)); |
| 75 | |
| 76 | if (i + (n - 1) >= len) |
| 77 | goto Lerr; // off end of string |
| 78 | |
| 79 | /* The following combinations are overlong, and illegal: |
| 80 | * 1100000x (10xxxxxx) |
| 81 | * 11100000 100xxxxx (10xxxxxx) |
| 82 | * 11110000 1000xxxx (10xxxxxx 10xxxxxx) |
| 83 | * 11111000 10000xxx (10xxxxxx 10xxxxxx 10xxxxxx) |
| 84 | * 11111100 100000xx (10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx) |
| 85 | */ |
| 86 | u2 = s[i + 1]; |
| 87 | if ((u & 0xFE) == 0xC0 || |
| 88 | (u == 0xE0 && (u2 & 0xE0) == 0x80) || |
| 89 | (u == 0xF0 && (u2 & 0xF0) == 0x80) || |
| 90 | (u == 0xF8 && (u2 & 0xF8) == 0x80) || |
| 91 | (u == 0xFC && (u2 & 0xFC) == 0x80)) |
| 92 | goto Lerr; // overlong combination |
| 93 | |
| 94 | for (size_t j = 1; j != n; j++) |
| 95 | { |
| 96 | u = s[i + j]; |
no test coverage detected