Exercise: Protobuf Parsing

In this exercise, you will build a parser for the protobuf binary encoding. Don’t worry, it’s simpler than it seems! This illustrates a common parsing pattern, passing slices of data. The underlying data itself is never copied.

Fully parsing a protobuf message requires knowing the types of the fields, indexed by their field numbers. That is typically provided in a proto file. In this exercise, we’ll encode that information into match statements in functions that get called for each field.

We’ll use the following proto:

  1. message PhoneNumber {
  2. optional string number = 1;
  3. optional string type = 2;
  4. }
  5. message Person {
  6. optional string name = 1;
  7. optional int32 id = 2;
  8. repeated PhoneNumber phones = 3;
  9. }

A proto message is encoded as a series of fields, one after the next. Each is implemented as a “tag” followed by the value. The tag contains a field number (e.g., 2 for the id field of a Person message) and a wire type defining how the payload should be determined from the byte stream.

Integers, including the tag, are represented with a variable-length encoding called VARINT. Luckily, parse_varint is defined for you below. The given code also defines callbacks to handle Person and PhoneNumber fields, and to parse a message into a series of calls to those callbacks.

What remains for you is to implement the parse_field function and the ProtoMessage trait for Person and PhoneNumber.

  1. /// A wire type as seen on the wire.
  2. enum WireType {
  3.     /// The Varint WireType indicates the value is a single VARINT.
  4.     Varint,
  5.     /// The I64 WireType indicates that the value is precisely 8 bytes in
  6.     /// little-endian order containing a 64-bit signed integer or double type.
  7.     //I64,  -- not needed for this exercise
  8.     /// The Len WireType indicates that the value is a length represented as a
  9.     /// VARINT followed by exactly that number of bytes.
  10.     Len,
  11.     // The I32 WireType indicates that the value is precisely 4 bytes in
  12.     // little-endian order containing a 32-bit signed integer or float type.
  13.     //I32,  -- not needed for this exercise
  14. }
  15. #[derive(Debug)]
  16. /// A field's value, typed based on the wire type.
  17. enum FieldValue<'a> {
  18.     Varint(u64),
  19.     //I64(i64),  -- not needed for this exercise
  20.     Len(&'a [u8]),
  21.     //I32(i32),  -- not needed for this exercise
  22. }
  23. #[derive(Debug)]
  24. /// A field, containing the field number and its value.
  25. struct Field<'a> {
  26.     field_num: u64,
  27.     value: FieldValue<'a>,
  28. }
  29. trait ProtoMessage<'a>: Default {
  30.     fn add_field(&mut self, field: Field<'a>);
  31. }
  32. impl From<u64> for WireType {
  33.     fn from(value: u64) -> Self {
  34.         match value {
  35.             0 => WireType::Varint,
  36.             //1 => WireType::I64,  -- not needed for this exercise
  37.             2 => WireType::Len,
  38.             //5 => WireType::I32,  -- not needed for this exercise
  39.             _ => panic!("Invalid wire type: {value}"),
  40.         }
  41.     }
  42. }
  43. impl<'a> FieldValue<'a> {
  44.     fn as_str(&self) -> &'a str {
  45.         let FieldValue::Len(data) = self else {
  46.             panic!("Expected string to be a `Len` field");
  47.         };
  48.         std::str::from_utf8(data).expect("Invalid string")
  49.     }
  50.     fn as_bytes(&self) -> &'a [u8] {
  51.         let FieldValue::Len(data) = self else {
  52.             panic!("Expected bytes to be a `Len` field");
  53.         };
  54.         data
  55.     }
  56.     fn as_u64(&self) -> u64 {
  57.         let FieldValue::Varint(value) = self else {
  58.             panic!("Expected `u64` to be a `Varint` field");
  59.         };
  60.         *value
  61.     }
  62. }
  63. /// Parse a VARINT, returning the parsed value and the remaining bytes.
  64. fn parse_varint(data: &[u8]) -> (u64, &[u8]) {
  65.     for i in 0..7 {
  66.         let Some(b) = data.get(i) else {
  67.             panic!("Not enough bytes for varint");
  68.         };
  69.         if b & 0x80 == 0 {
  70.             // This is the last byte of the VARINT, so convert it to
  71.             // a u64 and return it.
  72.             let mut value = 0u64;
  73.             for b in data[..=i].iter().rev() {
  74.                 value = (value << 7) | (b & 0x7f) as u64;
  75.             }
  76.             return (value, &data[i + 1..]);
  77.         }
  78.     }
  79.     // More than 7 bytes is invalid.
  80.     panic!("Too many bytes for varint");
  81. }
  82. /// Convert a tag into a field number and a WireType.
  83. fn unpack_tag(tag: u64) -> (u64, WireType) {
  84.     let field_num = tag >> 3;
  85.     let wire_type = WireType::from(tag & 0x7);
  86.     (field_num, wire_type)
  87. }
  88. /// Parse a field, returning the remaining bytes
  89. fn parse_field(data: &[u8]) -> (Field, &[u8]) {
  90.     let (tag, remainder) = parse_varint(data);
  91.     let (field_num, wire_type) = unpack_tag(tag);
  92.     let (fieldvalue, remainder) = match wire_type {
  93.         _ => todo!("Based on the wire type, build a Field, consuming as many bytes as necessary.")
  94.     };
  95.     todo!("Return the field, and any un-consumed bytes.")
  96. }
  97. /// Parse a message in the given data, calling `T::add_field` for each field in
  98. /// the message.
  99. ///
  100. /// The entire input is consumed.
  101. fn parse_message<'a, T: ProtoMessage<'a>>(mut data: &'a [u8]) -> T {
  102.     let mut result = T::default();
  103.     while !data.is_empty() {
  104.         let parsed = parse_field(data);
  105.         result.add_field(parsed.0);
  106.         data = parsed.1;
  107.     }
  108.     result
  109. }
  110. #[derive(Debug, Default)]
  111. struct PhoneNumber<'a> {
  112.     number: &'a str,
  113.     type_: &'a str,
  114. }
  115. #[derive(Debug, Default)]
  116. struct Person<'a> {
  117.     name: &'a str,
  118.     id: u64,
  119.     phone: Vec<PhoneNumber<'a>>,
  120. }
  121. // TODO: Implement ProtoMessage for Person and PhoneNumber.
  122. fn main() {
  123.     let person: Person = parse_message(&[
  124.         0x0a, 0x07, 0x6d, 0x61, 0x78, 0x77, 0x65, 0x6c, 0x6c, 0x10, 0x2a, 0x1a,
  125.         0x16, 0x0a, 0x0e, 0x2b, 0x31, 0x32, 0x30, 0x32, 0x2d, 0x35, 0x35, 0x35,
  126.         0x2d, 0x31, 0x32, 0x31, 0x32, 0x12, 0x04, 0x68, 0x6f, 0x6d, 0x65, 0x1a,
  127.         0x18, 0x0a, 0x0e, 0x2b, 0x31, 0x38, 0x30, 0x30, 0x2d, 0x38, 0x36, 0x37,
  128.         0x2d, 0x35, 0x33, 0x30, 0x38, 0x12, 0x06, 0x6d, 0x6f, 0x62, 0x69, 0x6c,
  129.         0x65,
  130.     ]);
  131.     println!("{:#?}", person);
  132. }

This slide and its sub-slides should take about 30 minutes.

  • In this exercise there are various cases where protobuf parsing might fail, e.g. if you try to parse an i32 when there are fewer than 4 bytes left in the data buffer. In normal Rust code we’d handle this with the Result enum, but for simplicity in this exercise we panic if any errors are encountered. On day 4 we’ll cover error handling in Rust in more detail.