Search code examples
typesprotocol-buffersada

Is it possible to define a numeric range for a field in Protocol Buffer?


I live in a very safety/critical Ada-ic environment, and have taken the habit of having well defined and bounded type definition. I am also confronted to lots ASN1 usage/evangelists.

One of the key features that some people around me define as superior in ASN1 over protocol buffers is the ability to define, and therefore check, data range.

So,

  • Is it true that protocol buffers do not have any range definition system ?
  • Are there any means on top of protocol buffer that could provide such a feature ?

Usual numerical types definition such as int32, int64 is out of scope here.


Solutions I've tried / Solution finding process:
I read this Google overview and found no reference to any data range definition. Except for features concerning the enum management/representation, and some ordering features.

To give some other references, I heard of/read the links below and became aware of an Ada implementation project.


Solution

  • It's true that protocol buffers do not have any built-in mechanism for numeric range.

    The syntax however does support defining custom options:

    extend google.protobuf.FieldOptions {
         optional int32 maxval = 50001;
         optional int32 minval = 50002;
    }
    
    message MyMessage {
         required int32 month = 1 [(minval) = 1, (maxval) = 12];
    }
    

    Depending on library used, these can then either be accessed in runtime using reflection, or you can use a custom code generator to automatically generate verification code.