2 libdrawtext - a simple library for fast text rendering in OpenGL
3 Copyright (C) 2011 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #define U8_IS_FIRST(x) (((((x) >> 7) & 1) == 0) || ((((x) >> 6) & 3) == 3))
22 static const char first_mask[] = {
24 0x7f, /* single byte, 7 bits valid */
25 0x1f, /* two-bytes, 5 bits valid */
26 0xf, /* three-bytes, 4 bits valid */
27 0x7 /* four-bytes, 3 bits valid */
29 static const char first_shift[] = { 0, 7, 5, 4, 3 }; /* see above */
31 #define CONT_PREFIX 0x80
32 #define CONT_MASK 0x3f
35 /* last charcodes for 1, 2, 3 or 4-byte utf8 chars */
36 static const int utf8_lastcode[] = { 0x7f, 0x7ff, 0xfff, 0x1fffff };
38 #define prefix_mask(x) (~first_mask[x])
39 #define prefix(x) ((prefix_mask(x) << 1) & 0xff)
42 char *dtx_utf8_next_char(char *str)
44 return str + dtx_utf8_nbytes(str);
47 char *dtx_utf8_prev_char(char *ptr, char *first)
51 } while(!U8_IS_FIRST(*ptr) && ptr > first);
55 int dtx_utf8_char_code(const char *str)
57 int i, nbytes, shift, code = 0;
60 if(!U8_IS_FIRST(*str)) {
64 nbytes = dtx_utf8_nbytes(str);
65 mask = first_mask[nbytes];
68 for(i=0; i<nbytes; i++) {
73 code = (code << shift) | (*str++ & mask);
80 int dtx_utf8_nbytes(const char *str)
86 for(i=0; !U8_IS_FIRST(str[i]); i++);
90 /* count the leading 1s */
92 if(((c >> (7 - i)) & 1) == 0) {
104 int dtx_utf8_char_count(const char *str)
110 str = dtx_utf8_next_char((char*)str);
115 int dtx_utf8_char_count_range(const char *str, int nbytes)
118 while(*str && nbytes > 0) {
119 char *next = dtx_utf8_next_char((char*)str);
121 nbytes -= next - str;
124 return (nbytes < 0 && n > 0) ? n - 1 : n;
127 size_t dtx_utf8_from_char_code(int code, char *buf)
133 if(code <= utf8_lastcode[i]) {
140 for(i=0; i<(int)nbytes; i++) {
141 int idx = nbytes - i - 1;
142 int mask, shift, prefix;
147 prefix = CONT_PREFIX;
149 mask = first_mask[nbytes];
150 shift = first_shift[nbytes];
151 prefix = prefix(nbytes);
154 buf[idx] = (code & mask) | (prefix & ~mask);
161 size_t dtx_utf8_from_string(const wchar_t *str, char *buf)
167 int cbytes = dtx_utf8_from_char_code(*str++, ptr);