scc

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

wcrtomb.c (454B)


      1 #include <errno.h>
      2 #include <wchar.h>
      3 
      4 #include "../libc.h"
      5 
      6 #undef wcrtomb
      7 
      8 size_t
      9 wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict ps)
     10 {
     11 	int i, n;
     12 	unsigned long c = wc;
     13 
     14 	if (!s)
     15 		return 1;
     16 
     17 	if (c < 0x80) {
     18 		*s = wc;
     19 		return 1;
     20 	}
     21 
     22 	if (!_validutf8(wc, &n)) {
     23 		errno = EILSEQ;
     24 		return -1;
     25 	}
     26 	n--;
     27 
     28 	*s = 0x80;
     29 	for (i = 0; i < n; i++) {
     30 		*s >>= 1;
     31 		*s |= 0x80;
     32 
     33 		s[n-i] = 0x80 | (c & 0x3f);
     34 		c >>= 6;
     35 	}
     36 	*s |= c;
     37 
     38 	return n+1;
     39 }