use std::borrow::Borrow; use std::collections::hash_map::{IntoKeys, IntoValues}; use std::collections::{hash_map, HashMap}; use std::fmt::{self, Debug}; use std::hash::{BuildHasher, Hash}; use std::iter::FromIterator; use std::ops::{Deref, DerefMut, Index}; use std::panic::UnwindSafe;
#[cfg(feature = "serde")] use serde::{
de::{Deserialize, Deserializer},
ser::{Serialize, Serializer},
};
usecrate::RandomState;
/// A [`HashMap`](std::collections::HashMap) using [`RandomState`](crate::RandomState) to hash the items. /// (Requires the `std` feature to be enabled.) #[derive(Clone)] pubstruct AHashMap<K, V, S = crate::RandomState>(HashMap<K, V, S>);
impl<K, V> AHashMap<K, V, RandomState> { /// This crates a hashmap using [RandomState::new] which obtains its keys from [RandomSource]. /// See the documentation in [RandomSource] for notes about key strength. pubfn new() -> Self {
AHashMap(HashMap::with_hasher(RandomState::new()))
}
/// This crates a hashmap with the specified capacity using [RandomState::new]. /// See the documentation in [RandomSource] for notes about key strength. pubfn with_capacity(capacity: usize) -> Self {
AHashMap(HashMap::with_capacity_and_hasher(capacity, RandomState::new()))
}
}
impl<K, V, S> AHashMap<K, V, S> where
K: Hash + Eq,
S: BuildHasher,
{ /// Returns a reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let mut map = HashMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.get(&1), Some(&"a")); /// assert_eq!(map.get(&2), None); /// ``` #[inline] pubfn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where
K: Borrow<Q>,
Q: Hash + Eq,
{ self.0.get(k)
}
/// Returns the key-value pair corresponding to the supplied key. /// /// The supplied key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let mut map = HashMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.get_key_value(&1), Some((&1, &"a"))); /// assert_eq!(map.get_key_value(&2), None); /// ``` #[inline] pubfn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)> where
K: Borrow<Q>,
Q: Hash + Eq,
{ self.0.get_key_value(k)
}
/// Returns a mutable reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let mut map = HashMap::new(); /// map.insert(1, "a"); /// if let Some(x) = map.get_mut(&1) { /// *x = "b"; /// } /// assert_eq!(map[&1], "b"); /// ``` #[inline] pubfn get_mut<Q: ?Sized>(&mutself, k: &Q) -> Option<&mut V> where
K: Borrow<Q>,
Q: Hash + Eq,
{ self.0.get_mut(k)
}
/// Inserts a key-value pair into the map. /// /// If the map did not have this key present, [`None`] is returned. /// /// If the map did have this key present, the value is updated, and the old /// value is returned. The key is not updated, though; this matters for /// types that can be `==` without being identical. See the [module-level /// documentation] for more. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let mut map = HashMap::new(); /// assert_eq!(map.insert(37, "a"), None); /// assert_eq!(map.is_empty(), false); /// /// map.insert(37, "b"); /// assert_eq!(map.insert(37, "c"), Some("b")); /// assert_eq!(map[&37], "c"); /// ``` #[inline] pubfn insert(&mutself, k: K, v: V) -> Option<V> { self.0.insert(k, v)
}
/// Creates a consuming iterator visiting all the keys in arbitrary order. /// The map cannot be used after calling this. /// The iterator element type is `K`. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let map = HashMap::from([ /// ("a", 1), /// ("b", 2), /// ("c", 3), /// ]); /// /// let mut vec: Vec<&str> = map.into_keys().collect(); /// // The `IntoKeys` iterator produces keys in arbitrary order, so the /// // keys must be sorted to test them against a sorted array. /// vec.sort_unstable(); /// assert_eq!(vec, ["a", "b", "c"]); /// ``` /// /// # Performance /// /// In the current implementation, iterating over keys takes O(capacity) time /// instead of O(len) because it internally visits empty buckets too. #[inline] pubfn into_keys(self) -> IntoKeys<K, V> { self.0.into_keys()
}
/// Creates a consuming iterator visiting all the values in arbitrary order. /// The map cannot be used after calling this. /// The iterator element type is `V`. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let map = HashMap::from([ /// ("a", 1), /// ("b", 2), /// ("c", 3), /// ]); /// /// let mut vec: Vec<i32> = map.into_values().collect(); /// // The `IntoValues` iterator produces values in arbitrary order, so /// // the values must be sorted to test them against a sorted array. /// vec.sort_unstable(); /// assert_eq!(vec, [1, 2, 3]); /// ``` /// /// # Performance /// /// In the current implementation, iterating over values takes O(capacity) time /// instead of O(len) because it internally visits empty buckets too. #[inline] pubfn into_values(self) -> IntoValues<K, V> { self.0.into_values()
}
/// Removes a key from the map, returning the value at the key if the key /// was previously in the map. /// /// The key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// # Examples /// /// ``` /// use std::collections::HashMap; /// /// let mut map = HashMap::new(); /// map.insert(1, "a"); /// assert_eq!(map.remove(&1), Some("a")); /// assert_eq!(map.remove(&1), None); /// ``` #[inline] pubfn remove<Q: ?Sized>(&mutself, k: &Q) -> Option<V> where
K: Borrow<Q>,
Q: Hash + Eq,
{ self.0.remove(k)
}
}
impl<K, V, S> Eq for AHashMap<K, V, S> where
K: Eq + Hash,
V: Eq,
S: BuildHasher,
{
}
impl<K, Q: ?Sized, V, S> Index<&Q> for AHashMap<K, V, S> where
K: Eq + Hash + Borrow<Q>,
Q: Eq + Hash,
S: BuildHasher,
{ type Output = V;
/// Returns a reference to the value corresponding to the supplied key. /// /// # Panics /// /// Panics if the key is not present in the `HashMap`. #[inline] fn index(&self, key: &Q) -> &V { self.0.index(key)
}
}
impl<K, V> FromIterator<(K, V)> for AHashMap<K, V, RandomState> where
K: Eq + Hash,
{ /// This crates a hashmap from the provided iterator using [RandomState::new]. /// See the documentation in [RandomSource] for notes about key strength. fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self { letmut inner = HashMap::with_hasher(RandomState::new());
inner.extend(iter);
AHashMap(inner)
}
}
/// NOTE: For safety this trait impl is only available available if either of the flags `runtime-rng` (on by default) or /// `compile-time-rng` are enabled. This is to prevent weakly keyed maps from being accidentally created. Instead one of /// constructors for [RandomState] must be used. #[cfg(any(feature = "compile-time-rng", feature = "runtime-rng", feature = "no-rng"))] impl<K, V> Default for AHashMap<K, V, RandomState> { #[inline] fn default() -> AHashMap<K, V, RandomState> {
AHashMap(HashMap::default())
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.