dup_wc_to_mb.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * dup_wc_to_mb: memory-allocating wrapper on wc_to_mb.
  3. *
  4. * Also dup_wc_to_mb_c: same but you already know the length of the
  5. * wide string, and you get told the length of the returned string.
  6. * (But it's still NUL-terminated, for convenience.).
  7. */
  8. #include <wchar.h>
  9. #include "putty.h"
  10. #include "misc.h"
  11. char *dup_wc_to_mb_c(int codepage, int flags, const wchar_t *string,
  12. size_t inlen, const char *defchr, size_t *outlen_p)
  13. {
  14. assert(inlen <= INT_MAX);
  15. size_t outsize = inlen+1;
  16. char *out = snewn(outsize, char);
  17. while (true) {
  18. size_t outlen = wc_to_mb(codepage, flags, string, inlen, out, outsize,
  19. defchr);
  20. /* We can only be sure we've consumed the whole input if the
  21. * output is not within a multibyte-character-length of the
  22. * end of the buffer! */
  23. if (outlen < outsize && outsize - outlen > MB_LEN_MAX) {
  24. if (outlen_p)
  25. *outlen_p = outlen;
  26. out[outlen] = '\0';
  27. return out;
  28. }
  29. sgrowarray(out, outsize, outsize);
  30. }
  31. }
  32. char *dup_wc_to_mb(int codepage, int flags, const wchar_t *string,
  33. const char *defchr)
  34. {
  35. return dup_wc_to_mb_c(codepage, flags, string, wcslen(string),
  36. defchr, NULL);
  37. }