开发者

protocol buffer uint32 field with data always in [0,255]

开发者 https://www.devze.com 2023-02-03 01:23 出处:网络
In a Google protocol buffer, I\'m going to use a field to store values that will be integers in [0,255]. From http://code.google.com/apis/protocol开发者_运维技巧buffers/docs/proto.html#scalar, it look

In a Google protocol buffer, I'm going to use a field to store values that will be integers in [0,255]. From http://code.google.com/apis/protocol开发者_运维技巧buffers/docs/proto.html#scalar, it looks like the uint32 will be the appropriate value type to use. Despite the field being able to hold up to 32-bit integers, those extra bits will not be wasted in my case due to the variable length encoding. (Correct me if I'm wrong up to here.)

My question is: how should I indicate that the reader of a serialized message can assume that the largest value in that field will be 255? Just a comment in the protocol buffer specification? Is there any other way?


In .proto there is no such specification; you must simply document it (and presumably cast it appropriately at the consuming code).

Aside: if you happen to be using the C# protobuf-net implementation, then you can do this by working outside a .proto definition (protobuf-net allows code-first):

[ProtoMember(3)] // <=== field number
public byte SomeValue {get;set;}

This is then obviously constrained to 0-255, but is encoded on the wire as you expect (like a uint32). It also does a checked conversion when deserializing, to sanity-check the values.

In .proto, the above is closest to:

optional uint32 someValue = 3;
0

精彩评论

暂无评论...
验证码 换一张
取 消