toUtf8
The returned slice is guaranteed to be valid utf8. If the passed in slice already was valid, the same slice will be returned. Otherwise, a new slice will be allocated.
const some_text = "This is some maybe utf8 text";
const utf8_text = try toUtf8(alloc, some_text);
// Detect if the text needs to be freed by checking the
defer if (utf8_text.ptr != some_text.ptr) alloc.free(utf8_text);
Parameters
- allocator:std.mem.Allocator
- std.mem.Allocator
- text:[]const u8
- []const u8
Source
Implementation
pub fn toUtf8(allocator: std.mem.Allocator, text: []const u8) std.mem.Allocator.Error![]const u8 {
if (std.unicode.utf8ValidateSlice(text)) return text;
return std.fmt.allocPrint(allocator, "{f}", .{std.unicode.fmtUtf8(text)});
}