How to implement map structure using Google Protobuf

Now I am using google protobuf and I want to use the map structure. However, I found that no such data structure is implemented in Google protobuf.

My problem is very simple. I have a structure with "Page number (uint32_t)" and very simple content. I want to use this page number as key and content as value. This should satisfy both the requirements of space and speed. However, there is no such data structure in Protobuf.

The method I am using looks like this:

message MyPageContent {
    required uint32 contentA = 1;
    required uint32 contentB = 2;
}

message MyTable {
    repeated MyPageContent table= 1;
}

      

The total number of pages is known. So at the beginning of my program, I add all pagecontent to the table with some special value (this value is used to notify the page, there is no, no one should use the content.) That way I could implicitly use the page number to index. When the page is ready, I will change the corresponding value in the table. People directly use the page number as an index to access content. This method wastes a lot of space (a lot of pages are not ready, and I just added special value there so people know it is not ready.) But the access times are very fast.

An alternative way to do something like this:

message MyTable {
    repeated uint32 pageNum = 1;
    repeated MyPageContent myContent = 2;
}

      

This way I can add the page to the table when it's ready. Thus, the size of the table should be limited. However, people must first do a linear search to find if a page is in a table. This will take a long time.

Basically this is why I want to use the Map structure in protobuf. This saves space and time.

+3


source to share


2 answers


Without a path, (un) luckily.



Protobuf is not a data manipulation library, it is a serialization library. This way you manipulate your data in std::map

or any other container and serialize it using the fields repeated

in protobuf.

+1


source


I'm not sure when this change happened, but currently (Apr '15) ProtoBuf supports maps :



If you want to create an associative map as part of a data definition, protocol buffers provide a convenient shortcut syntax:

map<key_type, value_type> map_field = N;

... where key_type

can be any integer or string type (thus, any scalar type except for floating point and bytes

). value_type

can be of any type.

So, for example, if you want to create a project map where each message Project

is associated with a key string

, you can define it like this:

map<string, Project> projects = 3;

+9


source







All Articles