From a6ede6f91f41ca20d02454de3bd33329d35fbbd1 Mon Sep 17 00:00:00 2001 From: Curtis McEnroe Date: Tue, 7 Aug 2018 16:24:14 -0400 Subject: Factor out allocating conversion between wcs and mbs --- pls.c | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'pls.c') diff --git a/pls.c b/pls.c index 0667036..27ede4c 100644 --- a/pls.c +++ b/pls.c @@ -20,6 +20,38 @@ #include #include +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 : // // While narrow strings provide snprintf, which makes it possible to determine -- cgit 1.4.1-2-gfad0