From 2ee0db4c5dbf1a5d956fc4a338781b48e812c85b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20Michaj=C5=82ow?= Date: Sun, 17 Mar 2024 12:54:06 +0100 Subject: [PATCH] misc/bstr: add bstr_to_wchar for win32 Convenience to avoid strlen above other things. --- misc/bstr.c | 20 ++++++++++++++++++++ misc/bstr.h | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/misc/bstr.c b/misc/bstr.c index 4f1e8629b3..abe688bd14 100644 --- a/misc/bstr.c +++ b/misc/bstr.c @@ -467,3 +467,23 @@ bool bstr_decode_hex(void *talloc_ctx, struct bstr hex, struct bstr *out) *out = (struct bstr){ .start = arr, .len = len }; return true; } + +#ifdef _WIN32 + +#include + +int bstr_to_wchar(void *talloc_ctx, struct bstr s, wchar_t **ret) +{ + int count = MultiByteToWideChar(CP_UTF8, 0, s.start, s.len, NULL, 0); + if (count <= 0) + abort(); + wchar_t *wbuf = *ret; + if (!wbuf || ta_get_size(wbuf) < (count + 1) * sizeof(wchar_t)) + wbuf = talloc_realloc(talloc_ctx, wbuf, wchar_t, count + 1); + MultiByteToWideChar(CP_UTF8, 0, s.start, s.len, wbuf, count); + wbuf[count] = L'\0'; + *ret = wbuf; + return count; +} + +#endif diff --git a/misc/bstr.h b/misc/bstr.h index dc8ad4030c..3da4f1639f 100644 --- a/misc/bstr.h +++ b/misc/bstr.h @@ -223,6 +223,12 @@ static inline bool bstr_eatend0(struct bstr *s, const char *prefix) return bstr_eatend(s, bstr0(prefix)); } +#ifdef _WIN32 + +int bstr_to_wchar(void *talloc_ctx, struct bstr s, wchar_t **ret); + +#endif + // create a pair (not single value!) for "%.*s" printf syntax #define BSTR_P(bstr) (int)((bstr).len), ((bstr).start ? (char*)(bstr).start : "")