Storing multiple messages in one protocol buffer binary file

后端 未结 4 1674
花落未央
花落未央 2020-12-05 12:27

I have repeating messages which I want to store in a single file. Currently I have to wrap this repeating message in another message. Is there a way around this?

<         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 13:03

    Protobuf doesn't support this functionality. It can be used to just serialize one message, but this serialized message doesn't contain information about its type (Box or Boxes) and length. So if you want to store multiple message you have to include type and length of message as well. Writing algorithm (in pseudo language) could look like this:

    for every message {
        write(type_of_message) // 1 byte long
        write(length_of_serialized_message) // 4 bytes long
        write(serialized_message)
    }
    

    Load algorithm:

    while(end_of_file) {
    
        type = read(1) // 1 byte
        length = read(4) // 4 bytes
        buffer = read(length)
        switch (type) {
          case 1:
             deserialise_message_1(buffer)
          case 2:
             deserialise_message_2(buffer)
        }
    }
    

提交回复
热议问题