I want to extract the payload of a http request, that I get as a vector of bytes.
In the request, the payload is separated from the rest by the sequence \r\n\r\n, that's why I want to split my vec at this position, and take the second element.
My current solution is to use the following function I wrote.
13 is the ASCII value of \r and 10 the value of \n. I then split by the returned index. While this solution is technically working, it feels very unclean, and I was wondering how to do this in a more elegant way.
fn find_payload_index(buffer: &[u8]) -> Option<usize> {
buffer
.windows(4)
.enumerate()
.find(|&(_, w)| matches!(w, b"\r\n\r\n"))
.map(|(ix, _)| ix + 4)
// or if you want to have the "if nothing found: return 0" behavior, you can instead
// use a `.map_or(0, |(ix, _)| ix + 4)` call, and change the return type back
}
I've seen this solution several times on this kind of questions. But I'm still feeling curious - if there are any KMP based implementations of splits/finds in Rust std (probably not) or among popular crates. Since it provides better asymptotics (n + m vs n*m)