commit bae714096f1a0571b82261d33644223fb2957cc2 parent 2ec551087972ddb3535b0147de2c9c4b0620ee73 Author: Drew DeVault <sir@cmpwn.com> Date: Sun, 7 Mar 2021 09:24:57 -0500 strings: add try_from_utf8 Diffstat:
M | strings/utf8.ha | | | 10 | ++++++++++ |
1 file changed, 10 insertions(+), 0 deletions(-)
diff --git a/strings/utf8.ha b/strings/utf8.ha @@ -21,6 +21,16 @@ export fn from_utf8(in: []u8) str = { return s; }; +// Converts a byte slice into a string. If the slice contains invalid UTF-8 +// sequences, void is returned instead. +export fn try_from_utf8(in: []u8) (str | utf8::invalid) = { + let s = from_utf8_unsafe(in); + if (!utf8::valid(s)) { + return utf8::invalid; + }; + return s; +}; + // Converts a string to a UTF-8 slice. export fn to_utf8(in: str) []u8 = *(&in: *[]u8);