Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a repeated element in protocol buffer?

Assume that I have this message.

message A {
  repeated float w = 1 [packed = true];
}

How can I initialize w in my Code? Can I do any better than this?

a = A()    
for (int i = 0 ; i < n; ++i) 
   a.add_w(0);
like image 939
Mohammad Moghimi Avatar asked Oct 18 '15 01:10

Mohammad Moghimi


People also ask

Are repeated fields ordered in Protobuf?

Yes, repeated fields retain the order of items.

What does repeated in Protobuf mean?

repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

What is repeated in gRPC?

gRPC services provide two ways of returning datasets, or lists of objects. The Protocol Buffers message specification uses the repeated keyword for declaring lists or arrays of messages within another message. The gRPC service specification uses the stream keyword to declare a long-running persistent connection.


1 Answers

a.w() or a.mutable_w() will return a google::protobuf::RepeatedField<float> which provides some additional options. For instance, you could call a.mutable_w()->Reserve(n) to pre-allocate space in advance, to avoid the usual strategy of re-allocating every time the size doubles. You can also use Resize(n) followed by mutable_data() to get direct access to the underlying buffer, but this probably won't provide much speed benefit over Reserve(n) followed by your loop.

like image 156
Kenton Varda Avatar answered Sep 20 '22 18:09

Kenton Varda