خرید بک لینک

Vote count: 0

I have two &str pointing to the same string, I need to know the byte offset between them.

Eg.:

fn main() {
    let foo = "  bar";
    assert_eq!(offset(foo, foo.trim()), Some(2));

    let bar = "baznquz";
    let mut lines = bar.lines();
    assert_eq!(offset(bar, lines.next().unwrap()), Some(0));
    assert_eq!(offset(bar, lines.next().unwrap()), Some(4));

    assert_eq!(offset(foo, bar), None); // not a sub-string

    let quz = "quz".to_owned();
    assert_eq!(offset(bar, &quz), None); // not the same string, could also retu `Some(4)`, I don't care
}

This is basically the same as str::find, but since the second slice is a sub-slice of the first, I would have hoped about something faster. Also str::find won't work in the lines() case if several lines are identical.

I though I could just use some pointer arithmetic to do that with something like foo.trim().as_ptr() - foo.as_ptr() but it tus out that Sub is not implemented on raw pointers.

Is there any way I could do that?

asked 24 secs ago

برچسب: نویسنده: استخدام کار تاريخ: جمعه 18 تير 1395 ساعت: 21:12

صفحه بندی