From: Joseph Sutton Date: Wed, 15 Nov 2023 22:10:28 +0000 (+1300) Subject: util/charset: Add talloc_utf16_str[n]dup() X-Git-Tag: talloc-2.4.2~665 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=939ceb233ef94a0d2d45da39076ba3e78665c776;p=thirdparty%2Fsamba.git util/charset: Add talloc_utf16_str[n]dup() Signed-off-by: Joseph Sutton Reviewed-by: Andrew Bartlett --- diff --git a/lib/util/charset/charset.h b/lib/util/charset/charset.h index 40ae8d1fa49..aa691734713 100644 --- a/lib/util/charset/charset.h +++ b/lib/util/charset/charset.h @@ -129,6 +129,10 @@ limited by 'n' bytes **/ size_t utf16_null_terminated_len_n(const void *src, size_t n); +uint16_t *talloc_utf16_strlendup(TALLOC_CTX *mem_ctx, const char *str, size_t len); +uint16_t *talloc_utf16_strdup(TALLOC_CTX *mem_ctx, const char *str); +uint16_t *talloc_utf16_strndup(TALLOC_CTX *mem_ctx, const char *str, size_t n); + char *strchr_m(const char *s, char c); /** * Calculate the number of units (8 or 16-bit, depending on the diff --git a/lib/util/charset/util_unistr.c b/lib/util/charset/util_unistr.c index 7d8ff68074b..54b7b939b1b 100644 --- a/lib/util/charset/util_unistr.c +++ b/lib/util/charset/util_unistr.c @@ -243,6 +243,50 @@ size_t utf16_null_terminated_len_n(const void *src, size_t n) return len; } +uint16_t *talloc_utf16_strlendup(TALLOC_CTX *mem_ctx, const char *str, size_t len) +{ + uint16_t *new_str = NULL; + + /* Check for overflow. */ + if (len > SIZE_MAX - 2) { + return NULL; + } + + /* + * Allocate the new string, including space for the + * UTF‐16 null terminator. + */ + new_str = talloc_size(mem_ctx, len + 2); + if (new_str == NULL) { + return NULL; + } + + memcpy(new_str, str, len); + + { + /* + * Ensure that the UTF‐16 string is + * null‐terminated. + */ + + char *new_bytes = (char *)new_str; + + new_bytes[len] = '\0'; + new_bytes[len + 1] = '\0'; + } + + return new_str; +} + +uint16_t *talloc_utf16_strdup(TALLOC_CTX *mem_ctx, const char *str) +{ + return talloc_utf16_strlendup(mem_ctx, str, utf16_len(str)); +} + +uint16_t *talloc_utf16_strndup(TALLOC_CTX *mem_ctx, const char *str, size_t n) +{ + return talloc_utf16_strlendup(mem_ctx, str, utf16_len_n(str, n)); +} /** * Determine the length and validity of a utf-8 string.