2 * UTF-8 utility functions
4 * (c) 2010 Steve Bennett <steveb@workware.net.au>
6 * See LICENCE for licence details.
16 int utf8_fromunicode(char *p, unsigned short uc)
22 else if (uc <= 0x7ff) {
23 *p++ = 0xc0 | ((uc & 0x7c0) >> 6);
24 *p = 0x80 | (uc & 0x3f);
28 *p++ = 0xe0 | ((uc & 0xf000) >> 12);
29 *p++ = 0x80 | ((uc & 0xfc0) >> 6);
30 *p = 0x80 | (uc & 0x3f);
35 int utf8_charlen(int c)
37 if ((c & 0x80) == 0) {
40 if ((c & 0xe0) == 0xc0) {
43 if ((c & 0xf0) == 0xe0) {
46 if ((c & 0xf8) == 0xf0) {
49 /* Invalid sequence */
53 int utf8_strlen(const char *str, int bytelen)
57 bytelen = strlen(str);
61 int l = utf8_tounicode(str, &c);
69 int utf8_index(const char *str, int index)
74 s += utf8_tounicode(s, &c);
79 int utf8_charequal(const char *s1, const char *s2)
83 utf8_tounicode(s1, &c1);
84 utf8_tounicode(s2, &c2);
89 int utf8_tounicode(const char *str, int *uc)
91 unsigned const char *s = (unsigned const char *)str;
98 if ((s[1] & 0xc0) == 0x80) {
99 *uc = ((s[0] & ~0xc0) << 6) | (s[1] & ~0x80);
103 else if (s[0] < 0xf0) {
104 if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80)) {
105 *uc = ((s[0] & ~0xe0) << 12) | ((s[1] & ~0x80) << 6) | (s[2] & ~0x80);
110 /* Invalid sequence, so just return the byte */