Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an item at the beginning of a protobuf list

I'm trying to insert an item at the beginning of a protobuf list of messages. add_foo appends the item to end. Is there an easy way to insert it at the beginning?

like image 622
Matthew Finlay Avatar asked Oct 19 '25 20:10

Matthew Finlay


1 Answers

There's no built-in way to do this with protocol buffers AFAIK. Certainly the docs don't seem to indicate any such option.

A reasonably efficient way might be to add the new element at the end as normal, then reverse iterate through the elements, swapping the new element in front of the previous one until it's at the front of the list. So e.g. for a protobuf message like:

message Bar {
  repeated bytes foo = 1;
}

you could do:

Bar bar;
bar.add_foo("two");
bar.add_foo("three");

// Push back new element
bar.add_foo("one");
// Get mutable pointer to repeated field
google::protobuf::RepeatedPtrField<std::string> *foo_field(bar.mutable_foo());
// Reverse iterate, swapping new element in front each time
for (int i(bar.foo_size() - 1); i > 0; --i)
  foo_field->SwapElements(i, i - 1);

std::cout << bar.DebugString() << '\n';
like image 168
Fraser Avatar answered Oct 21 '25 11:10

Fraser