Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

c++ - Protobuf: What if value given to enum does not exist in the set of enums?

Problem Description

I added the following enum structure to my protobuf:

  enum FooType {
    INVALID = 0;
    OW      = 1;
    RT      = 2;
    OJ      = 3;
    MC      = 4;
  }
[...]
optional FooType foo_type = 22 [default = INVALID];

What happens if we insert a value greater than 4? The idea is that, every value greater than 4 should be INVALID. I am doing that check in the code on my side.

if(Foo > 4) {
  Foo = 0;
}
//add to protobuf

This solution looks dirty. Is there a way to set that condition somewhere in the protobuf.


Protobuf Generated Code

In the generated code we have the following condition.

case 22: {
        if (tag == 176) {
         parse_itinerary_type:
          int value;
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
                 input, &value)));
          if (::sss::model::protoBom::common::Context_FooType_IsValid(value)) {
            set_itinerary_type(static_cast< ::sss::model::protoBom::common::Context_FooType >(value));
          } else {
            mutable_unknown_fields()->AddVarint(22, value);
          }
        } else {
          goto handle_unusual;
        }
        if (input->ExpectAtEnd()) goto success;
        break;
      }

I didn't understand mutable_unknown_fields()->AddVarint(22, value); The value that being assigned is not the default value. It's just the value that we sent as argument.

where:

bool Context_Footype_IsValid(int value) {
  switch(value) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
      return true;
    default:
      return false;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...