协议缓冲区:精确长度的字符串或字节序列

protocol-buffers: string or byte sequence of the exact length

查看 https://developers.google.com/protocol-buffers/docs/proto3#scalar 似乎 stringbytes 类型不限制长度?这是否意味着我们需要在单独的字段中指定传输字符串的长度,例如:

message Person {
  string name = 1;
  int32 name_len = 2;
  int32 user_id = 3;
  ...
}

wire type used for string/byte is Length-delimited. This means that the message includes the strings length. How this is made available to you will depend upon the language you are using - for example the table 表示在 C++ 中使用 string 类型,因此您可以调用 name.length() 来检索长度。

因此无需在单独的字段中指定长度。

我希望 GPB 做的一件事是允许使用模式来设置对 list/array 长度或数值范围等事物的约束。最好能在.proto文件中有注释,希望程序员注意!

其他序列化技术可以做到这一点,例如 XSD(尽管工具通常很差)、ASN.1 和 JSON 模式。这非常有用。如果 GPB 添加这些(它不会改变线路格式),GPB 将非常“完整”。