Streaming protobuf

66 views
Skip to first unread message

Joan Balagueró

unread,
May 9, 2023, 5:46:52 AM5/9/23
to Protocol Buffers
Hello,

I'm receiving protobuf messages from a client (I can't modify them in any way) with a list of hotels. There are hotels in the 90% of the times, but I need to differentitate when I receive hotels and when not.

The proto file for "no hotels" is something like below (simplified):
1: {
1: {}
2: {}
}

Is there any way to check the "2:" element is empty without loading the whole proto into memory?

Thanks,

Joan.

Florian Enner

unread,
May 9, 2023, 6:08:44 AM5/9/23
to Protocol Buffers
You could manually iterate through the data and only check for that field, e.g., in Java (untested):

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.WireFormat;

private static boolean containsHotels(byte[] data) throws IOException {
return containsField(CodedInputStream.newInstance(data), Message.HOTELS_FIELD_NUMBER);
}

private static boolean containsField(CodedInputStream input, int fieldNumber) throws IOException {
while (!input.isAtEnd()) {
int tag = input.readTag();
if (WireFormat.getTagFieldNumber(tag) == fieldNumber) {
return true;
}
input.skipField(tag);
}
return false;
}

Joan Balagueró

unread,
May 9, 2023, 8:13:45 AM5/9/23
to Protocol Buffers
Hi Florian,

Thanks a lot for your quick response. It works like a charm.

Thanks,

Joan.
Reply all
Reply to author
Forward
0 new messages