Skip to content

Impl Hash for IndexMap. #357

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
xuxiaocheng0201 opened this issue Oct 28, 2024 · 1 comment
Closed

Impl Hash for IndexMap. #357

xuxiaocheng0201 opened this issue Oct 28, 2024 · 1 comment

Comments

@xuxiaocheng0201
Copy link

Sometimes, IndexMap is passed as a parameter. But many cache implementations are essentially a large hashmap. So if I want to cache the return value of a function which contains a parameter of type IndexMap, IndexMap must implements Hash. But currently is not.

I wrote a simple wrapper and it works fine:

use std::hash::{Hash, Hasher};

use derive_more::{Deref, DerefMut};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Deref, DerefMut)]
pub struct HashIndexMap<K: Hash + Eq, V>(pub IndexMap<K, V>);

impl<K: Hash + Eq, V: Hash> Hash for HashIndexMap<K, V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        state.write_usize(self.0.len());
        for (k, v) in &self.0 {
            k.hash(state);
            v.hash(state);
        }
    }
}
@cuviper
Copy link
Member

cuviper commented Oct 28, 2024

The problem is inconsistency between Eq and Hash -- see #288. However, we have since published the ordermap crate, which is a thin wrapper around indexmap that does use map order for both Eq and Hash, and Ord as well.

Your own wrapper can work too, but you should re-implement PartialEq using iterator order, rather than deriving it.

@cuviper cuviper closed this as not planned Won't fix, can't repro, duplicate, stale Oct 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants