如何获取将用于 BTreeMap 中的值的散列

How to get the hash which would be used for a value in a BTreeMap

我目前正在使用 BTreeMap 因为我需要稳定的顺序。

是否有一个 Rust Map 结构允许我暂时添加一个新的 key/value 到一个有序的 Map 并查看散列是什么?

目前我必须克隆整个 BTreeMap,添加 key/value,获取哈希并删除克隆。这看起来很浪费。

假设您正在谈论由 Hash::hash method, then you can see that it is implemented like this:

返回的整棵树的哈希值
fn hash<H: Hasher>(&self, state: &mut H) {
    for elt in self {
        elt.hash(state);
    }
}

可以简单地修改以虚拟插入元素:

fn hash_with_extra<H: Hasher>(map: &BTreeMap<i32, i32>, state: &mut H, extra: &(i32, i32)) {
    let mut it = map.iter();
    let mut done = false;
    while let Some (elt) = it.next() {
        if extra.0 == elt.0 {
            extra.hash (state);
            done = true;
            break;
        } else if extra.0 < elt.0 {
            extra.hash (state);
            elt.hash (state);
            done = true;
            break;
        } else {
            elt.hash (state);
        }
    }
    if done {
        while let Some (elt) = it.next() { elt.hash (state); }
    } else {
        extra.hash (state);
    }
}

或使用itertools::merge and std::iter::once:

fn hash_with_extra<H: Hasher>(map: &BTreeMap<i32, i32>, state: &mut H, extra: &(i32, i32)) {
    for elt in merge (map.iter(), once (extra)) {
        elt.hash (state);
    }
}