0

In protobuf, how would you serialize an array of char's, (u)int8_t or (u)int16_t? Should the message look like this:

message ArrayWithNotSupportedTypes
{
int32 type = 1;
string byte_stream = 2;
}

where type could store some unique id of the element type stored in the array. And then the byte_stream is populated with contents of an array, where values are of one of the types above?

Also,I have seen that there is a type called bytes in protobuf, that is translated to an std::string in the corresponding grpc.pb.h files. Is there any advantage of choosing bytes ahead of string?

Wballer3
  • 141
  • 1
  • 9

1 Answers1

1

If the array size is not big, you can waste some space to make the interface simpler.

message ArrayWithNotSupportedTypes
{
  repeated int32 data = 1; // one data entry per one element
}

If the array size is big, you can use your solution to indicate the type

message ArrayWithNotSupportedTypes
{
  enum Type {
    CHAR = 0;
    INT8 = 1;
    INT16 = 2;
  }
  optional Type type = 1;
  optional bytes data = 2; 
}

bytes and string are similar in C++: why protocol buffer bytes is string in c++?

Reference: https://developers.google.com/protocol-buffers/docs/proto3#scalar

Boris Hu
  • 202
  • 1
  • 6