Is the change from Enum to int32 compatible?

964 views
Skip to first unread message

vole zheng

unread,
Jan 6, 2021, 10:55:19 AM1/6/21
to Protocol Buffers
Hi,

I have a similar problem with this one. Now I'd like to change an Enum to an int32, but I'm wondering if it's a safe and compatible change?

From this section, it seems to only mention 'int32, uint32, int64, uint64, and bool are all compatible'. But from this section, it seems 'int32, int64, uint32, uint64, sint32, sint64, bool, enum' are using the same wire format. So is enum and int32 compatible?

Adam Cozzette

unread,
Jan 6, 2021, 12:17:13 PM1/6/21
to vole zheng, Protocol Buffers
The answer to this is a little bit complicated and depends on whether you're using proto2 or proto3. Enums and int32 do share the same wire format, but you have to be careful with unknown enum values. In proto2, if you parse an unknown enum value then it will end up in the unknown field set and the enum field will appear to be absent. So if you migrate your field from an enum to int32 then you have to be aware that binaries using the old schema will have this parsing behavior if they try to parse an int that wasn't in the original enum definition. Actually to be fair, the same problem can occur any time you add new values to a proto2 enum.

We fixed this problem in proto3 by making proto3 enums "open", meaning they can store arbitrary integer values normally instead of treating them like unknown fields. So in proto3, moving from an enum to int32 is safer.

Overall I think this is probably a safe change even in proto2 if you do it carefully, especially if you can make sure all binaries get updated before you start using int values that weren't included in the original enum.

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/a4c61eaa-ca14-4ef3-8cb3-b0a54ed27c77n%40googlegroups.com.

Hao Zheng

unread,
Jan 11, 2021, 8:24:48 AM1/11/21
to Adam Cozzette, Protocol Buffers
Thanks for the answer, Adam!
Reply all
Reply to author
Forward
0 new messages