Protobuf maps 的排序

huangapple go评论87阅读模式
英文:

Ordering of Protobuf maps

问题

我正在创建 proto3 中的消息对象,并使用自动生成的 Java 类。
我想为每个消息对象分配唯一的键。

message Obj {
    ...
    string unique_key = 1;
    ...
}

在构建 Obj 时,它会从一个微服务接收一个名为 metaData 的 proto 对象,其定义如下:

message metaData {
     map<string, string> keyFields = 1;
}

根据 metaData 对象中的条目,unique_key 是通过迭代映射并对每个条目进行哈希运算来创建的。(keyFields 中最多有 10 个条目)

Protobuf 文档,无法定义键的排序。我应该如何确保具有相同 keyFields 条目的不同 metaData 对象生成相同的 unique_key

英文:

I am creating message objects in proto3 and using auto-generated java classes.
I want to have unique key assigned to each of the message object.

message Obj {
    ...
    string unique_key = 1;
    ...
}

During construction of Obj, it receives from a microservice, a proto object called metaData, which is defined as follows:

message metData {
     map<string, string> keyFields = 1;
}

Based on entries in metaData object, unique_key is created by iterating over the map and hashing each of the entries.(There are upto 10 entries in keyFields)

The protobuf documentation says, the ordering of keys can't be defined. How should I guarantee that different metaData objects with same entries in keyFields generate same unique_key?

答案1

得分: 2

你有两个一般选项:

  1. 实现一个可交换的哈希函数。例如,获取键的哈希值,然后简单地将它们相加,忽略溢出。
  2. 获取键并对它们进行排序。然后对排序后的键进行哈希。如果有“许多”键,考虑缓存哈希值。
英文:

You have two options in general:

  1. Implement a commutative hash function. E.g. get the hashes of the keys and simply sum them ignoring overflow.
  2. Get the keys and sort them. Then hash them sorted. If there are "many" keys, consider caching the hash value.

huangapple
  • 本文由 发表于 2020年7月31日 15:47:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63187818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定