为什么 CodedInputStream 将流位置设置为结束?

Why does CodedInputStream set stream position to end?

我在 C# 中使用协议缓冲区 3。我试图在流中反弹以找到每条消息的开始位置,而不实际反序列化消息。所有消息都使用 WriteDelimitedTo 写入流。

然后我使用这段代码尝试从长度标记跳转:

_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);
}

然而,在我做 codedStream.ReadInt32() 的那一刻,流位置被设置到末尾,而不仅仅是 varint32 之后的下一个字节。

此行为是由于 CodedInputStream 将原始流缓冲为 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,并直接通过原始流移动。