3 ms·
str::find performs a substring search, which is incorrect if the same token appears more than once. What I want is the literal offset of a string slice in anot
by ridiculous_fish 6y ago
str::find performs a substring search, which is incorrect if the same token appears more than once.
What I want is the literal offset of a string slice in another, aka pointer arithmetic in C:
fn derp() -> usize {
let src = "xxxxxxx";
let tok = &src[3..4];
let offset = tok.as_ptr() - src.as_ptr();
offset // should be 3
}
this should be doable safely; I think it's just an annoying hole in the API.
- steveklabnik 6y agocast both of those as_ptr()s to usize and this does what you want.
- defen 6y agoI know it's just an example, but in case anyone tries to grab the code - it's worth noting that this will panic if you try to slice into the middle of a UTF-8 sequence, and will give byte offsets and not char offsets, so it might not give the answer you expect if src contains multibyte chars before tok. Also I'm fairly new to Rust so it's possible there's some other way to do it that I just don't know about.
- masklinn 6y ago> What I want is the literal offset of a string slice in another, aka pointer arithmetic in C: I see, I'd misunderstood the original, sorry. > this should be doable safely The language doesn't know that there's any relationship between those two strings, so the method would probably need to be fallible, and be more convoluted than this.