How to get length number using PrefixStyle with ProtoBuf-net?

in the following example, how to get the length number using PrefixStyle with ProtoBuf-net?

and what's the difference between PrefixStyle.Base128 and PrefixStyle.Fixed32?

Thanks!

PerfTest clone; using (MemoryStream ms = new MemoryStream()) { Serializer.SerializeWithLengthPrefix(ms, obj,PrefixStyle.Base128); byte[] raw = ms.ToArray(); ms.Position = 0; clone = Serializer.DeserializeWithLengthPrefix<PerfTest>(ms,PrefixStyle.Base128); } 

Change Using the code below, the byte array has a length of 22. Why does TryReadLengthPrefix return 21? Of course, should return 22?

  PerfTest clone; using (MemoryStream ms = new MemoryStream()) { Serializer.SerializeWithLengthPrefix(ms, obj,PrefixStyle.Base128); byte[] raw = ms.ToArray(); ms.Position = 0; int bArrayLen = ms.ToArray().Length; //returns 22 int len;// set to 21. Why not 22? Serializer.TryReadLengthPrefix(ms, PrefixStyle.Base128,out len); clone = Serializer.DeserializeWithLengthPrefix<PerfTest>(ms,PrefixStyle.Fixed32); } 
+4
source share
1 answer

Fixed32 always uses 4 bytes for the length prefix - this seems to be not uncommon for people who package messages manually (indeed, I even had to add versions with different ends at some point due to repeated requests).

The preference should be Base128, which uses the "varint" encoding, so small numbers take up less space for encoding. In addition, this prefix style can be used to make a sequence of objects wired compatible with a single object with a repeated field, which has several useful applications.

Return the length; if you use DeserializeWithLenghPrefix or DeserializeItems , you do not need to - it processes it internally. But if you need it, check out Serializer.TryReadLengthPrefix .

To clarify: the purpose of *WithLengthPrefix methods is to allow the separation of different objects / messages in one thread - most often: network sockets. This is necessary because the protocol itself otherwise assumes that the entire stream is the only message, so keep reading until the stream / socket is closed.

Re 22 vs 21 bytes; this is because the length prefix itself takes some length :) in fact, if the array is 22, I am a little surprised that the payload is not 20 - the byte header field (to make the composite stream itself a valid protobuff stream), 1 byte long and payload of 20 bytes. I'm on my mobile phone now, so I can’t run the sample for research; however, you can omit the field header (optional), so it can be a length of 1 byte, a payload of 21 bytes. I'll watch it later.

+4
source

Source: https://habr.com/ru/post/1339460/


All Articles