Skip to content

Impl Hash for IndexMap. #357

Closed as not planned
Closed as not planned
@xuxiaocheng0201

Description

@xuxiaocheng0201

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);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions