[PATCH 17/30] lib: wchar: add wctomb and mbtowc

Ahmad Fatoum a.fatoum at pengutronix.de
Mon Nov 22 00:47:19 PST 2021


We currently convert wchar_t to char by truncating to 8-bit.
In future, we may want to do UTF-16 to UTF-8 conversion.
Prepare for this by wrapping each conversion direction in a function.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 include/wchar.h |  5 +++++
 lib/wchar.c     | 22 ++++++++++++++++++++--
 2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/include/wchar.h b/include/wchar.h
index b601cc62079b..fb9b127a8c04 100644
--- a/include/wchar.h
+++ b/include/wchar.h
@@ -17,4 +17,9 @@ char *strdup_wchar_to_char(const wchar_t *src);
 
 size_t wcslen(const wchar_t *s);
 
+#define MB_CUR_MAX 4
+
+int mbtowc(wchar_t *pwc, const char *s, size_t n);
+int wctomb(char *s, wchar_t wc);
+
 #endif /* __WCHAR_H */
diff --git a/lib/wchar.c b/lib/wchar.c
index 4d49431e8653..3be228b5a77a 100644
--- a/lib/wchar.c
+++ b/lib/wchar.c
@@ -44,12 +44,30 @@ wchar_t *strdup_wchar(const wchar_t *src)
 	return tmp;
 }
 
+int mbtowc(wchar_t *pwc, const char *s, size_t n)
+{
+	if (!s)
+		return 0; /* we don't mantain a non-trivial shift state */
+
+	if (n < 1)
+		return -1;
+
+	*pwc = *s;
+	return 1;
+}
+
+int wctomb(char *s, wchar_t wc)
+{
+	*s = wc & 0xFF;
+	return 1;
+}
+
 char *strcpy_wchar_to_char(char *dst, const wchar_t *src)
 {
 	char *ret = dst;
 
 	while (*src)
-		*dst++ = *src++ & 0xff;
+		wctomb(dst++, *src++);
 
 	*dst = 0;
 
@@ -61,7 +79,7 @@ wchar_t *strcpy_char_to_wchar(wchar_t *dst, const char *src)
 	wchar_t *ret = dst;
 
 	while (*src)
-		*dst++ = *src++;
+		mbtowc(dst++, src++, 1);
 
 	*dst = 0;
 
-- 
2.30.2




More information about the barebox mailing list