Bhanuka Yd
Bhanuka Yd

Reputation: 665

Protobuf parser parses other objects?

I have been using protocol buffers for a project of mine in Java. I have found that a parser for a protobuf object, parses other Protobuf data and does not throw an exception. Instead it returns a object of the parser type without any data (not the default instance)

Below is my test proto file

option java_package = "tester";
option java_outer_classname = "TestProto";

message A{
    string message = 1;
}

message B{
    int64 id = 1;
}

below is my test code

 TestProto.A a = TestProto.A.newBuilder().setMessage("My Test Message").build();
 TestProto.B b = TestProto.B.getDefaultInstance().getParserForType().parseFrom(a.toByteString());

 System.out.println("Is default instnace :" + (b.getDefaultInstanceForType() == b));

this code works without an exception and the result is 'false'.

I cannot understand this behaviour,I am in need of a situation where I have to parse some serialized protobuf objects and If one parser fails I have to try the other parser. How can I solve this.

thanks.

Upvotes: 2

Views: 1102

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064004

Protobuf is predicated on both ends knowing in advance - and agreeing on - the data structure. If you attempt to interpret a message with a radically different structure, precisely zero guarantees are made.

  • it could throw an error
  • it could work and present you with well-intentioned gibberish
  • it could work and preserve everything required as unknown fields

All are possible.

Basically: you can't rely on this behaviour.

Note: there are guarantees made regarding certain changes such as adding or removing fields (ensuring that they aren't reused later with different types/meanings). That is fine and expected. But other changes are simply not defined.


I am in need of a situation where I have to parse some serialized protobuf objects and If one parser fails I have to try the other parser. How can I solve this.

You cannot.

Upvotes: 3

Related Questions