scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

mbrtowc.c (748B)


      1 #include <wchar.h>
      2 
      3 #include "../libc.h"
      4 
      5 #undef mbrtowc
      6 
      7 size_t
      8 mbrtowc(wchar_t *restrict pwc, const char *restrict s, size_t n,
      9         mbstate_t *restrict ps)
     10 {
     11 	unsigned char *t = (unsigned char *) s;
     12 	unsigned long wc;
     13 	unsigned c;
     14 	int i, len, maxlen;
     15 
     16 	if (s == NULL)
     17 		return 0;
     18 
     19 	wc = c = *t++;
     20 	for (len = 0; n > 0 && c & 0x80; --n, ++len)
     21 		c <<= 1;
     22 	if (n == 0 || len == 1 || len == 8)
     23 		return -1;
     24 	if (len == 0)
     25 		goto return_code;
     26 
     27 	wc = (c & 0xFF) >> len;
     28 	for (i = 0; i < len-1; i++) {
     29 		if (((c = *t++) & 0xC0) != 0x80)
     30 			return -1;
     31 		wc <<= 6;
     32 		wc |= c & 0x3F;
     33 	}
     34 
     35 	if (!_validutf8(wc, &maxlen) || len != maxlen)
     36 		return -1;
     37 
     38 return_code:
     39 	if (pwc)
     40 		*pwc = wc;
     41 	if (*s == '\0')
     42 		return 0;
     43 	return t - (unsigned char *) s;
     44 }