strspn/
strspn.rs

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