wcsnrtombs.c 903 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. size_t wcsnrtombs(char *restrict dst, const wchar_t **restrict wcs, size_t wn, size_t n, mbstate_t *restrict st)
  8. {
  9. size_t l, cnt=0, n2;
  10. char *s, buf[256];
  11. const wchar_t *ws = *wcs;
  12. if (!dst) s = buf, n = sizeof buf;
  13. else s = dst;
  14. while ( ws && n && ( (n2=wn)>=n || n2>32 ) ) {
  15. if (n2>=n) n2=n;
  16. wn -= n2;
  17. l = wcsrtombs(s, &ws, n2, 0);
  18. if (!(l+1)) {
  19. cnt = l;
  20. n = 0;
  21. break;
  22. }
  23. if (s != buf) {
  24. s += l;
  25. n -= l;
  26. }
  27. cnt += l;
  28. }
  29. if (ws) while (n && wn) {
  30. l = wcrtomb(s, *ws, 0);
  31. if ((l+1)<=1) {
  32. if (!l) ws = 0;
  33. else cnt = l;
  34. break;
  35. }
  36. ws++; wn--;
  37. /* safe - this loop runs fewer than sizeof(buf) times */
  38. s+=l; n-=l;
  39. cnt++;
  40. }
  41. if (dst) *wcs = ws;
  42. return cnt;
  43. }