strspn/
strspn.rs

1extern crate cbitset;
2
3use cbitset::BitSet256;
4
5fn main() {
6    println!("The first {} bytes of \"hello\" are in \"eh\"",   strspn(b"hello", b"eh"));
7    println!("The first {} bytes of \"hello\" are in \"ehlo\"", strspn(b"hello", b"ehlo"));
8    println!("The first {} bytes of \"it works\" are letters",  strspn(b"it works", b"abcdefghijklmnopqrstuwxyz"));
9}
10
11/// The C standard library function strspn, reimplemented in rust. It works by
12/// placing all allowed values in a bit set, and returning on the first
13/// character not on the list. A BitSet256 uses no heap allocations and only 4
14/// 64-bit integers in stack memory.
15fn strspn(s: &[u8], accept: &[u8]) -> usize {
16    let mut allow = BitSet256::new();
17
18    for &c in accept {
19        allow.insert(c as usize);
20    }
21
22    for (i, &c) in s.iter().enumerate() {
23        if !allow.contains(c as usize) {
24            return i;
25        }
26    }
27    s.len()
28}