This patch adds a wrapper function to perform conversion of UTF-16
string to UTF-8 string using inline function grub_utf16_to_utf8(), but
pre-allocating necessary space for the target buffer. This behavior is
similar to existing inversed function grub_utf8_to_utf16_alloc()
in kern/misc.c.
Signed-off-by: Vitaly Kuzmichev <vitaly.kuzmichev@rtsoft.de>
---
include/grub/charset.h | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/include/grub/charset.h b/include/grub/charset.h
index 099f23fbe..4324fefb8 100644
--- a/include/grub/charset.h
+++ b/include/grub/charset.h
@@ -20,6 +20,9 @@
#define GRUB_CHARSET_HEADER 1
#include <grub/types.h>
+#include <grub/safemath.h>
+#include <grub/mm.h>
+#include <grub/i18n.h>
#define GRUB_UINT8_1_LEADINGBIT 0x80
#define GRUB_UINT8_2_LEADINGBITS 0xc0
@@ -304,6 +307,31 @@ grub_utf16_strnlen (const void *s, grub_size_t maxlen)
return len;
}
+/* Convert UTF-16 to UTF-8. Allocates buffer of necessary space. */
+static inline grub_uint8_t *
+grub_utf16_to_utf8_alloc (const void *utf16, grub_size_t maxlen,
+ grub_utf16_type_t type)
+{
+ grub_size_t len16, size;
+ grub_uint8_t *utf8;
+
+ len16 = grub_utf16_strnlen (utf16, maxlen);
+
+ /* Check for integer overflow */
+ if (grub_mul (len16, GRUB_MAX_UTF8_PER_UTF16, &size) ||
+ grub_add (size, 1, &size))
+ {
+ grub_error (GRUB_ERR_BAD_ARGUMENT, N_("string too long"));
This is too technical error. It shouldn't be marked for translation
+ return NULL;
+ }
+
+ utf8 = grub_malloc (size);
+ if (utf8)
+ *grub_utf16_to_utf8 (utf8, utf16, len16, type) = '\0';
+
+ return utf8;
+}
+
#define GRUB_MAX_UTF8_PER_LATIN1 2
/* Convert Latin1 to UTF-8. */
--
2.34.1
_______________________________________________
Grub-devel mailing list
Grub-devel@gnu.org
https://lists.gnu.org/mailman/listinfo/grub-devel