Mark
Mark

Reputation: 6474

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

Looking at https://developers.google.com/protocol-buffers/docs/proto3#scalar it appears that string and bytes types don't limit the length? Does it mean that we're expected to specify the length of transmitted string in a separate field, e.g. :

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

Upvotes: 2

Views: 1792

Answers (2)

bazza
bazza

Reputation: 8414

One of the things that I wished GPB did was allow the schema to be used to set constraints on such things as list/array length, or numerical value ranges. The best you can do is to have a comment in the .proto file and hope that programmers pay attention to it!

Other serialisation technologies do do this, like XSD (though often the tools are poor), ASN.1 and JSON schema. It's very useful. If GPB added these (it doesn't change wire formats), GPB would be pretty well "complete".

Upvotes: 1

Brits
Brits

Reputation: 18290

The 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 says that in C++ a string type is used so you can call name.length() to retrieve the length.

So there is no need to specify the length in a separate field.

Upvotes: 4

Related Questions