** Decode one UTF-8 sequence, returning NULL if byte sequence is ** invalid. The array 'limits' stores the minimum value for each ** sequence length, to check for overlong representations. Its first ** entry forces an error for non-ascii bytes with no continuation ** bytes (count == 0). */
| 55 | ** bytes (count == 0). |
| 56 | */ |
| 57 | static const char *utf8_decode (const char *s, utfint *val, int strict) { |
| 58 | static const utfint limits[] = |
| 59 | {~(utfint)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u}; |
| 60 | unsigned int c = (unsigned char)s[0]; |
| 61 | utfint res = 0; /* final result */ |
| 62 | if (c < 0x80) /* ascii? */ |
| 63 | res = c; |
| 64 | else { |
| 65 | int count = 0; /* to count number of continuation bytes */ |
| 66 | for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */ |
| 67 | unsigned int cc = (unsigned char)s[++count]; /* read next byte */ |
| 68 | if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ |
| 69 | return NULL; /* invalid byte sequence */ |
| 70 | res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ |
| 71 | } |
| 72 | res |= ((utfint)(c & 0x7F) << (count * 5)); /* add first byte */ |
| 73 | if (count > 5 || res > MAXUTF || res < limits[count]) |
| 74 | return NULL; /* invalid byte sequence */ |
| 75 | s += count; /* skip continuation bytes read */ |
| 76 | } |
| 77 | if (strict) { |
| 78 | /* check for invalid code points; too large or surrogates */ |
| 79 | if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu)) |
| 80 | return NULL; |
| 81 | } |
| 82 | if (val) *val = res; |
| 83 | return s + 1; /* +1 to include first byte */ |
| 84 | } |
| 85 | |
| 86 | |
| 87 | /* |