** 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). */
| 50 | ** bytes (count == 0). |
| 51 | */ |
| 52 | static const char *utf8_decode (const char *s, l_uint32 *val, int strict) { |
| 53 | static const l_uint32 limits[] = |
| 54 | {~(l_uint32)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u}; |
| 55 | unsigned int c = (unsigned char)s[0]; |
| 56 | l_uint32 res = 0; /* final result */ |
| 57 | if (c < 0x80) /* ASCII? */ |
| 58 | res = c; |
| 59 | else { |
| 60 | int count = 0; /* to count number of continuation bytes */ |
| 61 | for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */ |
| 62 | unsigned int cc = (unsigned char)s[++count]; /* read next byte */ |
| 63 | if (!iscont(cc)) /* not a continuation byte? */ |
| 64 | return NULL; /* invalid byte sequence */ |
| 65 | res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ |
| 66 | } |
| 67 | res |= ((l_uint32)(c & 0x7F) << (count * 5)); /* add first byte */ |
| 68 | if (count > 5 || res > MAXUTF || res < limits[count]) |
| 69 | return NULL; /* invalid byte sequence */ |
| 70 | s += count; /* skip continuation bytes read */ |
| 71 | } |
| 72 | if (strict) { |
| 73 | /* check for invalid code points; too large or surrogates */ |
| 74 | if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu)) |
| 75 | return NULL; |
| 76 | } |
| 77 | if (val) *val = res; |
| 78 | return s + 1; /* +1 to include first byte */ |
| 79 | } |
| 80 | |
| 81 | |
| 82 | /* |