wcrtomb.c 819 B

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