Alternate names for enumeration values

1,532 views
Skip to first unread message

MahlerFive

unread,
Feb 3, 2011, 9:42:15 PM2/3/11
to Protocol Buffers
Is there a way to assign alternate names to enumeration values? I have
a piece of C++ code that processes protocol buffer messages which have
a lot of enums in them, and I need to print out the contents in a user-
friendly, readable way.

I know that I can get the enum value name by doing something like:
pb::constants::EnumName_descriptor()->FindValueByNumber()->name()

But if my enum value name is "DEVICE_CATEGORY_TABLET", I would rather
output something like "Tablet". I can make a bunch of big maps of enum
values to strings in my C++ code, but this means that any time I
change the protocol buffers I need to update the C++ code. If there is
no "alternate name" available, is there perhaps a better way to
approach this where I don't have to make updates in two places for
every change?

Thanks!

Ben Wright

unread,
Feb 4, 2011, 9:38:18 AM2/4/11
to Protocol Buffers
I have just the solution for you...

I'll start by warning you that I use PB mainly in Java, so things may
look slightly different in C++ - but this method should still work.

You're going to want to define an extension to
"google.protobuf.EnumValueOptions"

in your ".proto" file you will need to add an import for
descriptor.proto

import "descriptor.proto";

then you will need to extent EnumValueOptions

extend google.protobuf.EnumValueOptions {
optional string friendly_name = 5000;
}

you will now have defined an EnumValueOption for your friendly
name... you can use it by adding...

enum my_enum {
FOO = 1 [(<my.package.name.>name)="Foo"];;
BAR = 2 [(<my.package.name.>name)="Bar"];;
}

Note that if you have a package defined - you will need to use it when
referencing your extension.. If not, just use [(friendly_name)="XXXX"]

The () are important as this tells PB that you are referencing an
Extension.

In Java you can access these by calling (probably similar in C++)

enumValueDescriptor.getOptions().getExtension(MyProtobufOuterClass.friendly_name);

You will now have successfully defined a fixed string for each enum
value you want one for - you can do the same to associate the ordinals
of an existing enumeration with one you're using in protobuf by
defining an "ordinal" extension of type uint32.

-Benjamin Wright
Reply all
Reply to author
Forward
0 new messages