Shopify / protoboeuf

Experimenting with a protobuf implementation
MIT License
24 stars 2 forks source link

Encode repeated fields #71

Closed paracycle closed 3 months ago

paracycle commented 3 months ago

Fixes #56

In order to encode repeated fields, we need to iterate over the array of values and encode each one of them. However, until now, we didn't have a way to reuse the encoding logic for a single value. Moreover, packed repeated fields use length encoding, and don't emit the tag for each field over and over again.

For those reasons, I've done the following changes in this commit:

  1. I've extracted the field encoding logic into a separate method, encode_subtype, which takes a field, an optional value and an optional tagged boolean, and passes these on to the individual field encoders. This way, we can reuse the encoding logic for a single value, by supplying the value argument to be something different than the default @#{field.name}. We can also control if the tag will be emitted or not, by passing the tagged argument as true or false.
  2. I've added a new method encode_tag_and_length which is used to encode the tag and, if applicable, the length of a field. This method is used by all the other field encoders, and if the length field is passed an argument, the value of that argument is used as the expression that will return the length of the field.

These two changes allow us to implement the encoding of repeated fields in a very simple way, and they make each encode method simpler as well.