chiark / gitweb /
more efficient utf32_iterator_set()
[disorder] / lib / unicode.c
CommitLineData
e5a5a138
RK
1/*
2 * This file is part of DisOrder
3 * Copyright (C) 2007 Richard Kettlewell
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
20/** @file lib/unicode.c
21 * @brief Unicode support functions
22 *
23 * Here by UTF-8 and UTF-8 we mean the encoding forms of those names (not the
35b651f0
RK
24 * encoding schemes). The primary encoding form is UTF-32 but convenience
25 * wrappers using UTF-8 are provided for a number of functions.
e5a5a138
RK
26 *
27 * The idea is that all the strings that hit the database will be in a
28 * particular normalization form, and for the search and tags database
29 * in case-folded form, so they can be naively compared within the
30 * database code.
31 *
32 * As the code stands this guarantee is not well met!
33 */
34
35#include <config.h>
36#include "types.h"
37
38#include <string.h>
39#include <stdio.h> /* TODO */
40
41#include "mem.h"
42#include "vector.h"
43#include "unicode.h"
44#include "unidata.h"
45
092f426f
RK
46/** @defgroup utf32props Unicode Code Point Properties */
47/*@{*/
48
49static const struct unidata *utf32__unidata_hard(uint32_t c);
50
51/** @brief Find definition of code point @p c
52 * @param c Code point
53 * @return Pointer to @ref unidata structure for @p c
54 *
55 * @p c can be any 32-bit value, a sensible value will be returned regardless.
56 * The returned pointer is NOT guaranteed to be unique to @p c.
57 */
58static inline const struct unidata *utf32__unidata(uint32_t c) {
59 /* The bottom half of the table contains almost everything of interest
60 * and we can just return the right thing straight away */
61 if(c < UNICODE_BREAK_START)
62 return &unidata[c / UNICODE_MODULUS][c % UNICODE_MODULUS];
63 else
64 return utf32__unidata_hard(c);
65}
66
67/** @brief Find definition of code point @p c
68 * @param c Code point
69 * @return Pointer to @ref unidata structure for @p c
70 *
71 * @p c can be any 32-bit value, a sensible value will be returned regardless.
72 * The returned pointer is NOT guaranteed to be unique to @p c.
73 *
74 * Don't use this function (although it will work fine) - use utf32__unidata()
75 * instead.
76 */
77static const struct unidata *utf32__unidata_hard(uint32_t c) {
78 if(c < UNICODE_BREAK_START)
79 return &unidata[c / UNICODE_MODULUS][c % UNICODE_MODULUS];
80 /* Within the break everything is unassigned */
81 if(c < UNICODE_BREAK_END)
82 return utf32__unidata(0xFFFF); /* guaranteed to be Cn */
83 /* Planes 15 and 16 are (mostly) private use */
84 if((c >= 0xF0000 && c <= 0xFFFFD)
85 || (c >= 0x100000 && c <= 0x10FFFD))
86 return utf32__unidata(0xE000); /* first Co code point */
87 /* Everything else above the break top is unassigned */
88 if(c >= UNICODE_BREAK_TOP)
89 return utf32__unidata(0xFFFF); /* guaranteed to be Cn */
90 /* Currently the rest is language tags and variation selectors */
91 c -= (UNICODE_BREAK_END - UNICODE_BREAK_START);
92 return &unidata[c / UNICODE_MODULUS][c % UNICODE_MODULUS];
93}
94
95/** @brief Return the combining class of @p c
96 * @param c Code point
97 * @return Combining class of @p c
98 *
99 * @p c can be any 32-bit value, a sensible value will be returned regardless.
100 */
101static inline int utf32__combining_class(uint32_t c) {
102 return utf32__unidata(c)->ccc;
103}
104
105/** @brief Return the General_Category value for @p c
106 * @param Code point
107 * @return General_Category property value
108 *
109 * @p c can be any 32-bit value, a sensible value will be returned regardless.
110 */
111static inline enum unicode_General_Category utf32__general_category(uint32_t c) {
112 return utf32__unidata(c)->general_category;
113}
114
115/** @brief Determine Grapheme_Break property
116 * @param c Code point
117 * @return Grapheme_Break property value of @p c
118 *
119 * @p c can be any 32-bit value, a sensible value will be returned regardless.
120 */
121static inline enum unicode_Grapheme_Break utf32__grapheme_break(uint32_t c) {
122 return utf32__unidata(c)->grapheme_break;
123}
124
125/** @brief Determine Word_Break property
126 * @param c Code point
127 * @return Word_Break property value of @p c
128 *
129 * @p c can be any 32-bit value, a sensible value will be returned regardless.
130 */
131static inline enum unicode_Word_Break utf32__word_break(uint32_t c) {
132 return utf32__unidata(c)->word_break;
133}
134
135/** @brief Determine Sentence_Break property
136 * @param c Code point
137 * @return Word_Break property value of @p c
138 *
139 * @p c can be any 32-bit value, a sensible value will be returned regardless.
140 */
141static inline enum unicode_Sentence_Break utf32__sentence_break(uint32_t c) {
142 return utf32__unidata(c)->sentence_break;
143}
144
145/** @brief Return true if @p c is ignorable for boundary specifications
146 * @param wb Word break property value
147 * @return non-0 if @p wb is unicode_Word_Break_Extend or unicode_Word_Break_Format
148 */
149static inline int utf32__boundary_ignorable(enum unicode_Word_Break wb) {
150 return (wb == unicode_Word_Break_Extend
151 || wb == unicode_Word_Break_Format);
152}
153
154/*@}*/
e5a5a138
RK
155/** @defgroup utftransform Functions that transform between different Unicode encoding forms */
156/*@{*/
157
158/** @brief Convert UTF-32 to UTF-8
159 * @param s Source string
160 * @param ns Length of source string in code points
161 * @param ndp Where to store length of destination string (or NULL)
162 * @return Newly allocated destination string or NULL on error
163 *
56fd389c
RK
164 * If the UTF-32 is not valid then NULL is returned. A UTF-32 code point is
165 * invalid if:
e5a5a138
RK
166 * - it codes for a UTF-16 surrogate
167 * - it codes for a value outside the unicode code space
168 *
56fd389c
RK
169 * The return value is always 0-terminated. The value returned via @p *ndp
170 * does not include the terminator.
e5a5a138
RK
171 */
172char *utf32_to_utf8(const uint32_t *s, size_t ns, size_t *ndp) {
173 struct dynstr d;
174 uint32_t c;
175
176 dynstr_init(&d);
177 while(ns > 0) {
178 c = *s++;
179 if(c < 0x80)
180 dynstr_append(&d, c);
181 else if(c < 0x0800) {
182 dynstr_append(&d, 0xC0 | (c >> 6));
183 dynstr_append(&d, 0x80 | (c & 0x3F));
184 } else if(c < 0x10000) {
56fd389c 185 if(c >= 0xD800 && c <= 0xDFFF)
e5a5a138
RK
186 goto error;
187 dynstr_append(&d, 0xE0 | (c >> 12));
188 dynstr_append(&d, 0x80 | ((c >> 6) & 0x3F));
189 dynstr_append(&d, 0x80 | (c & 0x3F));
190 } else if(c < 0x110000) {
191 dynstr_append(&d, 0xF0 | (c >> 18));
192 dynstr_append(&d, 0x80 | ((c >> 12) & 0x3F));
193 dynstr_append(&d, 0x80 | ((c >> 6) & 0x3F));
194 dynstr_append(&d, 0x80 | (c & 0x3F));
195 } else
196 goto error;
197 --ns;
198 }
199 dynstr_terminate(&d);
200 if(ndp)
201 *ndp = d.nvec;
202 return d.vec;
203error:
204 xfree(d.vec);
205 return 0;
206}
207
208/** @brief Convert UTF-8 to UTF-32
209 * @param s Source string
210 * @param ns Length of source string in code points
211 * @param ndp Where to store length of destination string (or NULL)
212 * @return Newly allocated destination string or NULL
213 *
56fd389c
RK
214 * The return value is always 0-terminated. The value returned via @p *ndp
215 * does not include the terminator.
e5a5a138
RK
216 *
217 * If the UTF-8 is not valid then NULL is returned. A UTF-8 sequence
218 * for a code point is invalid if:
219 * - it is not the shortest possible sequence for the code point
220 * - it codes for a UTF-16 surrogate
221 * - it codes for a value outside the unicode code space
222 */
223uint32_t *utf8_to_utf32(const char *s, size_t ns, size_t *ndp) {
224 struct dynstr_ucs4 d;
32b158f2 225 uint32_t c32;
e5a5a138 226 const uint8_t *ss = (const uint8_t *)s;
32b158f2 227 int n;
e5a5a138
RK
228
229 dynstr_ucs4_init(&d);
230 while(ns > 0) {
32b158f2
RK
231 const struct unicode_utf8_row *const r = &unicode_utf8_valid[*ss];
232 if(r->count <= ns) {
233 switch(r->count) {
234 case 1:
235 c32 = *ss;
236 break;
237 case 2:
238 if(ss[1] < r->min2 || ss[1] > r->max2)
239 goto error;
240 c32 = *ss & 0x1F;
241 break;
242 case 3:
243 if(ss[1] < r->min2 || ss[1] > r->max2)
244 goto error;
245 c32 = *ss & 0x0F;
246 break;
247 case 4:
248 if(ss[1] < r->min2 || ss[1] > r->max2)
249 goto error;
250 c32 = *ss & 0x07;
251 break;
252 default:
253 goto error;
254 }
e5a5a138
RK
255 } else
256 goto error;
32b158f2
RK
257 for(n = 1; n < r->count; ++n) {
258 if(ss[n] < 0x80 || ss[n] > 0xBF)
259 goto error;
260 c32 = (c32 << 6) | (ss[n] & 0x3F);
261 }
e5a5a138 262 dynstr_ucs4_append(&d, c32);
32b158f2
RK
263 ss += r->count;
264 ns -= r->count;
e5a5a138
RK
265 }
266 dynstr_ucs4_terminate(&d);
267 if(ndp)
268 *ndp = d.nvec;
269 return d.vec;
270error:
271 xfree(d.vec);
272 return 0;
273}
274
18cda350
RK
275/** @brief Test whether [s,s+ns) is valid UTF-8
276 * @param s Start of string
277 * @param ns Length of string
278 * @return non-0 if @p s is valid UTF-8, 0 if it is not valid
279 *
280 * This function is intended to be much faster than calling utf8_to_utf32() and
281 * throwing away the result.
282 */
283int utf8_valid(const char *s, size_t ns) {
284 const uint8_t *ss = (const uint8_t *)s;
285 while(ns > 0) {
286 const struct unicode_utf8_row *const r = &unicode_utf8_valid[*ss];
287 if(r->count <= ns) {
288 switch(r->count) {
289 case 1:
290 break;
291 case 2:
292 if(ss[1] < r->min2 || ss[1] > r->max2)
293 return 0;
294 break;
295 case 3:
296 if(ss[1] < r->min2 || ss[1] > r->max2)
297 return 0;
298 if(ss[2] < 0x80 || ss[2] > 0xBF)
299 return 0;
300 break;
301 case 4:
302 if(ss[1] < r->min2 || ss[1] > r->max2)
303 return 0;
304 if(ss[2] < 0x80 || ss[2] > 0xBF)
305 return 0;
306 if(ss[3] < 0x80 || ss[3] > 0xBF)
307 return 0;
308 break;
309 default:
310 return 0;
311 }
312 } else
313 return 0;
314 ss += r->count;
315 ns -= r->count;
316 }
317 return 1;
318}
319
092f426f
RK
320/*@}*/
321/** @defgroup utf32iterator UTF-32 string iterators */
322/*@{*/
323
324struct utf32_iterator_data {
325 /** @brief Start of string */
326 const uint32_t *s;
327
328 /** @brief Length of string */
329 size_t ns;
330
331 /** @brief Current position */
332 size_t n;
333
334 /** @brief Last two non-ignorable characters or (uint32_t)-1
335 *
336 * last[1] is the non-Extend/Format character just before position @p n;
337 * last[0] is the one just before that.
338 *
339 * Exception 1: if there is no such non-Extend/Format character then an
340 * Extend/Format character is accepted instead.
341 *
342 * Exception 2: if there is no such character even taking that into account
343 * the value is (uint32_t)-1.
344 */
345 uint32_t last[2];
346};
347
348/** @brief Create a new iterator pointing at the start of a string
349 * @param s Start of string
350 * @param ns Length of string
351 * @return New iterator
352 */
353utf32_iterator utf32_iterator_new(const uint32_t *s, size_t ns) {
354 utf32_iterator it = xmalloc(sizeof *it);
355 it->s = s;
356 it->ns = ns;
357 it->n = 0;
358 it->last[0] = it->last[1] = -1;
359 return it;
360}
361
362/** @brief Initialize an internal private iterator
363 * @param it Iterator
364 * @param s Start of string
365 * @param ns Length of string
366 * @param n Absolute position
367 */
368static void utf32__iterator_init(utf32_iterator it,
369 const uint32_t *s, size_t ns, size_t n) {
370 it->s = s;
371 it->ns = ns;
372 it->n = 0;
373 it->last[0] = it->last[1] = -1;
374 utf32_iterator_advance(it, n);
375}
376
377/** @brief Destroy an iterator
378 * @param it Iterator
379 */
380void utf32_iterator_destroy(utf32_iterator it) {
381 xfree(it);
382}
383
384/** @brief Find the current position of an interator
385 * @param it Iterator
386 */
387size_t utf32_iterator_where(utf32_iterator it) {
388 return it->n;
389}
390
391/** @brief Set an iterator's absolute position
392 * @param it Iterator
393 * @param n Absolute position
394 * @return 0 on success, non-0 on error
395 *
396 * It is an error to position the iterator outside the string (but acceptable
397 * to point it at the hypothetical post-final character). If an invalid value
398 * of @p n is specified then the iterator is not changed.
399 */
400int utf32_iterator_set(utf32_iterator it, size_t n) {
5617aaff
RK
401 /* We can't just jump to position @p n; the @p last[] values will be wrong.
402 * What we need is to jump a bit behind @p n and then advance forward,
403 * updating @p last[] along the way. How far back? We need to cross two
404 * non-ignorable code points as we advance forwards, so we'd better pass two
405 * such characters on the way back (if such are available).
406 */
407 size_t m = n;
408 int i;
409
410 if(n > it->ns) /* range check */
092f426f 411 return -1;
5617aaff
RK
412 for(i = 0; i < 2; ++i)
413 while(m > 0
414 && utf32__boundary_ignorable(utf32__word_break(it->s[m - 1])))
415 --m;
416 it->n = m;
417 return utf32_iterator_advance(it, n - m);
092f426f
RK
418}
419
420/** @brief Advance an iterator
421 * @param it Iterator
422 * @param count Number of code points to advance by
423 * @return 0 on success, non-0 on error
424 *
425 * It is an error to advance an iterator beyond the hypothetical post-final
426 * character of the string. If an invalid value of @p n is specified then the
427 * iterator is not changed.
428 *
429 * This function has O(n) time complexity: it works by advancing naively
430 * forwards through the string.
431 */
432int utf32_iterator_advance(utf32_iterator it, size_t count) {
433 if(count <= it->ns - it->n) {
434 while(count > 0) {
435 const uint32_t c = it->s[it->n];
436 const enum unicode_Word_Break wb = utf32__word_break(c);
437 if(it->last[1] == (uint32_t)-1
438 || !utf32__boundary_ignorable(wb)) {
439 it->last[0] = it->last[1];
440 it->last[1] = c;
441 }
442 ++it->n;
443 --count;
444 }
445 return 0;
446 } else
447 return -1;
448}
449
450/** @brief Find the current code point
451 * @param it Iterator
452 * @return Current code point or 0
453 *
454 * If the iterator points at the hypothetical post-final character of the
455 * string then 0 is returned. NB that this doesn't mean that there aren't any
456 * 0 code points inside the string!
457 */
458uint32_t utf32_iterator_code(utf32_iterator it) {
459 if(it->n < it->ns)
460 return it->s[it->n];
461 else
462 return 0;
463}
464
465/** @brief Test for a grapheme boundary
466 * @param it Iterator
467 * @return Non-0 if pointing just after a grapheme boundary, otherwise 0
468 */
469int utf32_iterator_grapheme_boundary(utf32_iterator it) {
470 uint32_t before, after;
471 enum unicode_Grapheme_Break gbbefore, gbafter;
472 /* GB1 and GB2 */
473 if(it->n == 0 || it->n == it->ns)
474 return 1;
475 /* Now we know that s[n-1] and s[n] are safe to inspect */
476 /* GB3 */
477 before = it->s[it->n-1];
478 after = it->s[it->n];
479 if(before == 0x000D && after == 0x000A)
480 return 0;
481 gbbefore = utf32__grapheme_break(before);
482 gbafter = utf32__grapheme_break(after);
483 /* GB4 */
484 if(gbbefore == unicode_Grapheme_Break_Control
485 || before == 0x000D
486 || before == 0x000A)
487 return 1;
488 /* GB5 */
489 if(gbafter == unicode_Grapheme_Break_Control
490 || after == 0x000D
491 || after == 0x000A)
492 return 1;
493 /* GB6 */
494 if(gbbefore == unicode_Grapheme_Break_L
495 && (gbafter == unicode_Grapheme_Break_L
496 || gbafter == unicode_Grapheme_Break_V
497 || gbafter == unicode_Grapheme_Break_LV
498 || gbafter == unicode_Grapheme_Break_LVT))
499 return 0;
500 /* GB7 */
501 if((gbbefore == unicode_Grapheme_Break_LV
502 || gbbefore == unicode_Grapheme_Break_V)
503 && (gbafter == unicode_Grapheme_Break_V
504 || gbafter == unicode_Grapheme_Break_T))
505 return 0;
506 /* GB8 */
507 if((gbbefore == unicode_Grapheme_Break_LVT
508 || gbbefore == unicode_Grapheme_Break_T)
509 && gbafter == unicode_Grapheme_Break_T)
510 return 0;
511 /* GB9 */
512 if(gbafter == unicode_Grapheme_Break_Extend)
513 return 0;
514 /* GB10 */
515 return 1;
516
517}
518
519/** @brief Test for a word boundary
520 * @param it Iterator
521 * @return Non-0 if pointing just after a word boundary, otherwise 0
522 */
523int utf32_iterator_word_boundary(utf32_iterator it) {
524 enum unicode_Word_Break twobefore, before, after, twoafter;
525 size_t nn;
526
527 /* WB1 and WB2 */
528 if(it->n == 0 || it->n == it->ns)
529 return 1;
530 /* WB3 */
531 if(it->s[it->n-1] == 0x000D && it->s[it->n] == 0x000A)
532 return 0;
533 /* WB4 */
534 /* (!Sep) x (Extend|Format) as in UAX #29 s6.2 */
535 if(utf32__sentence_break(it->s[it->n-1]) != unicode_Sentence_Break_Sep
536 && utf32__boundary_ignorable(utf32__word_break(it->s[it->n])))
537 return 0;
538 /* Gather the property values we'll need for the rest of the test taking the
539 * s6.2 changes into account */
540 /* First we look at the code points after the proposed boundary */
541 nn = it->n; /* <it->ns */
542 after = utf32__word_break(it->s[nn++]);
543 if(!utf32__boundary_ignorable(after)) {
544 /* X (Extend|Format)* -> X */
545 while(nn < it->ns
546 && utf32__boundary_ignorable(utf32__word_break(it->s[nn])))
547 ++nn;
548 }
549 /* It's possible now that nn=ns */
550 if(nn < it->ns)
551 twoafter = utf32__word_break(it->s[nn]);
552 else
553 twoafter = unicode_Word_Break_Other;
554
555 /* We've already recorded the non-ignorable code points before the proposed
556 * boundary */
557 before = utf32__word_break(it->last[1]);
558 twobefore = utf32__word_break(it->last[0]);
559
560 /* WB5 */
561 if(before == unicode_Word_Break_ALetter
562 && after == unicode_Word_Break_ALetter)
563 return 0;
564 /* WB6 */
565 if(before == unicode_Word_Break_ALetter
566 && after == unicode_Word_Break_MidLetter
567 && twoafter == unicode_Word_Break_ALetter)
568 return 0;
569 /* WB7 */
570 if(twobefore == unicode_Word_Break_ALetter
571 && before == unicode_Word_Break_MidLetter
572 && after == unicode_Word_Break_ALetter)
573 return 0;
574 /* WB8 */
575 if(before == unicode_Word_Break_Numeric
576 && after == unicode_Word_Break_Numeric)
577 return 0;
578 /* WB9 */
579 if(before == unicode_Word_Break_ALetter
580 && after == unicode_Word_Break_Numeric)
581 return 0;
582 /* WB10 */
583 if(before == unicode_Word_Break_Numeric
584 && after == unicode_Word_Break_ALetter)
585 return 0;
586 /* WB11 */
587 if(twobefore == unicode_Word_Break_Numeric
588 && before == unicode_Word_Break_MidNum
589 && after == unicode_Word_Break_Numeric)
590 return 0;
591 /* WB12 */
592 if(before == unicode_Word_Break_Numeric
593 && after == unicode_Word_Break_MidNum
594 && twoafter == unicode_Word_Break_Numeric)
595 return 0;
596 /* WB13 */
597 if(before == unicode_Word_Break_Katakana
598 && after == unicode_Word_Break_Katakana)
599 return 0;
600 /* WB13a */
601 if((before == unicode_Word_Break_ALetter
602 || before == unicode_Word_Break_Numeric
603 || before == unicode_Word_Break_Katakana
604 || before == unicode_Word_Break_ExtendNumLet)
605 && after == unicode_Word_Break_ExtendNumLet)
606 return 0;
607 /* WB13b */
608 if(before == unicode_Word_Break_ExtendNumLet
609 && (after == unicode_Word_Break_ALetter
610 || after == unicode_Word_Break_Numeric
611 || after == unicode_Word_Break_Katakana))
612 return 0;
613 /* WB14 */
614 return 1;
615}
616
e5a5a138
RK
617/*@}*/
618/** @defgroup utf32 Functions that operate on UTF-32 strings */
619/*@{*/
620
621/** @brief Return the length of a 0-terminated UTF-32 string
622 * @param s Pointer to 0-terminated string
623 * @return Length of string in code points (excluding terminator)
624 *
56fd389c 625 * Unlike the conversion functions no validity checking is done on the string.
e5a5a138
RK
626 */
627size_t utf32_len(const uint32_t *s) {
628 const uint32_t *t = s;
629
630 while(*t)
631 ++t;
632 return (size_t)(t - s);
633}
634
e5a5a138
RK
635/** @brief Stably sort [s,s+ns) into descending order of combining class
636 * @param s Start of array
637 * @param ns Number of elements, must be at least 1
638 * @param buffer Buffer of at least @p ns elements
639 */
640static void utf32__sort_ccc(uint32_t *s, size_t ns, uint32_t *buffer) {
641 uint32_t *a, *b, *bp;
642 size_t na, nb;
643
644 switch(ns) {
645 case 1: /* 1-element array is always sorted */
646 return;
647 case 2: /* 2-element arrays are trivial to sort */
648 if(utf32__combining_class(s[0]) > utf32__combining_class(s[1])) {
649 uint32_t tmp = s[0];
650 s[0] = s[1];
651 s[1] = tmp;
652 }
653 return;
654 default:
655 /* Partition the array */
656 na = ns / 2;
657 nb = ns - na;
658 a = s;
659 b = s + na;
660 /* Sort the two halves of the array */
661 utf32__sort_ccc(a, na, buffer);
662 utf32__sort_ccc(b, nb, buffer);
663 /* Merge them back into one, via the buffer */
664 bp = buffer;
665 while(na > 0 && nb > 0) {
666 /* We want descending order of combining class (hence <)
667 * and we want stability within combining classes (hence <=)
668 */
669 if(utf32__combining_class(*a) <= utf32__combining_class(*b)) {
670 *bp++ = *a++;
671 --na;
672 } else {
673 *bp++ = *b++;
674 --nb;
675 }
676 }
677 while(na > 0) {
678 *bp++ = *a++;
679 --na;
680 }
681 while(nb > 0) {
682 *bp++ = *b++;
683 --nb;
684 }
685 memcpy(s, buffer, ns * sizeof(uint32_t));
686 return;
687 }
688}
689
690/** @brief Put combining characters into canonical order
691 * @param s Pointer to UTF-32 string
692 * @param ns Length of @p s
693 * @return 0 on success, -1 on error
694 *
56fd389c
RK
695 * @p s is modified in-place. See Unicode 5.0 s3.11 for details of the
696 * ordering.
e5a5a138 697 *
56fd389c
RK
698 * Currently we only support a maximum of 1024 combining characters after each
699 * base character. If this limit is exceeded then -1 is returned.
e5a5a138
RK
700 */
701static int utf32__canonical_ordering(uint32_t *s, size_t ns) {
702 size_t nc;
703 uint32_t buffer[1024];
704
705 /* The ordering amounts to a stable sort of each contiguous group of
706 * characters with non-0 combining class. */
707 while(ns > 0) {
708 /* Skip non-combining characters */
709 if(utf32__combining_class(*s) == 0) {
710 ++s;
711 --ns;
712 continue;
713 }
714 /* We must now have at least one combining character; see how many
715 * there are */
716 for(nc = 1; nc < ns && utf32__combining_class(s[nc]) != 0; ++nc)
717 ;
718 if(nc > 1024)
719 return -1;
720 /* Sort the array */
721 utf32__sort_ccc(s, nc, buffer);
722 s += nc;
723 ns -= nc;
724 }
725 return 0;
726}
727
728/* Magic numbers from UAX #15 s16 */
729#define SBase 0xAC00
730#define LBase 0x1100
731#define VBase 0x1161
732#define TBase 0x11A7
733#define LCount 19
734#define VCount 21
735#define TCount 28
736#define NCount (VCount * TCount)
737#define SCount (LCount * NCount)
738
739/** @brief Guts of the decomposition lookup functions */
740#define utf32__decompose_one_generic(WHICH) do { \
bcf9ed7f 741 const uint32_t *dc = utf32__unidata(c)->WHICH; \
e5a5a138
RK
742 if(dc) { \
743 /* Found a canonical decomposition in the table */ \
744 while(*dc) \
745 utf32__decompose_one_##WHICH(d, *dc++); \
746 } else if(c >= SBase && c < SBase + SCount) { \
747 /* Mechanically decomposable Hangul syllable (UAX #15 s16) */ \
748 const uint32_t SIndex = c - SBase; \
749 const uint32_t L = LBase + SIndex / NCount; \
750 const uint32_t V = VBase + (SIndex % NCount) / TCount; \
751 const uint32_t T = TBase + SIndex % TCount; \
752 dynstr_ucs4_append(d, L); \
753 dynstr_ucs4_append(d, V); \
754 if(T != TBase) \
755 dynstr_ucs4_append(d, T); \
756 } else \
757 /* Equal to own canonical decomposition */ \
758 dynstr_ucs4_append(d, c); \
759} while(0)
760
761/** @brief Recursively compute the canonical decomposition of @p c
762 * @param d Dynamic string to store decomposition in
763 * @param c Code point to decompose (must be a valid!)
764 * @return 0 on success, -1 on error
765 */
766static void utf32__decompose_one_canon(struct dynstr_ucs4 *d, uint32_t c) {
767 utf32__decompose_one_generic(canon);
768}
769
770/** @brief Recursively compute the compatibility decomposition of @p c
771 * @param d Dynamic string to store decomposition in
772 * @param c Code point to decompose (must be a valid!)
773 * @return 0 on success, -1 on error
774 */
775static void utf32__decompose_one_compat(struct dynstr_ucs4 *d, uint32_t c) {
776 utf32__decompose_one_generic(compat);
777}
778
779/** @brief Guts of the decomposition functions */
780#define utf32__decompose_generic(WHICH) do { \
781 struct dynstr_ucs4 d; \
782 uint32_t c; \
783 \
784 dynstr_ucs4_init(&d); \
785 while(ns) { \
786 c = *s++; \
56fd389c 787 if((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF) \
e5a5a138
RK
788 goto error; \
789 utf32__decompose_one_##WHICH(&d, c); \
790 --ns; \
791 } \
792 if(utf32__canonical_ordering(d.vec, d.nvec)) \
793 goto error; \
794 dynstr_ucs4_terminate(&d); \
795 if(ndp) \
796 *ndp = d.nvec; \
797 return d.vec; \
798error: \
799 xfree(d.vec); \
800 return 0; \
801} while(0)
802
803/** @brief Canonically decompose @p [s,s+ns)
804 * @param s Pointer to string
805 * @param ns Length of string
806 * @param ndp Where to store length of result
807 * @return Pointer to result string, or NULL
808 *
809 * Computes the canonical decomposition of a string and stably sorts combining
810 * characters into canonical order. The result is in Normalization Form D and
811 * (at the time of writing!) passes the NFD tests defined in Unicode 5.0's
812 * NormalizationTest.txt.
813 *
56fd389c 814 * Returns NULL if the string is not valid for either of the following reasons:
e5a5a138
RK
815 * - it codes for a UTF-16 surrogate
816 * - it codes for a value outside the unicode code space
817 */
818uint32_t *utf32_decompose_canon(const uint32_t *s, size_t ns, size_t *ndp) {
819 utf32__decompose_generic(canon);
820}
821
822/** @brief Compatibility decompose @p [s,s+ns)
823 * @param s Pointer to string
824 * @param ns Length of string
825 * @param ndp Where to store length of result
826 * @return Pointer to result string, or NULL
827 *
828 * Computes the compatibility decomposition of a string and stably sorts
829 * combining characters into canonical order. The result is in Normalization
830 * Form KD and (at the time of writing!) passes the NFKD tests defined in
831 * Unicode 5.0's NormalizationTest.txt.
832 *
56fd389c 833 * Returns NULL if the string is not valid for either of the following reasons:
e5a5a138
RK
834 * - it codes for a UTF-16 surrogate
835 * - it codes for a value outside the unicode code space
836 */
837uint32_t *utf32_decompose_compat(const uint32_t *s, size_t ns, size_t *ndp) {
838 utf32__decompose_generic(compat);
839}
840
56fd389c
RK
841/** @brief Single-character case-fold and decompose operation */
842#define utf32__casefold_one(WHICH) do { \
bcf9ed7f 843 const uint32_t *cf = utf32__unidata(c)->casefold; \
56fd389c
RK
844 if(cf) { \
845 /* Found a case-fold mapping in the table */ \
846 while(*cf) \
847 utf32__decompose_one_##WHICH(&d, *cf++); \
848 } else \
849 utf32__decompose_one_##WHICH(&d, c); \
850} while(0)
e5a5a138
RK
851
852/** @brief Case-fold @p [s,s+ns)
853 * @param s Pointer to string
854 * @param ns Length of string
855 * @param ndp Where to store length of result
856 * @return Pointer to result string, or NULL
857 *
858 * Case-fold the string at @p s according to full default case-folding rules
56fd389c 859 * (s3.13) for caseless matching. The result will be in NFD.
e5a5a138 860 *
56fd389c 861 * Returns NULL if the string is not valid for either of the following reasons:
e5a5a138
RK
862 * - it codes for a UTF-16 surrogate
863 * - it codes for a value outside the unicode code space
864 */
865uint32_t *utf32_casefold_canon(const uint32_t *s, size_t ns, size_t *ndp) {
866 struct dynstr_ucs4 d;
867 uint32_t c;
868 size_t n;
869 uint32_t *ss = 0;
870
871 /* If the canonical decomposition of the string includes any combining
872 * character that case-folds to a non-combining character then we must
873 * normalize before we fold. In Unicode 5.0.0 this means 0345 COMBINING
874 * GREEK YPOGEGRAMMENI in its decomposition and the various characters that
875 * canonically decompose to it. */
bcf9ed7f
RK
876 for(n = 0; n < ns; ++n)
877 if(utf32__unidata(s[n])->flags & unicode_normalize_before_casefold)
e5a5a138 878 break;
e5a5a138
RK
879 if(n < ns) {
880 /* We need a preliminary decomposition */
881 if(!(ss = utf32_decompose_canon(s, ns, &ns)))
882 return 0;
883 s = ss;
884 }
885 dynstr_ucs4_init(&d);
886 while(ns) {
887 c = *s++;
56fd389c 888 if((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF)
e5a5a138 889 goto error;
56fd389c 890 utf32__casefold_one(canon);
e5a5a138
RK
891 --ns;
892 }
893 if(utf32__canonical_ordering(d.vec, d.nvec))
894 goto error;
895 dynstr_ucs4_terminate(&d);
896 if(ndp)
897 *ndp = d.nvec;
898 return d.vec;
899error:
900 xfree(d.vec);
901 xfree(ss);
902 return 0;
903}
904
56fd389c
RK
905/** @brief Compatibilit case-fold @p [s,s+ns)
906 * @param s Pointer to string
907 * @param ns Length of string
908 * @param ndp Where to store length of result
909 * @return Pointer to result string, or NULL
910 *
911 * Case-fold the string at @p s according to full default case-folding rules
912 * (s3.13) for compatibility caseless matching. The result will be in NFKD.
913 *
914 * Returns NULL if the string is not valid for either of the following reasons:
915 * - it codes for a UTF-16 surrogate
916 * - it codes for a value outside the unicode code space
917 */
918uint32_t *utf32_casefold_compat(const uint32_t *s, size_t ns, size_t *ndp) {
919 struct dynstr_ucs4 d;
920 uint32_t c;
921 size_t n;
922 uint32_t *ss = 0;
923
bcf9ed7f
RK
924 for(n = 0; n < ns; ++n)
925 if(utf32__unidata(s[n])->flags & unicode_normalize_before_casefold)
56fd389c 926 break;
56fd389c
RK
927 if(n < ns) {
928 /* We need a preliminary _canonical_ decomposition */
929 if(!(ss = utf32_decompose_canon(s, ns, &ns)))
930 return 0;
931 s = ss;
932 }
933 /* This computes NFKD(toCaseFold(s)) */
934#define compat_casefold_middle() do { \
935 dynstr_ucs4_init(&d); \
936 while(ns) { \
937 c = *s++; \
938 if((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF) \
939 goto error; \
940 utf32__casefold_one(compat); \
941 --ns; \
942 } \
943 if(utf32__canonical_ordering(d.vec, d.nvec)) \
944 goto error; \
945} while(0)
946 /* Do the inner (NFKD o toCaseFold) */
947 compat_casefold_middle();
948 /* We can do away with the NFD'd copy of the input now */
949 xfree(ss);
950 s = ss = d.vec;
951 ns = d.nvec;
952 /* Do the outer (NFKD o toCaseFold) */
953 compat_casefold_middle();
954 /* That's all */
955 dynstr_ucs4_terminate(&d);
956 if(ndp)
957 *ndp = d.nvec;
958 return d.vec;
959error:
960 xfree(d.vec);
961 xfree(ss);
962 return 0;
963}
964
e5a5a138
RK
965/** @brief Order a pair of UTF-32 strings
966 * @param a First 0-terminated string
967 * @param b Second 0-terminated string
968 * @return -1, 0 or 1 for a less than, equal to or greater than b
969 *
970 * "Comparable to strcmp() at its best."
971 */
972int utf32_cmp(const uint32_t *a, const uint32_t *b) {
973 while(*a && *b && *a == *b) {
974 ++a;
975 ++b;
976 }
977 return *a < *b ? -1 : (*a > *b ? 1 : 0);
978}
979
35b651f0
RK
980/** @brief Identify a grapheme cluster boundary
981 * @param s Start of string (must be NFD)
982 * @param ns Length of string
983 * @param n Index within string (in [0,ns].)
984 * @return 1 at a grapheme cluster boundary, 0 otherwise
985 *
986 * This function identifies default grapheme cluster boundaries as described in
987 * UAX #29 s3. It returns 1 if @p n points at the code point just after a
988 * grapheme cluster boundary (including the hypothetical code point just after
989 * the end of the string).
35b651f0 990 */
1625e11a 991int utf32_is_grapheme_boundary(const uint32_t *s, size_t ns, size_t n) {
092f426f 992 struct utf32_iterator_data it[1];
35b651f0 993
092f426f
RK
994 utf32__iterator_init(it, s, ns, n);
995 return utf32_iterator_grapheme_boundary(it);
0b7052da
RK
996}
997
998/** @brief Identify a word boundary
999 * @param s Start of string (must be NFD)
1000 * @param ns Length of string
1001 * @param n Index within string (in [0,ns].)
1002 * @return 1 at a word boundary, 0 otherwise
1003 *
1004 * This function identifies default word boundaries as described in UAX #29 s4.
1005 * It returns 1 if @p n points at the code point just after a word boundary
1006 * (including the hypothetical code point just after the end of the string).
1007 */
1008int utf32_is_word_boundary(const uint32_t *s, size_t ns, size_t n) {
092f426f 1009 struct utf32_iterator_data it[1];
0b7052da 1010
092f426f
RK
1011 utf32__iterator_init(it, s, ns, n);
1012 return utf32_iterator_word_boundary(it);
0b7052da
RK
1013}
1014
e5a5a138 1015/*@}*/
349b7b74 1016/** @defgroup utf8 Functions that operate on UTF-8 strings */
e5a5a138
RK
1017/*@{*/
1018
1019/** @brief Wrapper to transform a UTF-8 string using the UTF-32 function */
1020#define utf8__transform(FN) do { \
1021 uint32_t *to32 = 0, *decomp32 = 0; \
1022 size_t nto32, ndecomp32; \
1023 char *decomp8 = 0; \
1024 \
1025 if(!(to32 = utf8_to_utf32(s, ns, &nto32))) goto error; \
1026 if(!(decomp32 = FN(to32, nto32, &ndecomp32))) goto error; \
1027 decomp8 = utf32_to_utf8(decomp32, ndecomp32, ndp); \
1028error: \
1029 xfree(to32); \
1030 xfree(decomp32); \
1031 return decomp8; \
1032} while(0)
1033
1034/** @brief Canonically decompose @p [s,s+ns)
1035 * @param s Pointer to string
1036 * @param ns Length of string
1037 * @param ndp Where to store length of result
1038 * @return Pointer to result string, or NULL
1039 *
1040 * Computes the canonical decomposition of a string and stably sorts combining
1041 * characters into canonical order. The result is in Normalization Form D and
1042 * (at the time of writing!) passes the NFD tests defined in Unicode 5.0's
1043 * NormalizationTest.txt.
1044 *
1045 * Returns NULL if the string is not valid; see utf8_to_utf32() for reasons why
1046 * this might be.
1047 *
1048 * See also utf32_decompose_canon().
1049 */
1050char *utf8_decompose_canon(const char *s, size_t ns, size_t *ndp) {
1051 utf8__transform(utf32_decompose_canon);
1052}
1053
1054/** @brief Compatibility decompose @p [s,s+ns)
1055 * @param s Pointer to string
1056 * @param ns Length of string
1057 * @param ndp Where to store length of result
1058 * @return Pointer to result string, or NULL
1059 *
1060 * Computes the compatibility decomposition of a string and stably sorts
1061 * combining characters into canonical order. The result is in Normalization
1062 * Form KD and (at the time of writing!) passes the NFKD tests defined in
1063 * Unicode 5.0's NormalizationTest.txt.
1064 *
1065 * Returns NULL if the string is not valid; see utf8_to_utf32() for reasons why
1066 * this might be.
1067 *
1068 * See also utf32_decompose_compat().
1069 */
1070char *utf8_decompose_compat(const char *s, size_t ns, size_t *ndp) {
1071 utf8__transform(utf32_decompose_compat);
1072}
1073
1074/** @brief Case-fold @p [s,s+ns)
1075 * @param s Pointer to string
1076 * @param ns Length of string
1077 * @param ndp Where to store length of result
1078 * @return Pointer to result string, or NULL
1079 *
1080 * Case-fold the string at @p s according to full default case-folding rules
1081 * (s3.13). The result will be in NFD.
1082 *
1083 * Returns NULL if the string is not valid; see utf8_to_utf32() for reasons why
1084 * this might be.
1085 */
1086char *utf8_casefold_canon(const char *s, size_t ns, size_t *ndp) {
1087 utf8__transform(utf32_casefold_canon);
1088}
1089
1090/** @brief Compatibility case-fold @p [s,s+ns)
1091 * @param s Pointer to string
1092 * @param ns Length of string
1093 * @param ndp Where to store length of result
1094 * @return Pointer to result string, or NULL
1095 *
1096 * Case-fold the string at @p s according to full default case-folding rules
1097 * (s3.13). The result will be in NFKD.
1098 *
1099 * Returns NULL if the string is not valid; see utf8_to_utf32() for reasons why
1100 * this might be.
1101 */
e5a5a138
RK
1102char *utf8_casefold_compat(const char *s, size_t ns, size_t *ndp) {
1103 utf8__transform(utf32_casefold_compat);
1104}
e5a5a138
RK
1105
1106/*@}*/
1107
1108/*
1109Local Variables:
1110c-basic-offset:2
1111comment-column:40
1112fill-column:79
1113indent-tabs-mode:nil
1114End:
1115*/