Ignore next n bytes of TcpStream input

Is there any easy and memory-efficient way to skip the next n bytes received on a BufReader<TcpStream>?

I am implementing a protocol in which messages have an optional payload with a length provided in the message header, and I want to be able to provide a reasonable error response when receiving a message that is too large for the service to handle. When such a message is received, the next message will come after the client has finished sending the entire too-large-to-handle payload, so somehow the protocol needs to ignore all the bytes in the payload (since they're too large to read into memory). BufReader implements Seek when its underlying reader implements seek, but TcpStream does not.

Here's something that appears to work, using io::copy and io::Sink; in this line, r represents the buffered TCP reader:

std::io::copy(&mut r.take(len as u64), &mut std::io::sink());

Edit: take() actually consumes the BufReader by value, so this doesn't actually work.

You could do std::io::copy(&mut r.by_ref().take(len as u64), &mut std::io::sink());


Strange, I thought I had tried that unsuccessfully already, but it does compile. Thank you!

Note the by_ref, this will give you a mutable reference to the reader.

Yes, that's why I tried it before. I must have had some other error elsewhere in my code, though, and the declaration is take(self) -> ..., so I took by_ref back out.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.