mbsrtowcs.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 <stdint.h>
  7. #include <wchar.h>
  8. #include <errno.h>
  9. #include "internal.h"
  10. size_t mbsrtowcs(wchar_t *restrict ws, const char **restrict src, size_t wn, mbstate_t *restrict st)
  11. {
  12. const unsigned char *s = (const void *)*src;
  13. size_t wn0 = wn;
  14. unsigned c = 0;
  15. if (st && (c = *(unsigned *)st)) {
  16. if (ws) {
  17. *(unsigned *)st = 0;
  18. goto resume;
  19. } else {
  20. goto resume0;
  21. }
  22. }
  23. if (!ws) for (;;) {
  24. if (*s-1u < 0x7f && (uintptr_t)s%4 == 0) {
  25. while (!(( *(uint32_t*)s | *(uint32_t*)s-0x01010101) & 0x80808080)) {
  26. s += 4;
  27. wn -= 4;
  28. }
  29. }
  30. if (*s-1u < 0x7f) {
  31. s++;
  32. wn--;
  33. continue;
  34. }
  35. if (*s-SA > SB-SA) break;
  36. c = bittab[*s++-SA];
  37. resume0:
  38. if (OOB(c,*s)) { s--; break; }
  39. s++;
  40. if (c&(1U<<25)) {
  41. if (*s-0x80u >= 0x40) { s-=2; break; }
  42. s++;
  43. if (c&(1U<<19)) {
  44. if (*s-0x80u >= 0x40) { s-=3; break; }
  45. s++;
  46. }
  47. }
  48. wn--;
  49. c = 0;
  50. } else for (;;) {
  51. if (!wn) {
  52. *src = (const void *)s;
  53. return wn0;
  54. }
  55. if (*s-1u < 0x7f && (uintptr_t)s%4 == 0) {
  56. while (wn>=5 && !(( *(uint32_t*)s | *(uint32_t*)s-0x01010101) & 0x80808080)) {
  57. *ws++ = *s++;
  58. *ws++ = *s++;
  59. *ws++ = *s++;
  60. *ws++ = *s++;
  61. wn -= 4;
  62. }
  63. }
  64. if (*s-1u < 0x7f) {
  65. *ws++ = *s++;
  66. wn--;
  67. continue;
  68. }
  69. if (*s-SA > SB-SA) break;
  70. c = bittab[*s++-SA];
  71. resume:
  72. if (OOB(c,*s)) { s--; break; }
  73. c = (c<<6) | *s++-0x80;
  74. if (c&(1U<<31)) {
  75. if (*s-0x80u >= 0x40) { s-=2; break; }
  76. c = (c<<6) | *s++-0x80;
  77. if (c&(1U<<31)) {
  78. if (*s-0x80u >= 0x40) { s-=3; break; }
  79. c = (c<<6) | *s++-0x80;
  80. }
  81. }
  82. *ws++ = c;
  83. wn--;
  84. c = 0;
  85. }
  86. if (!c && !*s) {
  87. if (ws) {
  88. *ws = 0;
  89. *src = 0;
  90. }
  91. return wn0-wn;
  92. }
  93. errno = EILSEQ;
  94. if (ws) *src = (const void *)s;
  95. return -1;
  96. }