4 ms·
UTF-8 substrings can't find a misaligned match, because of the way UTF-8 is encoded. First bytes are unambiguous. I had to write "rfind" in Rust, and here it i
by Animats 10y ago
UTF-8 substrings can't find a misaligned match, because of the way UTF-8 is encoded. First bytes are unambiguous. I had to write "rfind" in Rust, and here it is:
fn rfind(s: &[&str], key: &str) -> Option<usize> {
(0 .. s.len()).rev().find(|&i| s[i] == key)
}
No need to explicitly worry about rune boundaries.
This, like forward find, returns a byte index into a UTF-8 string. Explicit byte indices into UTF-8 strings are troublesome.
- Manishearth 10y ago> because of the way UTF-8 is encoded. Yes, I know, I mention this in my blog post :) Rust's indexing methods on strings actually do operate on byte indices. You can't do `"foo"[2]`, but you can do `"foo[2..3]"`, and it will panic if you are not on a boundary. Nobody uses this (like you say, it's troublesome) :P I've seen folks just break out the byte/char iterator whenever they need something more complicated, because usually they do need to iterate anyway. Rust internally stores slices as byte indices (well, pointer + byte length), but the compiler enforces the validity of that.
- dbaupp 10y agoIncidentally, that function could be s.iter().rev().position(|ss| ss == key), or drop the `rev()` and use `.rposition(...)` if one wants indices from the start of the slice. Although I'm not sure how searching a slice of strings for a specific one is related to UTF-8: the &str's are used completely opaquely. Did you mean to be searching a &str itself?