Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define uint8_t variable in Protocol Buffers message file

I want to define a Point message in Protocol Buffers which represents an RGB Colored Point in 3-dimensional space.

message Point {
    float x   = 1;
    float y   = 2;
    float z   = 3;
    uint8_t r = 4;
    uint8_t g = 5;
    uint8_t b = 6;
}

Here, x, y, z variables defines the position of Point and r, g, b defines the color in RGB space.

Since uint8_t is not defined in Protocol Buffers, I am looking for a workaround to define it. At present, I am using uint32 in place of uint8_t.

like image 342
Ravi Joshi Avatar asked Nov 21 '17 10:11

Ravi Joshi


People also ask

What is a protocol buffer message?

Protocol buffers are a combination of the definition language (created in . proto files), the code that the proto compiler generates to interface with data, language-specific runtime libraries, and the serialization format for data that is written to a file (or sent across a network connection).

How do I set default value in Protobuf?

For bool s, the default value is false. For numeric types, the default value is zero. For enums , the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

How does Protobuf define enum?

enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java. Now our message class contains an Enum for payment. Each of them also has a position which is what Protobuf uses while serialization and deserialization.


1 Answers

There isn't anything in protobuf that represents a single byte - it simply isn't a thing that the wire-format worries about. The options are:

  • varint (up to 64 bits input, up to 10 bytes on the wire depending on the highest set bit)
  • fixed 32 bit
  • fixed 64 bit
  • length-prefixed (strings, sub-objects, packed arrays)
  • (group tokens; a rare implementation detail)

A single byte isn't a good fit for any of those. Frankly, I'd use a single fixed32 for all 3, and combine/decompose the 3 bytes manually (via shifting etc). The advantage here is that it would only have one field header for the 3 bytes, and wouldn't be artificially stretched via having high bits (I'm not sure that a composed RGB value is a good candidate for varint). You'd also have a spare byte if you want to add something else at a later date (alpha, maybe).

So:

message Point {
    float x     = 1;
    float y     = 2;
    float z     = 3;
    fixed32 rgb = 4;
}
like image 117
Marc Gravell Avatar answered Dec 01 '22 20:12

Marc Gravell