Rabin Karp Rolling Hash Pattern Match (Rust)

Find all occurrences of a pattern in Rust text using Rabin Karp with a rolling hash for O(n+m) average time.

RustData Fetching

Code

snippet
fn rabin_karp(text: &str, pattern: &str) -> Vec<usize> {
    let (base, mod_): (i64, i64) = (256, 101);
    let t: Vec<u8> = text.bytes().collect(); let p: Vec<u8> = pattern.bytes().collect();
    let (n, m) = (t.len(), p.len());
    if m == 0 || m > n { return vec![]; }
    let mut pat_h = 0i64; let mut txt_h = 0i64; let mut h = 1i64;
    for _ in 0..m-1 { h = (h * base) % mod_; }
    for i in 0..m { pat_h = (pat_h * base + p[i] as i64) % mod_; txt_h = (txt_h * base + t[i] as i64) % mod_; }
    let mut result = vec![];
    for i in 0..=n-m { if pat_h == txt_h && &t[i..i+m] == &p[..] { result.push(i); } if i < n-m { txt_h = (base * (txt_h - t[i] as i64 * h) + t[i+m] as i64) % mod_; if txt_h < 0 { txt_h += mod_; } } }
    result
}