protoc-gen-validate icon indicating copy to clipboard operation
protoc-gen-validate copied to clipboard

[C++] Required numerics rule

Open xamix opened this issue 1 year ago • 1 comments

Hi,

I use proto3 and latest protoc 22.3 and latest pgv 1.0.0 I have a need to check the presence of numerics fields like bool or others.

It is possible to get protoc generating the has_field accessor on thoses numerics types by using the keyword optional, for example in the following definition, the scheduled field have the optional keyword:

message Event {
        optional bool   scheduled = 1; 
}

And the corresponding function event.has_scheduled() do exist.

What I want is a rule something like [(validate.rules).bool.required = true]

I know that I can use the WKT (Well Known Type) google.protobuf.BoolValue in place of bool however it's a pain to use it in C++ since it will force to create an object and set it's value instead of just setting the boolean value directly:

With google.protobuf.BoolValue scheduled = 1;:

event.mutable_scheduled()->set_value(true);

With optional bool scheduled = 1; :

event.set_scheduled(true);

Moreover the serialized size of object using WKT here (google.protobuf.BoolValue ) is bigger than the solution with optional bool when you serialize non default value, for example on boolean true value take 4 byte to encode with google.protobuf.BoolValue whereas it takes always 2 byte to encode false or true with the optional bool

So if it's possible to add required rules on the optional field it will be a gain in coding and also in serialized size.

EDIT: To help here is a link to the explanation of the usage of optional

While reading this I came to a dirty solution to keep serialized size to minimum and accessing field easily, by wrapping each numerics type in a single oneof, and applying validate.required rule on it for example:

oneof scheduled_value {
    option (validate.required) = true;
    bool scheduled = 1;
}

As a side note, if the name of the oneof start or end with underscore, the validator generate code which do not compile.

Now my proto file is very ugly to my point of view, so implementing optional and handling rule required in PGV should be a better option

xamix avatar Apr 25 '23 11:04 xamix

+1

C0mbatwombat avatar May 11 '23 13:05 C0mbatwombat

Hello, thanks for your interest! As explained in the README, this project is in maintenance mode. We recommend upgrading to protovalidate.

I'm going to go ahead and close this issue, but feel free to open one against protovalidate if needed. Thanks!

chrispine avatar Feb 29 '24 19:02 chrispine