#Cast a []const u8 to []const u21

1 messages · Page 1 of 1 (latest)

elder siren
#

The title explains it enough I thnk. I don't want to use a for loop with @intCast tho, as it seems not efficent. So I wanted to ask if there is a more efficent way?

#

Maybe std.ArrayListUnmanaged has a method to do the cast, because what I am doing is:

try line.appendSlice(allocator, s);```

where s is the []const u8 and line a std.ArrayList(u21)
glacial mantle
#

there is no cast that applies here because u8 and u21 are different sizes

#

and what exactly are you looking for here, because u21 is a very strange integer

elder siren
#

where c = u8

glacial mantle
#

and the []const u8 is UTF8?

elder siren
glacial mantle
#

because what you likely want here is a unicode iterator; the slice of u8 and the slice of unicode codepoints are very likely different lengths

#

because utf-8 is a multi-byte encoding

elder siren
#

no []const u8 is a single line of file

#
 var split = std.mem.splitScalar(u8, data, '\n');

while (split.next()) |s| {
    var line = Line{};
    errdefer line.deinit(allocator);

    try line.appendSlice(allocator, s);
    try tab.lines.append(line);
}```
glacial mantle
elder siren
#

oh wait I think I get what you're saying

glacial mantle
#

because the encoding determines how each codepoint is encoded in those bytes

elder siren
#
var iter = std.unicode.Utf8Iterator{ .bytes = s, .i = 0 };

while (iter.nextCodepoint()) |unicode_char| {
  try line.append(allocator, unicode_char);
}

try tab.lines.append(line);
#

like this?

#

where s is []const u8

glacial mantle
#

you're intended to obtain a Utf8Iterator from a Utf8View

#

but otherwise yes

#

because Utf8Iterator requires validated utf8

elder siren
elder siren
glacial mantle
#

view can be const, but yes

elder siren
elder siren
#

@glacial mantle sorry for the ping, but is there a way to convert []const u21 to []u8?

glacial mantle
#

utf8Encode

elder siren
#

so

#

iterate over []const u21

glacial mantle
elder siren
#

hmmm

#

so iterate over []const u21

#

every u21 char to utf8encode and then concat into another slice