Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protobuf: how nested (custom) optional fields are to be handled in C++?

Reading into Protocol Buffer Basics: C++, found nothing that matches the situation:; with following .proto processed with --cpp_out,

message A {
 required int32 foo = 1;
}
message B {
 optional A data = 1;
}

no obviously looking accessor/setter is generated to set custom optional field (including 'nested types' section which I'm too lazy to put here):

   // accessors -------------------------------------------------------

   // optional .A = 1;
   inline bool has_a() const;
   inline void clear_a();
   static const int kAFieldNumber = 1;
   inline const ::A& a() const;
   inline ::A* mutable_a();
   inline ::A* release_a();

So, how to set B::A to some A instance in C++?


TEST FILES: .proto, generated results: .h, .cc and some .java


Upd: in Java, nested fields are set via Builder: see link above for example (look for setData).

like image 510
kagali-san Avatar asked Jun 04 '12 03:06

kagali-san


People also ask

What is optional protobuf?

In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.

Is repeated optional protobuf?

A repeated field is inherently optional : you just don't add any values. As for com. google. protobuf.

Are repeated fields ordered in protobuf?

Yes, repeated fields retain the order of items. From Google's Protocol Buffers encoding specification: The order of the elements with respect to each other is preserved when parsing, though the ordering with respect to other fields is lost.

What is the difference between proto2 and proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.


1 Answers

Solution: use mutable to modify some returned doodad.

A a;
A.set_foo(1);

B b;
B.mutable_A()->CopyFrom(a);
like image 153
kagali-san Avatar answered Nov 15 '22 19:11

kagali-san