2 Copyright (C) 2010 Joseph A. Adams (joeyadams3.14159@gmail.com)
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 bool utf8_allow_surrogates = false;
28 bool utf8_validate(const char *str, size_t length)
30 const unsigned char *s = (const unsigned char*)str;
31 const unsigned char *e = s + length;
34 unsigned char c = *s++;
35 unsigned int len; /* number of bytes in sequence - 2 */
37 /* If character is ASCII, move on. */
42 return false; /* Missing bytes in sequence. */
45 /* 2-byte sequence, U+0080 to U+07FF
46 c must be 11000010 or higher
47 s[0] must be 10xxxxxx */
51 } else if (c < 0xF0) {
52 /* 3-byte sequence, U+0800 to U+FFFF
53 Note that the surrogate range is U+D800 to U+DFFF,
54 and that U+FFFE and U+FFFF are illegal characters.
55 c must be >= 11100000 (which it is)
56 If c is 11100000, then s[0] must be >= 10100000
57 If the global parameter utf8_allow_surrogates is false:
58 If c is 11101101 and s[0] is >= 10100000,
59 then this is a surrogate and we should fail.
60 If c is 11101111, s[0] is 10111111, and s[1] >= 10111110,
61 then this is an illegal character and we should fail.
62 s[0] and s[1] must be 10xxxxxx */
64 if (c == 0xE0 && *s < 0xA0)
66 if (!utf8_allow_surrogates && c == 0xED && *s >= 0xA0)
68 if (c == 0xEF && s[0] == 0xBF && (s+1 >= e || s[1] >= 0xBE))
71 /* 4-byte sequence, U+010000 to U+10FFFF
72 c must be >= 11110000 (which it is) and <= 11110100
73 If c is 11110000, then s[0] must be >= 10010000
74 If c is 11110100, then s[0] must be < 10010000
75 s[0], s[1], and s[2] must be 10xxxxxx */
79 if (c == 0xF0 && *s < 0x90)
81 if (c == 0xF4 && *s >= 0x90)
86 return false; /* Missing bytes in sequence. */
89 if ((*s++ & 0xC0) != 0x80)
98 Note to future contributors: These routines are currently all under the
99 MIT license. It would be nice to keep it that way :)