silk.text.byte_search.
Fast searches over byte slices: the first or last position of a byte, the first of two or three bytes, the number of times a byte occurs, and the first position of a byte sequence.
When to use#
Use these functions instead of a byte-by-byte loop when scanning text or binary data, for example to find the end of a line, a delimiter or a header name.
Details#
On CPUs with 128-bit vectors (x86-64, AArch64, and wasm32 with simd128), each function
compares sixteen bytes at a time with silk.simd.u8x16 and finishes the last bytes one by
one. Elsewhere it is a plain loop. The results are the same everywhere; only the speed
differs. findSlice filters candidates by the first and last byte of the needle, then
compares the whole needle at each candidate.
Examples#
Split off the first line#
import silk.text.byte_search
import silk.core.option { Option }
pub fn main() -> i32 {
let text = b"GET / HTTP/1.1\r\nHost: example.com\r\n"
let end = match byte_search.findSlice(text, b"\r\n") {
Option<usize>.Some { value } => value
Option<usize>.None => { return 1 }
}
if end != 14 || byte_search.count(text, 10) != 2 {
return 1
}
return 0
}Import as byte_search with import silk.text.byte_search as byte_search.
Public declarations: 6.
find#
pub fn find(haystack: &[u8], wanted: u8) -> Option<usize>Returns the index of the first byte of haystack equal to wanted, or none.
findLast#
pub fn findLast(haystack: &[u8], wanted: u8) -> Option<usize>Returns the index of the last byte of haystack equal to wanted, or none.
find2#
pub fn find2(haystack: &[u8], first: u8, second: u8) -> Option<usize>Returns the index of the first byte of haystack equal to first or second, or none.
find3#
pub fn find3(haystack: &[u8], first: u8, second: u8, third: u8) -> Option<usize>Returns the index of the first byte of haystack equal to first, second or third, or
none.
count#
pub fn count(haystack: &[u8], wanted: u8) -> usizeReturns the number of bytes of haystack equal to wanted.
findSlice#
pub fn findSlice(haystack: &[u8], needle: &[u8]) -> Option<usize>Returns the index where needle first occurs in haystack, or none. An empty needle
occurs at 0.
Category: Text.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2.