Thursday, January 10, 2013

Vala support for Protocol Buffers

Recently I was playing around with Protocol Buffers, a data interchange format from Google. In the past I have spent quite a bit of time working with ASN.1 which is a similar format that has been around for many years. Protocol buffers seem to me to be a nice distillation of the useful parts of efficient data interchange and a welcome relief to the enormous size of the ASN.1 specifications.

With Vala being my favourite super-productive language I felt the need to add support to it. Solution: protobuf-vala.

Let's see it in action. Say you have the following protocol in rating.proto:

message Rating {
  required string thing = 1;
  required uint32 n_stars = 2 [default = 3];
  optional string comment = 3;
}


Run it through the protocol buffer compiler with:

$ protoc rating.proto --vala_out=.

This will create a Vala file rating.pb.vala with a class like this:

public class Rating
{

  string thing;
  uint32 n_stars;
  string comment;
  etc
}


You can use this class to encode a rating, e.g. for storing to a file or sending over a network protocol:

var rating = new Rating ();
rating.thing = "Vala";
rating.comment = "Vala is super awesome!";
rating.n_stars = 5;
var buffer = new Protobuf.EncodeBuffer ();
rating.encode (buffer);
do_something_with_data (buffer.data);

And decode it:

var data = get_data_from_somewhere ();
var buffer = new Protobuf.DecodeBuffer (data);
var rating = new Rating ();
rating.decode (buffer);
stderr.printf ("%s is %d stars\n", rating.thing, rating.n_stars);

That's pretty much it!

If you're using Ubuntu (12.04 LTS, 12.10 or 13.04) then you can install Vala protocol buffer support with:

$ sudo apt-add-repository ppa:protobuf-vala-team/ppa
$ sudo apt-get update
$ sudo apt-get install protobuf-compiler-vala libprotobuf-vala-dev

Have fun!

4 comments:

David Yu said...

Good job! Performance wise, is a vala a good choice compared to golang?

David Yu said...

Good job! Performance wise, is vala a good choice compared to golang?

Robert Ancell said...

@David, I don't know how the performance compares. I suspect they're not too different as they both are compiled. Vala has the advantage of the more familiar syntax, is older and integrates better with GNOME technologies. I hope golang becomes successful as it will be a good next generation language.

Luca Bruno said...

A futuristic comment.
In a world where valac would have wip/transform branch merged, this work would be a protobuf-transformer.so plugin that does a similar job of the dbus codegen, so that you have direct support inside the compiler with [Protobuf] attributes instead of generating .vala files.