wcrtomb.c 884 B

1234567891011121314151617181920212223242526272829303132333435363738
  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 <stdlib.h>
  7. #include <inttypes.h>
  8. #include <wchar.h>
  9. #include <errno.h>
  10. #include "internal.h"
  11. size_t wcrtomb(char *restrict s, wchar_t wc, mbstate_t *restrict st)
  12. {
  13. if (!s) return 1;
  14. if ((unsigned)wc < 0x80) {
  15. *s = wc;
  16. return 1;
  17. } else if ((unsigned)wc < 0x800) {
  18. *s++ = 0xc0 | (wc>>6);
  19. *s = 0x80 | (wc&0x3f);
  20. return 2;
  21. } else if ((unsigned)wc < 0xd800 || (unsigned)wc-0xe000 < 0x2000) {
  22. *s++ = 0xe0 | (wc>>12);
  23. *s++ = 0x80 | ((wc>>6)&0x3f);
  24. *s = 0x80 | (wc&0x3f);
  25. return 3;
  26. } else if ((unsigned)wc-0x10000 < 0x100000) {
  27. *s++ = 0xf0 | (wc>>18);
  28. *s++ = 0x80 | ((wc>>12)&0x3f);
  29. *s++ = 0x80 | ((wc>>6)&0x3f);
  30. *s = 0x80 | (wc&0x3f);
  31. return 4;
  32. }
  33. errno = EILSEQ;
  34. return -1;
  35. }