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.
Code
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
}What the code does
Rabin Karp Rolling Hash Pattern Match (Rust) reduces to the function rabin_karp.
Iteration happens inside for _ in 0..m-1 { h = (h * base) % mod_; } — everything outside it runs once.
Applying it
The main signature reads fn rabin_karp(text: &str, pattern: &str) -> Vec<usize>
The surface worth importing is rabin_karp; the helpers around it are private to the snippet.
Statements that matter
let t: Vec<u8> = text.bytes().collect(); let p: Vec<u8> = pattern.bytes().collect();
if m == 0 || m > n { return vec![]; }
Interactive Tools for This Topic
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `rabin_karp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.