How can I find a subsequence in a &[u8] slice?

Viewed 9537

I have a &[u8] slice over a binary buffer. I need to parse it, but a lot of the methods that I would like to use (such as str::find) don't seem to be available on slices.

I've seen that I can covert both by buffer slice and my pattern to str by using from_utf8_unchecked() but that seems a little dangerous (and also really hacky).

How can I find a subsequence in this slice? I actually need the index of the pattern, not just a slice view of the parts, so I don't think split will work.

4 Answers

How about Regex on bytes? That looks very powerful. See this Rust playground demo.

extern crate regex;

use regex::bytes::Regex;

fn main() {
    //see https://doc.rust-lang.org/regex/regex/bytes/

    let re = Regex::new(r"say [^,]*").unwrap();

    let text = b"say foo, say bar, say baz";

    // Extract all of the strings without the null terminator from each match.
    // The unwrap is OK here since a match requires the `cstr` capture to match.
    let cstrs: Vec<usize> =
        re.captures_iter(text)
          .map(|c| c.get(0).unwrap().start())
          .collect();

    assert_eq!(cstrs, vec![0, 9, 18]);
}

I found the memmem crate useful for this task:

use memmem::{Searcher, TwoWaySearcher};

let search = TwoWaySearcher::new("dog".as_bytes());
assert_eq!(
    search.search_in("The quick brown fox jumped over the lazy dog.".as_bytes()),
    Some(41)
);
Related