Why does CodedInputStream set stream position to e

2019-03-03 03:51发布

问题:

I'm using protocol buffers 3 in c#. I'm trying to bounce through a stream to find the start locations of each message, without actually Deserialising the messages. All messages are written to the stream with WriteDelimitedTo.

I then use this code to try to jump from length markers:

_map = new List<int>();
_stream.Seek(0, SeekOrigin.Begin);

var codedStream = new CodedInputStream(_stream);

while (_stream.Position < _stream.Length)
{
    var length = codedStream.ReadInt32();

    _map.Add((int) _stream.Position);

    _stream.Seek(length, SeekOrigin.Current);
}

However, the moment I do codedStream.ReadInt32() the stream position is set to the end, rather than just the next byte after the varint32.

回答1:

This behaviour is due to CodedInputStream buffering the original stream as you can see in the source code. It is probably unsuitable for manually reading and seeking through a stream. An alternative is to use parts of Marc Gravell's source code for reading a varint, available here, and move though the raw stream directly.