mbrtowc.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #include <wchar.h>
  7. #include <errno.h>
  8. #include "internal.h"
  9. size_t mbrtowc(wchar_t *restrict wc, const char *restrict src, size_t n, mbstate_t *restrict st)
  10. {
  11. static unsigned internal_state;
  12. unsigned c;
  13. const unsigned char *s = (const void *)src;
  14. const unsigned N = n;
  15. wchar_t dummy;
  16. if (!st) st = (void *)&internal_state;
  17. c = *(unsigned *)st;
  18. if (!s) {
  19. if (c) goto ilseq;
  20. return 0;
  21. } else if (!wc) wc = &dummy;
  22. if (!n) return -2;
  23. if (!c) {
  24. if (*s < 0x80) return !!(*wc = *s);
  25. if (*s-SA > SB-SA) goto ilseq;
  26. c = bittab[*s++-SA]; n--;
  27. }
  28. if (n) {
  29. if (OOB(c,*s)) goto ilseq;
  30. loop:
  31. c = c<<6 | *s++-0x80; n--;
  32. if (!(c&(1U<<31))) {
  33. *(unsigned *)st = 0;
  34. *wc = c;
  35. return N-n;
  36. }
  37. if (n) {
  38. if (*s-0x80u >= 0x40) goto ilseq;
  39. goto loop;
  40. }
  41. }
  42. *(unsigned *)st = c;
  43. return -2;
  44. ilseq:
  45. *(unsigned *)st = 0;
  46. errno = EILSEQ;
  47. return -1;
  48. }