#Convert u8 to u16 string at runtime (wide string)
1 messages · Page 1 of 1 (latest)
hm, so initialize a new []u16 with the length being the result of calcUtf16LeLen of the u8 string?
and pass that to the function?
the function takes a []u16 (should be empty) and the []u8
thats as much as i could figure out
you can do something like this:
const utf8_str: []const u8 = ...;
const utf16_str: []u16 = try allocator.alloc(u16, std.unicode.calcUtf16LeLen(utf8_str));
defer allocator.free(utf16_str);
assert(utf16_str.len == try std.unicode.utf8ToUtf16Le(utf16_str, utf8_str));
oh you need an allocator
okay
thats pretty verbose still for such a simple operation
you only need the allocator if the size of the string is unknown
itll be that way in any language, some might just hide it
why do you think it's simple?
decoding a string and encoding it into an encoding of a different size is a pretty complicated operation
and for utf8 to utf16 it's pretty much impossible to do it in-place
so yeah, allocation is necessary, and counting the size in advance it is the easiest way
indeed. I'd say that's probably one of zig's greatest strengths: it makes complexity plain to see
though tbf std.unicode could probably expose a function like utf8ToUtf16LeAlloc
theres utf16leToUtf8Alloc :p
lol