use an accessor function for __libc data pointer when compiled as PIC
[musl] / src / multibyte / decode.c
1 /* 
2  * This code was written by Rich Felker in 2010; no copyright is claimed.
3  * This code is in the public domain. Attribution is appreciated but
4  * unnecessary.
5  */
6
7 #include <stdlib.h>
8 #include <inttypes.h>
9 #include <wchar.h>
10 #include <errno.h>
11
12 #include "internal.h"
13
14 /* Decodes UTF-8 byte-by-byte. The c argument must be initialized to 0
15  * to begin decoding; when finished it will contain the Unicode scalar
16  * value decoded. Return value is 1 if finished, 0 if in-progress, and
17  * -1 if an invalid sequence was encountered. After an invalid sequence,
18  * the state (in c) automatically resets to 0 if a continuation byte was
19  * expected to facilitate a calling idiom of immediately retrying a
20  * failed decode call after processing the invalid sequence. If the
21  * second try fails, the byte is invalid as a starter as well.
22  *
23  * A trivial usage idiom is:
24  *       while (src<end && (n=decode(dst, *src))>=0) 1[dst+=n]=0, src++;
25  */
26
27 int decode(unsigned *c, unsigned b)
28 {
29         if (!*c) {
30                 if (b < 0x80) {
31                         *c = b;
32                         return 1;
33                 } else if (b-SA >= SB-SA) {
34                         *c = FAILSTATE;
35                         return -1;
36                 }
37                 *c = bittab[b-SA];
38                 return 0;
39         }
40
41         if (OOB(*c,b)) {
42                 *c = 0;
43                 return -1;
44         }
45         *c = *c<<6 | b-0x80;
46         return !(*c&(1U<<31));
47 }