Skip to content

Add a replace_key_for_value API for HashMaps #632

Description

@cactusdualcore

I recently ran into this. It is is actually quite simple to achieve this as a pure library user.

use hashbrown::hash_map::Entry;
use core::hash::{Hash, BuildHasher};

fn replace_key_for_value<K, V, S>(
    this: &mut HashMap<K, V, S>,
    old_key: &K,
    new_key: K,
) -> Option<V>
where
    K: Eq + Hash,
    S: BuildHasher,
{
    if old_key != &new_key
        && let Some(value) = this.remove(old_key)
    {
        match this.entry(new_key) {
            Entry::Vacant(vacant) => {
                vacant.insert(value);
            }
            Entry::Occupied(mut occupied) => {
                return Some({
                    let mut old_value = value;
                    core::mem::swap(occupied.get_mut(), &mut old_value);
                    old_value
                });
            }
        }
    }

    None
}

However, I think this is the kind of function which is useful for anybody who runs into this situation and which is much more convenient and efficient as a part of the library. As this is a pretty niche function, I understand if this is not added to the library.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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