]> git.ipfire.org Git - thirdparty/samba.git/commitdiff
util/charset: Add talloc_utf16_str[n]dup()
authorJoseph Sutton <josephsutton@catalyst.net.nz>
Wed, 15 Nov 2023 22:10:28 +0000 (11:10 +1300)
committerAndrew Bartlett <abartlet@samba.org>
Thu, 16 Nov 2023 05:18:36 +0000 (05:18 +0000)
Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
lib/util/charset/charset.h
lib/util/charset/util_unistr.c

index 40ae8d1fa4930f13db864b9dac477b9858fa3c1b..aa6917347130a9cd8ea1c93457bc7b922a241ef2 100644 (file)
@@ -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
index 7d8ff68074bb96b405ef5b83a7af48324c9f31a5..54b7b939b1bf36f339e43464dca715f83402eef0 100644 (file)
@@ -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.