diff options
author | Curtis McEnroe | 2018-08-07 16:24:14 -0400 |
---|---|---|
committer | Curtis McEnroe | 2018-08-07 16:24:14 -0400 |
commit | a6ede6f91f41ca20d02454de3bd33329d35fbbd1 (patch) | |
tree | a3d9eab30cd4ae9cca359f6649a6e2cc4a0b3299 /pls.c | |
parent | 2fe8b4e61448fed717a06300a8a7c74604a81ca0 (diff) |
Factor out allocating conversion between wcs and mbs
Diffstat (limited to 'pls.c')
-rw-r--r-- | pls.c | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/pls.c b/pls.c index 0667036..27ede4c 100644 --- a/pls.c +++ b/pls.c @@ -20,6 +20,38 @@ #include <stdlib.h> #include <wchar.h> +wchar_t *ambstowcs(const char *src) { + size_t len = mbsrtowcs(NULL, &src, 0, NULL); + if (len == (size_t)-1) return NULL; + + wchar_t *dst = malloc(sizeof(*dst) * (1 + len)); + if (!dst) return NULL; + + len = mbsrtowcs(dst, &src, 1 + len, NULL); + if (len == (size_t)-1) { + free(dst); + return NULL; + } + + return dst; +} + +char *awcstombs(const wchar_t *src) { + size_t len = wcsrtombs(NULL, &src, 0, NULL); + if (len == (size_t)-1) return NULL; + + char *dst = malloc(sizeof(*dst) * (1 + len)); + if (!dst) return NULL; + + len = wcsrtombs(dst, &src, 1 + len, NULL); + if (len == (size_t)-1) { + free(dst); + return NULL; + } + + return dst; +} + // From <https://en.cppreference.com/w/c/io/fwprintf#Notes>: // // While narrow strings provide snprintf, which makes it possible to determine |