struct / union in initializer, RFE #901.
[sdcc.git] / sdcc / device / lib / pic14 / libc / mbrtowc.c
blobe62bc04b8677dc1d63e0815519bae584b983382e
1 /*-------------------------------------------------------------------------
2 mbrtowc.c - convert a multibyte sequence to a wide character
4 Copyright (C) 2016, Philipp Klaus Krause, pkk@spth.de
6 Modifications for PIC14 by
7 Copyright (C) 2019 Gonzalo Pérez de Olaguer Córdoba <salo@gpoc.es>
9 This library is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this library; see the file COPYING. If not, write to the
21 Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
22 MA 02110-1301, USA.
24 As a special exception, if you link this library with other files,
25 some of which are compiled with SDCC, to produce an executable,
26 this library does not by itself cause the resulting executable to
27 be covered by the GNU General Public License. This exception does
28 not however invalidate any other reasons why the executable file
29 might be covered by the GNU General Public License.
30 -------------------------------------------------------------------------*/
32 #include <wchar.h>
33 #include <errno.h>
35 size_t mbrtowc(wchar_t *restrict pwc, const char *restrict s, size_t n, mbstate_t *restrict ps)
37 unsigned char first_byte;
38 unsigned char seqlen;
39 char mbseq[4];
40 wchar_t codepoint;
41 unsigned char i, j;
42 static mbstate_t sps;
44 if(!s)
45 #if defined(__SDCC_pic14)
46 /* try to minimize nested calls */
47 { pwc = 0; s = ""; n = 1; }
48 #else
49 return(mbrtowc(0, "", 1, ps));
50 #endif
51 if(!n)
52 goto eilseq;
53 if(!ps)
55 ps = &sps;
58 for(i = 0; ps->c[i] && i < 3; i++)
59 mbseq[i] = ps->c[i];
61 seqlen = 1;
62 first_byte = ps->c[0] ? ps->c[0] : *s;
64 if(first_byte & 0x80)
66 while (first_byte & (0x80 >> seqlen))
67 seqlen++;
68 first_byte &= (0xff >> (seqlen + 1));
71 if(seqlen > 4)
72 goto eilseq;
74 if(i + n < seqlen) // Incomplete multibyte character
76 for(;n-- ; i++)
77 ps->c[i] = *s++;
78 return(-2);
81 for(j = 0; j < i; j++)
82 ps->c[j] = 0;
84 for(n = 1, i = i ? i : 1; i < seqlen; i++, n++)
86 mbseq[i] = *s++;
87 if((mbseq[i] & 0xc0) != 0x80)
88 goto eilseq;
91 codepoint = first_byte;
93 for(s = mbseq + 1, seqlen--; seqlen; seqlen--)
95 codepoint <<= 6;
96 codepoint |= (*s & 0x3f);
97 s++;
100 if(codepoint >= 0xd800 && codepoint <= 0xdfff) // UTF-16 surrogate.
101 return(-1);
103 if(pwc)
104 *pwc = codepoint;
105 return(n);
107 eilseq:
108 errno = EILSEQ;
109 return(-1);