14

Consider the following message.

message example { 
   repeated string text; 
}

Let's say that in C++ I have a list of string that I insert into the text field of example:

exemple aMessage; 
std::list<std::string> aList = ... ;
for (std::string anStr : aList) 
{
    aMessage.add_text(anStr);
}

Later on if I access text of the my message, will that field be ordered in the same way as my list? What about when I serialize it and send it off somewhere?

Will the order stay constant?

Alperen AYDIN
  • 547
  • 1
  • 6
  • 17

1 Answers1

17

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.

jpa
  • 10,351
  • 1
  • 28
  • 45
  • 4
    I am afraid I don't understand what the second part of the sentence means. – Alperen AYDIN Mar 10 '19 at 09:27
  • 8
    @AlperenAYDIN If you have `repeated string textA` and `repeated string textB`, the order within `textA` and `textB` arrays is kept. However, you could technically create a message that is `textA[0], textB[0], textA[1], textB[1]` in encoded form, but after decoding and recoding it will look like `textA[0], textA[1], textB[0], textB[1]`. – jpa Mar 10 '19 at 11:36
  • I see. Thank you. – Alperen AYDIN Mar 11 '19 at 13:35
  • 4
    While the question is tagged with C, the ordering is part of the protocol, so it applies for implementation in any language. – Martin Grey Sep 23 '21 at 10:33