Sunday, August 23, 2015

Google ProtoBuf - quick Overview

Protocol Buffers are flexible, efficient, automated mechanism for serializing structured data. This is smaller, faster, simpler. A developer define how he want the data to be structured once. then on, he can use special generated source code to easily write and read the structured data to and from a variety of data streams and using variety of languages. 

Now the question is how do they work? 

A developer specifies how he want the information he is serializing to be structured by defining protocol buffer message types in .proto files. Each protocol buffer message is a small logical record information, containing a series of name-value pairs. Below is a sample of a .proto file that defines a message containing information about a person. 

message Person 
{
required string name = 1 ; 
required int32 id = 2;
optional string email = 3; 
enum PhoneType
{
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber 
{
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}

repeated PhoneNumber phone = 4;

Here, Person is called a protocol buffer message. Once the Protocol buffer message is defined, it needs to be run through buffer compiler of the application’s language on the photo file to generate the data access classes. These provide sample accessors for each filed like name as well as methods to serialize, parse the whole structure to/from raw bytes. 

Person person;
person.set_name(“John”);
person.set_id(1234);
person.SerializeToOStream(person);

References:

No comments:

Post a Comment