4 ms·
Rust strings are guaranteed to be valid utf-8. Mutating a string byte directly might result in an invalid String. You perform a free conversion to bytes, mutate
by ibraheemdev 5y ago
Rust strings are guaranteed to be valid utf-8. Mutating a string byte directly might result in an invalid String. You perform a free conversion to bytes, mutate the slice, and then perform an free but unsafe conversion back to String, or a potentially expensive but safe (utf-8 validation) conversion. If you want to handle non-ascii, then you must search the string for unicode character indices, which is not free.
- patrick451 5y agoI don't know rust, but it sounds like you're saying that indexing into a string gives you the i-th byte, not the i-th unicode character. If so, that sounds like a design flaw.
- ibraheemdev 5y agoNo, you cannot index into a string directly. You must either convert it to bytes to index by byte, or call `.chars()` to get an iterator over unicode scalars. The former is free, but the latter requires searching for character indices.
- TheCoelacanth 5y agoThere is no valid use case for indexing into a unicode string by character. Any language that allows you to do that has a design flaw.
- wtetzner 5y agoThere isn't really even a good definition for "character" in unicode. There are code points, grapheme clusters, etc.