New module 'uninorm/decomposition'.
[gnulib.git] / lib / uninorm / decomposition.c
1 /* Decomposition of Unicode characters.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2009.
4
5    This program is free software: you can redistribute it and/or modify it
6    under the terms of the GNU Lesser General Public License as published
7    by the Free Software Foundation; either version 3 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,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
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/>.  */
17
18 #include <config.h>
19
20 /* Specification.  */
21 #include "uninorm.h"
22
23 #include "decomposition-table.h"
24
25 int
26 uc_decomposition (ucs4_t uc, int *decomp_tag, ucs4_t *decomposition)
27 {
28   if (uc >= 0xAC00 && uc < 0xD7A4)
29     {
30       /* Hangul syllable.  See Unicode standard, chapter 3,
31          section "Hangul Syllable Decomposition".  */
32       unsigned int t, v, l;
33
34       uc -= 0xAC00;
35       t = uc % 28;
36       uc = uc / 28;
37       v = uc % 21;
38       l = uc / 21;
39
40       *decomp_tag = UC_DECOMP_CANONICAL;
41       decomposition[0] = 0x1100 + l;
42       decomposition[1] = 0x1161 + v;
43       if (t == 0)
44         return 2;
45       else
46         {
47           decomposition[2] = 0x11A7 + t;
48           return 3;
49         }
50     }
51   else if (uc < 0x110000)
52     {
53       unsigned short entry = decomp_index (uc);
54       if (entry != (unsigned short)(-1))
55         {
56           const unsigned char *p;
57           unsigned int element;
58           unsigned int length;
59
60           p = &gl_uninorm_decomp_chars_table[3 * (entry & 0x7FFF)];
61           element = (p[0] << 16) | (p[1] << 8) | p[2];
62           /* The first element has 5 bits for the decomposition type.  */
63           *decomp_tag = (element >> 18) & 0x1f;
64           length = 1;
65           for (;;)
66             {
67               /* Every element has an 18 bits wide Unicode code point.  */
68               *decomposition = element & 0x3ffff;
69               /* Bit 23 tells whether there are more elements,  */
70               if ((element & (1 << 23)) == 0)
71                 break;
72               p += 3;
73               element = (p[0] << 16) | (p[1] << 8) | p[2];
74               decomposition++;
75               length++;
76             }
77           return length;
78         }
79     }
80   return -1;
81 }