Fixup max decomposition len guarantee
[platform/upstream/glib.git] / glib / gunidecomp.c
1 /* decomp.c - Character decomposition.
2  *
3  *  Copyright (C) 1999, 2000 Tom Tromey
4  *  Copyright 2000 Red Hat, Inc.
5  *
6  * The Gnome Library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * The Gnome Library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with the Gnome Library; see the file COPYING.LIB.  If not,
18  * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  *   Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:unicode
24  * @Title: Unicode Manipulation
25  * @Short_description: functions operating on Unicode characters and
26  *     UTF-8 strings
27  * @See_also: g_locale_to_utf8(), g_locale_from_utf8()
28  *
29  * This section describes a number of functions for dealing with
30  * Unicode characters and strings.  There are analogues of the
31  * traditional <filename>ctype.h</filename> character classification
32  * and case conversion functions, UTF-8 analogues of some string utility
33  * functions, functions to perform normalization, case conversion and
34  * collation on UTF-8 strings and finally functions to convert between
35  * the UTF-8, UTF-16 and UCS-4 encodings of Unicode.
36  *
37  * The implementations of the Unicode functions in GLib are based
38  * on the Unicode Character Data tables, which are available from
39  * <ulink url="http://www.unicode.org/">www.unicode.org</ulink>.
40  * GLib 2.8 supports Unicode 4.0, GLib 2.10 supports Unicode 4.1,
41  * GLib 2.12 supports Unicode 5.0, GLib 2.16.3 supports Unicode 5.1,
42  * GLib 2.30 supports Unicode 6.0.
43  */
44
45 #include "config.h"
46
47 #include <stdlib.h>
48
49 #include "gunicode.h"
50 #include "gunidecomp.h"
51 #include "gmem.h"
52 #include "gunicomp.h"
53 #include "gunicodeprivate.h"
54
55
56 #define CC_PART1(Page, Char) \
57   ((combining_class_table_part1[Page] >= G_UNICODE_MAX_TABLE_INDEX) \
58    ? (combining_class_table_part1[Page] - G_UNICODE_MAX_TABLE_INDEX) \
59    : (cclass_data[combining_class_table_part1[Page]][Char]))
60
61 #define CC_PART2(Page, Char) \
62   ((combining_class_table_part2[Page] >= G_UNICODE_MAX_TABLE_INDEX) \
63    ? (combining_class_table_part2[Page] - G_UNICODE_MAX_TABLE_INDEX) \
64    : (cclass_data[combining_class_table_part2[Page]][Char]))
65
66 #define COMBINING_CLASS(Char) \
67   (((Char) <= G_UNICODE_LAST_CHAR_PART1) \
68    ? CC_PART1 ((Char) >> 8, (Char) & 0xff) \
69    : (((Char) >= 0xe0000 && (Char) <= G_UNICODE_LAST_CHAR) \
70       ? CC_PART2 (((Char) - 0xe0000) >> 8, (Char) & 0xff) \
71       : 0))
72
73 /**
74  * g_unichar_combining_class:
75  * @uc: a Unicode character
76  * 
77  * Determines the canonical combining class of a Unicode character.
78  * 
79  * Return value: the combining class of the character
80  *
81  * Since: 2.14
82  **/
83 gint
84 g_unichar_combining_class (gunichar uc)
85 {
86   return COMBINING_CLASS (uc);
87 }
88
89 /* constants for hangul syllable [de]composition */
90 #define SBase 0xAC00 
91 #define LBase 0x1100 
92 #define VBase 0x1161 
93 #define TBase 0x11A7
94 #define LCount 19 
95 #define VCount 21
96 #define TCount 28
97 #define NCount (VCount * TCount)
98 #define SCount (LCount * NCount)
99
100 /**
101  * g_unicode_canonical_ordering:
102  * @string: a UCS-4 encoded string.
103  * @len: the maximum length of @string to use.
104  *
105  * Computes the canonical ordering of a string in-place.  
106  * This rearranges decomposed characters in the string 
107  * according to their combining classes.  See the Unicode 
108  * manual for more information. 
109  **/
110 void
111 g_unicode_canonical_ordering (gunichar *string,
112                               gsize     len)
113 {
114   gsize i;
115   int swap = 1;
116
117   while (swap)
118     {
119       int last;
120       swap = 0;
121       last = COMBINING_CLASS (string[0]);
122       for (i = 0; i < len - 1; ++i)
123         {
124           int next = COMBINING_CLASS (string[i + 1]);
125           if (next != 0 && last > next)
126             {
127               gsize j;
128               /* Percolate item leftward through string.  */
129               for (j = i + 1; j > 0; --j)
130                 {
131                   gunichar t;
132                   if (COMBINING_CLASS (string[j - 1]) <= next)
133                     break;
134                   t = string[j];
135                   string[j] = string[j - 1];
136                   string[j - 1] = t;
137                   swap = 1;
138                 }
139               /* We're re-entering the loop looking at the old
140                  character again.  */
141               next = last;
142             }
143           last = next;
144         }
145     }
146 }
147
148 /* http://www.unicode.org/unicode/reports/tr15/#Hangul
149  * r should be null or have sufficient space. Calling with r == NULL will
150  * only calculate the result_len; however, a buffer with space for three
151  * characters will always be big enough. */
152 static void
153 decompose_hangul (gunichar s,
154                   gunichar *r,
155                   gsize *result_len)
156 {
157   gint SIndex = s - SBase;
158   gint TIndex = SIndex % TCount;
159
160   if (r)
161     {
162       r[0] = LBase + SIndex / NCount;
163       r[1] = VBase + (SIndex % NCount) / TCount;
164     }
165
166   if (TIndex)
167     {
168       if (r)
169         r[2] = TBase + TIndex;
170       *result_len = 3;
171     }
172   else
173     *result_len = 2;
174 }
175
176 /* returns a pointer to a null-terminated UTF-8 string */
177 static const gchar *
178 find_decomposition (gunichar ch,
179                     gboolean compat)
180 {
181   int start = 0;
182   int end = G_N_ELEMENTS (decomp_table);
183   
184   if (ch >= decomp_table[start].ch &&
185       ch <= decomp_table[end - 1].ch)
186     {
187       while (TRUE)
188         {
189           int half = (start + end) / 2;
190           if (ch == decomp_table[half].ch)
191             {
192               int offset;
193
194               if (compat)
195                 {
196                   offset = decomp_table[half].compat_offset;
197                   if (offset == G_UNICODE_NOT_PRESENT_OFFSET)
198                     offset = decomp_table[half].canon_offset;
199                 }
200               else
201                 {
202                   offset = decomp_table[half].canon_offset;
203                   if (offset == G_UNICODE_NOT_PRESENT_OFFSET)
204                     return NULL;
205                 }
206               
207               return &(decomp_expansion_string[offset]);
208             }
209           else if (half == start)
210             break;
211           else if (ch > decomp_table[half].ch)
212             start = half;
213           else
214             end = half;
215         }
216     }
217
218   return NULL;
219 }
220
221 /**
222  * g_unicode_canonical_decomposition:
223  * @ch: a Unicode character.
224  * @result_len: location to store the length of the return value.
225  *
226  * Computes the canonical decomposition of a Unicode character.  
227  * 
228  * Return value: a newly allocated string of Unicode characters.
229  *   @result_len is set to the resulting length of the string.
230  *
231  * Deprecated: 2.30: Use the more flexible g_unichar_fully_decompose()
232  *   instead.
233  **/
234 gunichar *
235 g_unicode_canonical_decomposition (gunichar ch,
236                                    gsize   *result_len)
237 {
238   const gchar *decomp;
239   const gchar *p;
240   gunichar *r;
241
242   /* Hangul syllable */
243   if (ch >= SBase && ch < SBase + SCount)
244     {
245       decompose_hangul (ch, NULL, result_len);
246       r = g_malloc (*result_len * sizeof (gunichar));
247       decompose_hangul (ch, r, result_len);
248     }
249   else if ((decomp = find_decomposition (ch, FALSE)) != NULL)
250     {
251       /* Found it.  */
252       int i;
253       
254       *result_len = g_utf8_strlen (decomp, -1);
255       r = g_malloc (*result_len * sizeof (gunichar));
256       
257       for (p = decomp, i = 0; *p != '\0'; p = g_utf8_next_char (p), i++)
258         r[i] = g_utf8_get_char (p);
259     }
260   else
261     {
262       /* Not in our table.  */
263       r = g_malloc (sizeof (gunichar));
264       *r = ch;
265       *result_len = 1;
266     }
267
268   return r;
269 }
270
271 /* L,V => LV and LV,T => LVT  */
272 static gboolean
273 combine_hangul (gunichar a,
274                 gunichar b,
275                 gunichar *result)
276 {
277   gint LIndex = a - LBase;
278   gint SIndex = a - SBase;
279
280   gint VIndex = b - VBase;
281   gint TIndex = b - TBase;
282
283   if (0 <= LIndex && LIndex < LCount
284       && 0 <= VIndex && VIndex < VCount)
285     {
286       *result = SBase + (LIndex * VCount + VIndex) * TCount;
287       return TRUE;
288     }
289   else if (0 <= SIndex && SIndex < SCount && (SIndex % TCount) == 0
290            && 0 < TIndex && TIndex < TCount)
291     {
292       *result = a + TIndex;
293       return TRUE;
294     }
295
296   return FALSE;
297 }
298
299 #define CI(Page, Char) \
300   ((compose_table[Page] >= G_UNICODE_MAX_TABLE_INDEX) \
301    ? (compose_table[Page] - G_UNICODE_MAX_TABLE_INDEX) \
302    : (compose_data[compose_table[Page]][Char]))
303
304 #define COMPOSE_INDEX(Char) \
305      (((Char >> 8) > (COMPOSE_TABLE_LAST)) ? 0 : CI((Char) >> 8, (Char) & 0xff))
306
307 static gboolean
308 combine (gunichar  a,
309          gunichar  b,
310          gunichar *result)
311 {
312   gushort index_a, index_b;
313
314   if (combine_hangul (a, b, result))
315     return TRUE;
316
317   index_a = COMPOSE_INDEX(a);
318
319   if (index_a >= COMPOSE_FIRST_SINGLE_START && index_a < COMPOSE_SECOND_START)
320     {
321       if (b == compose_first_single[index_a - COMPOSE_FIRST_SINGLE_START][0])
322         {
323           *result = compose_first_single[index_a - COMPOSE_FIRST_SINGLE_START][1];
324           return TRUE;
325         }
326       else
327         return FALSE;
328     }
329   
330   index_b = COMPOSE_INDEX(b);
331
332   if (index_b >= COMPOSE_SECOND_SINGLE_START)
333     {
334       if (a == compose_second_single[index_b - COMPOSE_SECOND_SINGLE_START][0])
335         {
336           *result = compose_second_single[index_b - COMPOSE_SECOND_SINGLE_START][1];
337           return TRUE;
338         }
339       else
340         return FALSE;
341     }
342
343   if (index_a >= COMPOSE_FIRST_START && index_a < COMPOSE_FIRST_SINGLE_START &&
344       index_b >= COMPOSE_SECOND_START && index_b < COMPOSE_SECOND_SINGLE_START)
345     {
346       gunichar res = compose_array[index_a - COMPOSE_FIRST_START][index_b - COMPOSE_SECOND_START];
347
348       if (res)
349         {
350           *result = res;
351           return TRUE;
352         }
353     }
354
355   return FALSE;
356 }
357
358 gunichar *
359 _g_utf8_normalize_wc (const gchar    *str,
360                       gssize          max_len,
361                       GNormalizeMode  mode)
362 {
363   gsize n_wc;
364   gunichar *wc_buffer;
365   const char *p;
366   gsize last_start;
367   gboolean do_compat = (mode == G_NORMALIZE_NFKC ||
368                         mode == G_NORMALIZE_NFKD);
369   gboolean do_compose = (mode == G_NORMALIZE_NFC ||
370                          mode == G_NORMALIZE_NFKC);
371
372   n_wc = 0;
373   p = str;
374   while ((max_len < 0 || p < str + max_len) && *p)
375     {
376       const gchar *decomp;
377       gunichar wc = g_utf8_get_char (p);
378
379       if (wc >= SBase && wc < SBase + SCount)
380         {
381           gsize result_len;
382           decompose_hangul (wc, NULL, &result_len);
383           n_wc += result_len;
384         }
385       else 
386         {
387           decomp = find_decomposition (wc, do_compat);
388
389           if (decomp)
390             n_wc += g_utf8_strlen (decomp, -1);
391           else
392             n_wc++;
393         }
394
395       p = g_utf8_next_char (p);
396     }
397
398   wc_buffer = g_new (gunichar, n_wc + 1);
399
400   last_start = 0;
401   n_wc = 0;
402   p = str;
403   while ((max_len < 0 || p < str + max_len) && *p)
404     {
405       gunichar wc = g_utf8_get_char (p);
406       const gchar *decomp;
407       int cc;
408       gsize old_n_wc = n_wc;
409           
410       if (wc >= SBase && wc < SBase + SCount)
411         {
412           gsize result_len;
413           decompose_hangul (wc, wc_buffer + n_wc, &result_len);
414           n_wc += result_len;
415         }
416       else
417         {
418           decomp = find_decomposition (wc, do_compat);
419           
420           if (decomp)
421             {
422               const char *pd;
423               for (pd = decomp; *pd != '\0'; pd = g_utf8_next_char (pd))
424                 wc_buffer[n_wc++] = g_utf8_get_char (pd);
425             }
426           else
427             wc_buffer[n_wc++] = wc;
428         }
429
430       if (n_wc > 0)
431         {
432           cc = COMBINING_CLASS (wc_buffer[old_n_wc]);
433
434           if (cc == 0)
435             {
436               g_unicode_canonical_ordering (wc_buffer + last_start, n_wc - last_start);
437               last_start = old_n_wc;
438             }
439         }
440       
441       p = g_utf8_next_char (p);
442     }
443
444   if (n_wc > 0)
445     {
446       g_unicode_canonical_ordering (wc_buffer + last_start, n_wc - last_start);
447       last_start = n_wc;
448     }
449           
450   wc_buffer[n_wc] = 0;
451
452   /* All decomposed and reordered */ 
453
454   if (do_compose && n_wc > 0)
455     {
456       gsize i, j;
457       int last_cc = 0;
458       last_start = 0;
459       
460       for (i = 0; i < n_wc; i++)
461         {
462           int cc = COMBINING_CLASS (wc_buffer[i]);
463
464           if (i > 0 &&
465               (last_cc == 0 || last_cc < cc) &&
466               combine (wc_buffer[last_start], wc_buffer[i],
467                        &wc_buffer[last_start]))
468             {
469               for (j = i + 1; j < n_wc; j++)
470                 wc_buffer[j-1] = wc_buffer[j];
471               n_wc--;
472               i--;
473               
474               if (i == last_start)
475                 last_cc = 0;
476               else
477                 last_cc = COMBINING_CLASS (wc_buffer[i-1]);
478               
479               continue;
480             }
481
482           if (cc == 0)
483             last_start = i;
484
485           last_cc = cc;
486         }
487     }
488
489   wc_buffer[n_wc] = 0;
490
491   return wc_buffer;
492 }
493
494 /**
495  * g_utf8_normalize:
496  * @str: a UTF-8 encoded string.
497  * @len: length of @str, in bytes, or -1 if @str is nul-terminated.
498  * @mode: the type of normalization to perform.
499  *
500  * Converts a string into canonical form, standardizing
501  * such issues as whether a character with an accent
502  * is represented as a base character and combining
503  * accent or as a single precomposed character. The
504  * string has to be valid UTF-8, otherwise %NULL is
505  * returned. You should generally call g_utf8_normalize()
506  * before comparing two Unicode strings.
507  *
508  * The normalization mode %G_NORMALIZE_DEFAULT only
509  * standardizes differences that do not affect the
510  * text content, such as the above-mentioned accent
511  * representation. %G_NORMALIZE_ALL also standardizes
512  * the "compatibility" characters in Unicode, such
513  * as SUPERSCRIPT THREE to the standard forms
514  * (in this case DIGIT THREE). Formatting information
515  * may be lost but for most text operations such
516  * characters should be considered the same.
517  *
518  * %G_NORMALIZE_DEFAULT_COMPOSE and %G_NORMALIZE_ALL_COMPOSE
519  * are like %G_NORMALIZE_DEFAULT and %G_NORMALIZE_ALL,
520  * but returned a result with composed forms rather
521  * than a maximally decomposed form. This is often
522  * useful if you intend to convert the string to
523  * a legacy encoding or pass it to a system with
524  * less capable Unicode handling.
525  *
526  * Return value: a newly allocated string, that is the
527  *   normalized form of @str, or %NULL if @str is not
528  *   valid UTF-8.
529  **/
530 gchar *
531 g_utf8_normalize (const gchar    *str,
532                   gssize          len,
533                   GNormalizeMode  mode)
534 {
535   gunichar *result_wc = _g_utf8_normalize_wc (str, len, mode);
536   gchar *result;
537
538   result = g_ucs4_to_utf8 (result_wc, -1, NULL, NULL, NULL);
539   g_free (result_wc);
540
541   return result;
542 }
543
544 static gboolean
545 decompose_hangul_step (gunichar  ch,
546                        gunichar *a,
547                        gunichar *b)
548 {
549   gint SIndex, TIndex;
550
551   if (ch < SBase || ch >= SBase + SCount)
552     return FALSE;  /* not a hangul syllable */
553
554   SIndex = ch - SBase;
555   TIndex = SIndex % TCount;
556
557   if (TIndex)
558     {
559       /* split LVT -> LV,T */
560       *a = ch - TIndex;
561       *b = TBase + TIndex;
562     }
563   else
564     {
565       /* split LV -> L,V */
566       *a = LBase + SIndex / NCount;
567       *b = VBase + (SIndex % NCount) / TCount;
568     }
569
570   return TRUE;
571 }
572
573 /**
574  * g_unichar_decompose:
575  * @ch: a Unicode character
576  * @a: return location for the first component of @ch
577  * @b: return location for the second component of @ch
578  *
579  * Performs a single decomposition step of the
580  * Unicode canonical decomposition algorithm.
581  *
582  * This function does not include compatibility
583  * decompositions. It does, however, include algorithmic
584  * Hangul Jamo decomposition, as well as 'singleton'
585  * decompositions which replace a character by a single
586  * other character. In the case of singletons *@b will
587  * be set to zero.
588  *
589  * If @ch is not decomposable, *@a is set to @ch and *@b
590  * is set to zero.
591  *
592  * Note that the way Unicode decomposition pairs are
593  * defined, it is guaranteed that @b would not decompose
594  * further, but @a may itself decompose.  To get the full
595  * canonical decomposition for @ch, one would need to
596  * recursively call this function on @a.  Or use
597  * g_unichar_fully_decompose().
598  *
599  * See <ulink url="http://unicode.org/reports/tr15/">UAX#15</ulink>
600  * for details.
601  *
602  * Returns: %TRUE if the character could be decomposed
603  *
604  * Since: 2.30
605  */
606 gboolean
607 g_unichar_decompose (gunichar  ch,
608                      gunichar *a,
609                      gunichar *b)
610 {
611   gint start = 0;
612   gint end = G_N_ELEMENTS (decomp_step_table);
613
614   if (decompose_hangul_step (ch, a, b))
615     return TRUE;
616
617   /* TODO use bsearch() */
618   if (ch >= decomp_step_table[start].ch &&
619       ch <= decomp_step_table[end - 1].ch)
620     {
621       while (TRUE)
622         {
623           gint half = (start + end) / 2;
624           const decomposition_step *p = &(decomp_step_table[half]);
625           if (ch == p->ch)
626             {
627               *a = p->a;
628               *b = p->b;
629               return TRUE;
630             }
631           else if (half == start)
632             break;
633           else if (ch > p->ch)
634             start = half;
635           else
636             end = half;
637         }
638     }
639
640   *a = ch;
641   *b = 0;
642
643   return FALSE;
644 }
645
646 /**
647  * g_unichar_compose:
648  * @a: a Unicode character
649  * @b: a Unicode character
650  * @ch: return location for the composed character
651  *
652  * Performs a single composition step of the
653  * Unicode canonical composition algorithm.
654  *
655  * This function does not perform algorithmic composition
656  * for Hangul characters, and does not include compatibility
657  * compositions. It does, however, include 'singleton'
658  * compositions which replace a character by a single
659  * other character. To obtain these, pass zero for @b.
660  *
661  * This function includes algorithmic Hangul Jamo composition.
662  *
663  * If @a and @b do not compose a new character, @ch is set to zero.
664  *
665  * See <ulink url="http://unicode.org/reports/tr15/">UAX#15</ulink>
666  * for details.
667  *
668  * Returns: %TRUE if the characters could be composed
669  *
670  * Since: 2.30
671  */
672 gboolean
673 g_unichar_compose (gunichar  a,
674                    gunichar  b,
675                    gunichar *ch)
676 {
677   if (combine (a, b, ch))
678     return TRUE;
679
680   *ch = 0;
681   return FALSE;
682 }
683
684 /**
685  * g_unichar_fully_decompose:
686  * @ch: a Unicode character.
687  * @compat: whether perform canonical or compatibility decomposition
688  * @result: location to store decomposed result, or %NULL
689  * @result_len: length of @result
690  *
691  * Computes the canonical or compatibility decomposition of a
692  * Unicode character.  For compatibility decomposition,
693  * pass %TRUE for @compat; for canonical decomposition
694  * pass %FALSE for @compat.
695  *
696  * The decomposed sequence is placed in @result.  Only up to
697  * @result_len characters are written into @result.  The length
698  * of the full decomposition (irrespective of @result_len) is
699  * returned by the function.  For canonical decomposition,
700  * currently all decompositions are of length at most 4, but
701  * this may change in the future (very unlikely though).
702  * At any rate, Unicode does guarantee that a buffer of length
703  * 18 is always enough for both compatibility and canonical
704  * decompositions.
705  *
706  * See <ulink url="http://unicode.org/reports/tr15/">UAX#15</ulink>
707  * for details.
708  *
709  * Return value: the length of the full decomposition.
710  *
711  * Since: 2.30
712  **/
713 gsize
714 g_unichar_fully_decompose (gunichar  ch,
715                            gboolean  compat,
716                            gunichar *result,
717                            gsize     result_len)
718 {
719   const gchar *decomp;
720   const gchar *p;
721
722   /* Hangul syllable */
723   if (ch >= SBase && ch < SBase + SCount)
724     {
725       gsize len, i;
726       gunichar buffer[3];
727       decompose_hangul (ch, result ? buffer : NULL, &len);
728       if (result)
729         for (i = 0; i < len && i < result_len; i++)
730           result[i] = buffer[i];
731       return len;
732     }
733   else if ((decomp = find_decomposition (ch, compat)) != NULL)
734     {
735       /* Found it.  */
736       gsize len, i;
737
738       len = g_utf8_strlen (decomp, -1);
739
740       for (p = decomp, i = 0; i < len && i < result_len; p = g_utf8_next_char (p), i++)
741         result[i] = g_utf8_get_char (p);
742
743       return len;
744     }
745
746   /* Does not decompose */
747   if (result && result_len >= 1)
748     *result = ch;
749   return 1;
750 }