mbtowc.c 970 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <stdlib.h>
  2. #include <wchar.h>
  3. #include <errno.h>
  4. #include "internal.h"
  5. int mbtowc(wchar_t *restrict wc, const char *restrict src, size_t n)
  6. {
  7. unsigned c;
  8. const unsigned char *s = (const void *)src;
  9. wchar_t dummy;
  10. if (!s) return 0;
  11. if (!n) goto ilseq;
  12. if (!wc) wc = &dummy;
  13. if (*s < 0x80) return !!(*wc = *s);
  14. if (MB_CUR_MAX==1) return (*wc = CODEUNIT(*s)), 1;
  15. if (*s-SA > SB-SA) goto ilseq;
  16. c = bittab[*s++-SA];
  17. /* Avoid excessive checks against n: If shifting the state n-1
  18. * times does not clear the high bit, then the value of n is
  19. * insufficient to read a character */
  20. if (n<4 && ((c<<(6*n-6)) & (1U<<31))) goto ilseq;
  21. if (OOB(c,*s)) goto ilseq;
  22. c = c<<6 | *s++-0x80;
  23. if (!(c&(1U<<31))) {
  24. *wc = c;
  25. return 2;
  26. }
  27. if (*s-0x80u >= 0x40) goto ilseq;
  28. c = c<<6 | *s++-0x80;
  29. if (!(c&(1U<<31))) {
  30. *wc = c;
  31. return 3;
  32. }
  33. if (*s-0x80u >= 0x40) goto ilseq;
  34. *wc = c<<6 | *s++-0x80;
  35. return 4;
  36. ilseq:
  37. errno = EILSEQ;
  38. return -1;
  39. }