Google Protobuf Primer (2) Language Guide
- 作者:柳大·Poechant(钟超)
- 邮箱:zhongchao.ustc#gmail.com(# -> @)
- 博客:Blog.youkuaiyun.com/Poechant
- 微博:weibo.com/lauginhom
- 日期:June 9th, 2012
去年年初初次接触 Google Protobuf,如今已经有不少变化,从这篇开始,续一下 :)
1. Specifying Field Rules
You specify that message fields are one of the following:
required: a well-formed message must have exactly one of this field.optional: a well-formed message can have zero or one of this field (but not more than one).repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
For historical reasons, repeated fields of basic numeric types aren't encoded as efficiently as they could be. New code should use the special option [packed=true] to get a more efficient encoding. For example:
repeated int32 samples = 4 [packed=true];
But when you use it as the following:
message Locations {
repeated Location location = 1 [packed=true];
}
compile it, then you will got a warning:
[packed = true] can only be specified for repeated primitive fields.
So pay attention to the type of fields you intend to specify.
2. Scalar Value Types
| proto Type | Notes | C++ Type | Java Type |
|---|---|---|---|
| double | double | double | |
| float | float | float | |
| int32 | variable-len, inefficient for negative num | int32 | int |
| int64 | variable-len, inefficient for negative num | int64 | long |
| uint32 | variable-len | uint32 | int |
| uint64 | variable-len | uint64 | long |
| sint32 | variable-len, signed num | int32 | int |
| sint64 | variable-len, signed num | int64 | long |
| fixed32 | always 4-byte, efficient > 228 | int32 | int |
| fixed64 | always 8-byte, efficient > 256 | int64 | long |
| sfixed32 | always 4-byte | int32 | int |
| sfixed64 | always 8-btye | int64 | long |
| bool | bool | boolean | |
| string | UTF-8 string, 7-bit ASCII string | string | String |
| bytes | any arbitrary sequence of bytes | string | ByteString |
概括下:
- 可正可负,范围小(228或256以内):
sint32或sint64 - 可正可负,范围大(228或256以上):
sfixed32或sfixed64 - 只会正的,范围小(228或256以内):
uint32或uint64 - 只会正的,范围大(228或256以上):
fixed32或fixed64 - 布尔:
bool - 浮点:
float或double - utf8 string 或 7-bit ascii string:
string - ByteString:
bytes
-
转载请注明来自柳大的优快云博客:Blog.youkuaiyun.com/Poechant,微博:weibo.com/lauginhom
-
本文深入探讨了Google Protobuf的规则指定方法,包括消息字段的必填、可选和重复属性,并详细解释了标量值类型的使用与编码效率。涵盖了不同数值类型的应用场景,以及如何通过特殊选项优化编码。
256

被折叠的 条评论
为什么被折叠?



