I would like to classify incoming tcp streams by their first n bytes and then pass to different handlers according to the classification.
I do not want to consume any of the bytes in the stream, otherwise I will be passing invalid streams to the handlers, that start with the nth byte.
So poll_peek looks almost like what I need, as it waits for data to be available before it peeks.
However I think what I would ideally need would be a poll_peek_exact that does not return until the passed buffer is full.
This method does not seem to exist in TcpStream, so I'm not sure what the correct way would be to peek the first n bytes of a TcpStream without consuming them.
I could do something like:
// Keep peeking until we have enough bytes to decide.
while let Ok(num_bytes) = poll_fn(|cx| {
tcp_stream.poll_peek(cx, &mut buf)
}).await? {
if num_bytes >= n {
return classify(&buf);
}
}
But I think that would be busy waiting, so it seems like a bad idea, right? I could of course add a sleep to the loop, but that also does not seem like good style to me.
So what's the right way to do that?
Here is my attempt:
When I run
echo "123HelloWorld!" | nc -N l localhost 12345on another console, I get: