2

I'm writing a streaming binary encoding parser, pulling bytes from a data source that implements the Read trait. Values in the stream are prefixed with a short header that indicates what type the next value is and how many bytes it takes to represent it.

I've been using Read::bytes to read the header. Then, if I'm interested in the value that the header represents, I can use the Read::read method to copy the required number of bytes from the data source into a buffer. However, if I'm not interested in the value, I'd like to skip over those bytes without having to process them. I can achieve this by doing:

for byte_result in data_source.bytes().take(n) {
    let _byte = byte_result?;
}

However, checking on the result of each individual byte feels very expensive. Is there a way I can achieve this that only requires that I check the result of an overall skip operation?

The Seek trait is promising, but many forms of input do not implement it (TcpStream, for example.)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
zslayton
  • 51,416
  • 9
  • 35
  • 50
  • 1
    `lseek` is not supported on sockets by POSIX. This is likely because there wouldn't be a real benefit compared to just reading and discarding, and is likely why the `Seek` trait is not implemented on `TcpStream`. You are right that reading byte by byte and using `?` seems expensive. However, `read_exact` might be more efficient (but has the downside to require a buffer of the right size). – mcarton Aug 12 '18 at 17:20
  • 2
    I believe your question is answered by the answers of [How to advance through data from the std::io::Read trait when Seek isn't implemented?](https://stackoverflow.com/q/42243355/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Aug 12 '18 at 17:31
  • Yep, that answers it, thank you! – zslayton Aug 12 '18 at 19:04

0 Answers0