Function str_offset

Source
pub(crate) fn str_offset(haystack: &str, needle: &str) -> Option<usize>
Expand description

Return the position of one string slice within another.

If needle is indeed part of haystack, returns some offset off, such that needle is the same as &haystack[off..needle.len()].

Returns None if needle is not a part of haystack.

Remember, offsets are in bytes, not in characters.

§Example

use tor_netdoc::util::str_offset;
let quote = "A rose is a rose is a rose."; // -- Gertrude Stein
assert_eq!(&quote[2..6], "rose");
assert_eq!(str_offset(quote, &quote[2..6]).unwrap(), 2);
assert_eq!(&quote[12..16], "rose");
assert_eq!(str_offset(quote, &quote[12..16]).unwrap(), 12);
assert_eq!(&quote[22..26], "rose");
assert_eq!(str_offset(quote, &quote[22..26]).unwrap(), 22);

assert_eq!(str_offset(quote, "rose"), None);

assert_eq!(str_offset(&quote[1..], &quote[2..6]), Some(1));
assert_eq!(str_offset(&quote[1..5], &quote[2..6]), None);