Showing posts with label protobuf. Show all posts
Showing posts with label protobuf. Show all posts

Friday, January 13, 2012

Defaulting message fields in protobuf

Not well documented is the technique for defaulting message fields in protobuf. Say you have a field of message type, named "start" here:

message Complex {
    required int64 real = 1;
    optional int64 imaginary = 2 [default = 0];
}

message Vector {
    required Complex start = 1;
    required int64 length = 2;
}

How to you provide a default value, say at the origin? Like this:

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
    // Pick the field number that is right for you!
    optional Complex complex = 50000;
}

message Vector {
    optional Complex start = 1
    [(complex) = { real: 0 imaginary: 0 }];
    required int64 length = 2;
}

See the Custom Options section for details.

Monday, August 15, 2011

Working with Google Protobuf DynamicMessage

Google Protobuf is an stand out project with mixed quality documentation. A corporate cynic points working with DynamicMessage, an interesting Protobuf feature lacking official documentation beyond skeletal javadoc and a short blurb.

The key trick condenses down to:

public static Descriptor descriptorFor(
        final InputStream in, final String name)
        throws IOException, DescriptorValidationException {
    final FileDescriptorSet fileDescriptorSet
            = FileDescriptorSet.parseFrom(in);
    final FileDescriptorProto fileDescriptorProto
            = fileDescriptorSet.getFile(0);
    final FileDescriptor fileDescriptor = FileDescriptor.
            buildFrom(fileDescriptorProto, new FileDescriptor[0]);
    return fileDescriptor.findMessageTypeByName(name);
}

// Elsewhere

final InputStream in = Class.class.
        getResourceAsStream("... your descriptors from protoc ...");
final Descriptor descriptor = descriptorFor(in,
        Outer.getDescriptor().getName());
final DynamicMessage dynamicMessage = DynamicMessage.
        parseFrom(descriptor, outer.toByteArray());
System.out.println("dynamicMessage = " + dynamicMessage);

Note the baked-in assumption of "getFile(0)", etc. The cynic's example is more forthcoming. Caveat coder.