Search code examples
sizeprotocol-bufferslimitproto3

Can I set a maximum value for a number in protobuf?


In protobuf, we only have the choice of using signed or unsigned 32- or 64-bit integer to limit the range of a value.

However, the datastructure I want to define contains a mixture of 8-bit, 16-bit and 32-bit integers to save space on embedded devices. On them, the datastructure is also implemented somewhat differently and requires reserved special values for some fields, so the maximum number for them is not a power of 2.

On these embedded devices, the protobuf definition is only used for transmission to and from them, not for actual storage. So I could just limit the numbers when reading them in.

However, I'd rather define these maximum values in the .proto or .options file to make sure all client applications are aware of these limitations.

Is there a way to do this?

I know there are field options, but the ones listed here does not include an option for this. It is possible to create custom options, but that seems to require writing a compiler extension, which means I have to manually implement this limit checking for every language I want to compile to, and that costs more time than it will ever save.


Solution

  • This is not possible in protobuf by default, and the specification includes no syntax to enforce limits like this.

    However, some third party implementations do include such support.

    For example, my own nanopb has the int_size option:

    int_size: Override the integer type of a field. (To use e.g. uint8_t to save RAM.)

    This will return an error at runtime from pb_decode() if the value does not fit in the field.