From ba33f6aeae50a84caeead05a775bf4422270cae3 Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Thu, 17 May 2018 00:27:19 -0400 Subject: [PATCH 1/4] WIP: add raw_entry API to HashMap --- src/libstd/collections/hash/map.rs | 740 +++++++++++++++++++++++++++-- src/libstd/lib.rs | 1 + 2 files changed, 704 insertions(+), 37 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index a7eb002d5a1d9..0333421050d33 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -20,7 +20,7 @@ use fmt::{self, Debug}; use hash::{Hash, Hasher, BuildHasher, SipHasher13}; use iter::{FromIterator, FusedIterator}; use mem::{self, replace}; -use ops::{Deref, Index}; +use ops::{Deref, DerefMut, Index}; use sys; use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash}; @@ -422,6 +422,23 @@ fn search_hashed(table: M, hash: SafeHash, is_match: F) -> InternalE search_hashed_nonempty(table, hash, is_match) } +/// Search for a pre-hashed key. +/// If you don't already know the hash, use search or search_mut instead +#[inline] +fn search_hashed_mut(table: M, hash: SafeHash, is_match: F) -> InternalEntry + where M: DerefMut>, + F: FnMut(&mut K) -> bool +{ + // This is the only function where capacity can be zero. To avoid + // undefined behavior when Bucket::new gets the raw bucket in this + // case, immediately return the appropriate search result. + if table.capacity() == 0 { + return InternalEntry::TableIsEmpty; + } + + search_hashed_nonempty_mut(table, hash, is_match) +} + /// Search for a pre-hashed key when the hash map is known to be non-empty. #[inline] fn search_hashed_nonempty(table: M, hash: SafeHash, mut is_match: F) @@ -472,6 +489,56 @@ fn search_hashed_nonempty(table: M, hash: SafeHash, mut is_match: F) } } +/// Search for a pre-hashed key when the hash map is known to be non-empty. +#[inline] +fn search_hashed_nonempty_mut(table: M, hash: SafeHash, mut is_match: F) + -> InternalEntry + where M: DerefMut>, + F: FnMut(&mut K) -> bool +{ + // Do not check the capacity as an extra branch could slow the lookup. + + let size = table.size(); + let mut probe = Bucket::new(table, hash); + let mut displacement = 0; + + loop { + let mut full = match probe.peek() { + Empty(bucket) => { + // Found a hole! + return InternalEntry::Vacant { + hash, + elem: NoElem(bucket, displacement), + }; + } + Full(bucket) => bucket, + }; + + let probe_displacement = full.displacement(); + + if probe_displacement < displacement { + // Found a luckier bucket than me. + // We can finish the search early if we hit any bucket + // with a lower distance to initial bucket than we've probed. + return InternalEntry::Vacant { + hash, + elem: NeqElem(full, probe_displacement), + }; + } + + // If the hash doesn't match, it can't be this one.. + if hash == full.hash() { + // If the key doesn't match, it can't be this one.. + if is_match(full.read_mut().0) { + return InternalEntry::Occupied { elem: full }; + } + } + displacement += 1; + probe = full.next(); + debug_assert!(displacement <= size); + } +} + fn pop_internal(starting_bucket: FullBucketMut) -> (K, V, &mut RawTable) { @@ -1451,6 +1518,47 @@ impl HashMap } } +impl HashMap + where K: Eq + Hash, + S: BuildHasher +{ + /// Creates a raw entry builder for the HashMap. + /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with hash and + /// then manually searched. After this, insertions into the entry also + /// still require an owned key to be provided. + /// + /// Raw entries are useful for such exotic situations as: + /// + /// * Hash memoization + /// * Deferring the creation of an owned key until it is known to be required + /// * Using a HashMap where the key type can't or shouldn't be hashed and/or compared + /// + /// Unless you are in such a situation, higher-level and more foolproof APIs like + /// `entry` should be preferred. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn raw_entry(&mut self) -> RawEntryBuilder { + self.reserve(1); + RawEntryBuilder { map: self } + } + + /// Creates a raw immutable entry builder for the HashMap. + /// + /// This is useful for + /// * Hash memoization + /// * Querying a HashMap where the key type can't or shouldn't be hashed and/or compared + /// + /// Unless you are in such a situation, higher-level and more foolproof APIs like + /// `entry` should be preferred. + /// + /// Immutable raw entries have very limited use; you might instead want `raw_entry`. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn raw_entry_immut(&self) -> RawImmutableEntryBuilder { + RawImmutableEntryBuilder { map: self } + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for HashMap where K: Eq + Hash, @@ -1676,14 +1784,13 @@ impl<'a, K, V> InternalEntry> { InternalEntry::Occupied { elem } => { Some(Occupied(OccupiedEntry { key: Some(key), - elem, + entry: RawOccupiedEntry { elem }, })) } InternalEntry::Vacant { hash, elem } => { Some(Vacant(VacantEntry { - hash, key, - elem, + entry: RawVacantEntry { hash, elem } })) } InternalEntry::TableIsEmpty => None, @@ -1691,6 +1798,584 @@ impl<'a, K, V> InternalEntry> { } } +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> { + map: &'a mut HashMap, +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawEntryBuilderHashed<'a, K: 'a, V: 'a> { + map: &'a mut RawTable, + hash: SafeHash, +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub enum RawEntry<'a, K: 'a, V: 'a> { + /// WIP + Occupied(RawOccupiedEntry<'a, K, V>), + /// WIP + Vacant(RawVacantEntry<'a, K, V>), +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawOccupiedEntry<'a, K: 'a, V: 'a> { + elem: FullBucket>, +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawVacantEntry<'a, K: 'a, V: 'a> { + hash: SafeHash, + elem: VacantEntryState>, +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawImmutableEntryBuilder<'a, K: 'a, V: 'a, S: 'a> { + map: &'a HashMap, +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +pub struct RawImmutableEntryBuilderHashed<'a, K: 'a, V: 'a> { + map: &'a RawTable, + hash: SafeHash, +} + +impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> + where S: BuildHasher, +{ + /// Initializes the raw entry builder with the hash of the given query value. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn hash_by(self, k: &Q) -> RawEntryBuilderHashed<'a, K, V> + where Q: Hash + { + self.hash_with(|mut hasher| { + k.hash(&mut hasher); + hasher.finish() + }) + } + + /// Initializes the raw entry builder with the hash yielded by the given function. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn hash_with(self, func: F) -> RawEntryBuilderHashed<'a, K, V> + where F: FnOnce(S::Hasher) -> u64 + { + let hasher = self.map.hash_builder.build_hasher(); + let hash = SafeHash::new(func(hasher)); + + RawEntryBuilderHashed { map: &mut self.map.table, hash } + } + + /// Searches for the location of the raw entry with the given query value. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_by(self, k: &Q) -> RawEntry<'a, K, V> + where K: Borrow, + Q: Eq + Hash + { + self.hash_by(k).search_by(k) + } +} + +impl<'a, K, V> RawEntryBuilderHashed<'a, K, V> +{ + /// Searches for the location of the raw entry with the given query value. + /// + /// Note that it isn't required that the query value be hashable, as the + /// builder's hash is used. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_by(self, k: &Q) -> RawEntry<'a, K, V> + where K: Borrow, + Q: Eq, + { + // I don't know why we need this `&mut -> &` transform to resolve Borrow, but we do + self.search_with(|key| (&*key).borrow() == k) + } + + /// Searches for the location of the raw entry with the given comparison function. + /// + /// Note that mutable access is given to each key that is visited, because + /// this land is truly godless, and *someone* might have a use for this. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_with(self, func: F) -> RawEntry<'a, K, V> + where F: FnMut(&mut K) -> bool, + { + match search_hashed_mut(self.map, self.hash, func) { + InternalEntry::Occupied { elem } => { + RawEntry::Occupied(RawOccupiedEntry { elem }) + } + InternalEntry::Vacant { hash, elem } => { + RawEntry::Vacant(RawVacantEntry { hash, elem }) + } + InternalEntry::TableIsEmpty => { + unreachable!() + } + } + } +} + +impl<'a, K, V, S> RawImmutableEntryBuilder<'a, K, V, S> + where S: BuildHasher, +{ + /// Initializes the raw entry builder with the hash of the given query value. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn hash_by(self, k: &Q) -> RawImmutableEntryBuilderHashed<'a, K, V> + where Q: Hash + { + self.hash_with(|mut hasher| { + k.hash(&mut hasher); + hasher.finish() + }) + } + + /// Initializes the raw entry builder with the hash yielded by the given function. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn hash_with(self, func: F) -> RawImmutableEntryBuilderHashed<'a, K, V> + where F: FnOnce(S::Hasher) -> u64 + { + let hasher = self.map.hash_builder.build_hasher(); + let hash = SafeHash::new(func(hasher)); + + RawImmutableEntryBuilderHashed { map: &self.map.table, hash } + } + + /// Searches for the location of the raw entry with the given query value. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_by(self, k: &Q) -> Option<(&'a K, &'a V)> + where K: Borrow, + Q: Eq + Hash + { + self.hash_by(k).search_by(k) + } +} + +impl<'a, K, V> RawImmutableEntryBuilderHashed<'a, K, V> +{ + /// Searches for the location of the raw entry with the given query value. + /// + /// Note that it isn't required that the query value be hashable, as the + /// builder's hash is used. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_by(self, k: &Q) -> Option<(&'a K, &'a V)> + where K: Borrow, + Q: Eq, + { + self.search_with(|key| key.borrow() == k) + } + + /// Searches for the location of the raw entry with the given comparison function. + /// + /// Note that mutable access is given to each key that is visited, because + /// this land is truly godless, and *someone* might have a use for this. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn search_with(self, func: F) -> Option<(&'a K, &'a V)> + where F: FnMut(&K) -> bool, + { + match search_hashed(self.map, self.hash, func) { + InternalEntry::Occupied { elem } => { + Some(elem.into_refs()) + } + InternalEntry::Vacant { .. } | InternalEntry::TableIsEmpty => { + None + } + } + } +} + +impl<'a, K, V> RawEntry<'a, K, V> { + /// Ensures a value is in the entry by inserting the default if empty, and returns + /// a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// + /// *map.entry("poneyland").or_insert(12) += 10; + /// assert_eq!(map["poneyland"], 22); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V) { + match self { + RawEntry::Occupied(entry) => entry.into_kv(), + RawEntry::Vacant(entry) => entry.insert(default_key, default_val), + } + } + + /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// + /// let mut map: HashMap<&str, String> = HashMap::new(); + /// let s = "hoho".to_string(); + /// + /// map.entry("poneyland").or_insert_with(|| s); + /// + /// assert_eq!(map["poneyland"], "hoho".to_string()); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn or_insert_with(self, default: F) -> (&'a mut K, &'a mut V) + where F: FnOnce() -> (K, V), + { + match self { + RawEntry::Occupied(entry) => entry.into_kv(), + RawEntry::Vacant(entry) => { + let (k, v) = default(); + entry.insert(k, v) + } + } + } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn and_modify(self, f: F) -> Self + where F: FnOnce(&mut K, &mut V) + { + match self { + RawEntry::Occupied(mut entry) => { + { + let (k, v) = entry.kv_mut(); + f(k, v); + } + RawEntry::Occupied(entry) + }, + RawEntry::Vacant(entry) => RawEntry::Vacant(entry), + } + } +} + +impl<'a, K, V> RawOccupiedEntry<'a, K, V> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn key(&self) -> &K { + self.elem.read().0 + } + + /// Gets a mutable reference to the key in the entry. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn key_mut(&mut self) -> &mut K { + self.elem.read_mut().0 + } + + /// Converts the entry into a mutable reference to the key in the entry + /// with a lifetime bound to the map itself. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn into_key(self) -> &'a mut K { + self.elem.into_mut_refs().0 + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// assert_eq!(o.get(), &12); + /// } + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn get(&self) -> &V { + self.elem.read().1 + } + + /// Converts the OccupiedEntry into a mutable reference to the value in the entry + /// with a lifetime bound to the map itself. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// *o.into_mut() += 10; + /// } + /// + /// assert_eq!(map["poneyland"], 22); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn into_mut(self) -> &'a mut V { + self.elem.into_mut_refs().1 + } + + /// Gets a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// assert_eq!(map["poneyland"], 12); + /// if let Entry::Occupied(mut o) = map.entry("poneyland") { + /// *o.get_mut() += 10; + /// } + /// + /// assert_eq!(map["poneyland"], 22); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn get_mut(&mut self) -> &mut V { + self.elem.read_mut().1 + } + + /// Gets a reference to the key and value in the entry. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn kv(&mut self) -> (&K, &V) { + self.elem.read() + } + + /// Gets a mutable reference to the key and value in the entry. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn kv_mut(&mut self) -> (&mut K, &mut V) { + self.elem.read_mut() + } + + /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry + /// with a lifetime bound to the map itself. + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn into_kv(self) -> (&'a mut K, &'a mut V) { + self.elem.into_mut_refs() + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(mut o) = map.entry("poneyland") { + /// assert_eq!(o.insert(15), 12); + /// } + /// + /// assert_eq!(map["poneyland"], 15); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn insert(&mut self, value: V) -> V { + mem::replace(self.get_mut(), value) + } + + /// Sets the value of the entry, and returns the entry's old value. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(mut o) = map.entry("poneyland") { + /// assert_eq!(o.insert(15), 12); + /// } + /// + /// assert_eq!(map["poneyland"], 15); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn insert_key(&mut self, key: K) -> K { + mem::replace(self.key_mut(), key) + } + + /// Takes the value out of the entry, and returns it. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// assert_eq!(o.remove(), 12); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn remove(self) -> V { + pop_internal(self.elem).1 + } + + + /// Take the ownership of the key and value from the map. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// map.entry("poneyland").or_insert(12); + /// + /// if let Entry::Occupied(o) = map.entry("poneyland") { + /// // We delete the entry from the map. + /// o.remove_entry(); + /// } + /// + /// assert_eq!(map.contains_key("poneyland"), false); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn remove_entry(self) -> (K, V) { + let (k, v, _) = pop_internal(self.elem); + (k, v) + } +} + +impl<'a, K, V> RawVacantEntry<'a, K, V> { + /// Sets the value of the entry with the VacantEntry's key, + /// and returns a mutable reference to it. + /// + /// # Examples + /// + /// ``` + /// use std::collections::HashMap; + /// use std::collections::hash_map::Entry; + /// + /// let mut map: HashMap<&str, u32> = HashMap::new(); + /// + /// if let Entry::Vacant(o) = map.entry("poneyland") { + /// o.insert(37); + /// } + /// assert_eq!(map["poneyland"], 37); + /// ``` + #[unstable(feature = "raw_entry", issue = "42069")] + pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) { + let b = match self.elem { + NeqElem(mut bucket, disp) => { + if disp >= DISPLACEMENT_THRESHOLD { + bucket.table_mut().set_tag(true); + } + robin_hood(bucket, disp, self.hash, key, value) + }, + NoElem(mut bucket, disp) => { + if disp >= DISPLACEMENT_THRESHOLD { + bucket.table_mut().set_tag(true); + } + bucket.put(self.hash, key, value) + }, + }; + b.into_mut_refs() + } +} + +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V> Debug for RawEntryBuilderHashed<'a, K, V> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V> Debug for RawEntry<'a, K, V> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V> Debug for RawOccupiedEntry<'a, K, V> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V> Debug for RawVacantEntry<'a, K, V> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V, S> Debug for RawImmutableEntryBuilder<'a, K, V, S> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +/// WIP +#[unstable(feature = "raw_entry", issue = "42069")] +impl<'a, K, V> Debug for RawImmutableEntryBuilderHashed<'a, K, V> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + /// A view into a single entry in a map, which may either be vacant or occupied. /// /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. @@ -1735,7 +2420,7 @@ impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> { #[stable(feature = "rust1", since = "1.0.0")] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { key: Option, - elem: FullBucket>, + entry: RawOccupiedEntry<'a, K, V>, } #[stable(feature= "debug_hash_map", since = "1.12.0")] @@ -1754,9 +2439,8 @@ impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for OccupiedEntry<'a, K, V> { /// [`Entry`]: enum.Entry.html #[stable(feature = "rust1", since = "1.0.0")] pub struct VacantEntry<'a, K: 'a, V: 'a> { - hash: SafeHash, key: K, - elem: VacantEntryState>, + entry: RawVacantEntry<'a, K, V>, } #[stable(feature= "debug_hash_map", since = "1.12.0")] @@ -2182,7 +2866,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "map_entry_keys", since = "1.10.0")] pub fn key(&self) -> &K { - self.elem.read().0 + self.entry.key() } /// Take the ownership of the key and value from the map. @@ -2205,8 +2889,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] pub fn remove_entry(self) -> (K, V) { - let (k, v, _) = pop_internal(self.elem); - (k, v) + self.entry.remove_entry() } /// Gets a reference to the value in the entry. @@ -2226,7 +2909,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get(&self) -> &V { - self.elem.read().1 + self.entry.get() } /// Gets a mutable reference to the value in the entry. @@ -2249,7 +2932,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self) -> &mut V { - self.elem.read_mut().1 + self.entry.get_mut() } /// Converts the OccupiedEntry into a mutable reference to the value in the entry @@ -2273,7 +2956,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn into_mut(self) -> &'a mut V { - self.elem.into_mut_refs().1 + self.entry.into_mut() } /// Sets the value of the entry, and returns the entry's old value. @@ -2294,10 +2977,8 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// assert_eq!(map["poneyland"], 15); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn insert(&mut self, mut value: V) -> V { - let old_value = self.get_mut(); - mem::swap(&mut value, old_value); - value + pub fn insert(&mut self, value: V) -> V { + self.entry.insert(value) } /// Takes the value out of the entry, and returns it. @@ -2319,7 +3000,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn remove(self) -> V { - pop_internal(self.elem).1 + self.entry.remove() } /// Returns a key that was used for search. @@ -2352,7 +3033,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[unstable(feature = "map_entry_replace", issue = "44286")] pub fn replace_entry(mut self, value: V) -> (K, V) { - let (old_key, old_value) = self.elem.read_mut(); + let (old_key, old_value) = self.entry.kv_mut(); let old_key = mem::replace(old_key, self.key.unwrap()); let old_value = mem::replace(old_value, value); @@ -2387,8 +3068,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// ``` #[unstable(feature = "map_entry_replace", issue = "44286")] pub fn replace_key(mut self) -> K { - let (old_key, _) = self.elem.read_mut(); - mem::replace(old_key, self.key.unwrap()) + mem::replace(self.entry.key_mut(), self.key.unwrap()) } } @@ -2446,21 +3126,7 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(self, value: V) -> &'a mut V { - let b = match self.elem { - NeqElem(mut bucket, disp) => { - if disp >= DISPLACEMENT_THRESHOLD { - bucket.table_mut().set_tag(true); - } - robin_hood(bucket, disp, self.hash, self.key, value) - }, - NoElem(mut bucket, disp) => { - if disp >= DISPLACEMENT_THRESHOLD { - bucket.table_mut().set_tag(true); - } - bucket.put(self.hash, self.key, value) - }, - }; - b.into_mut_refs().1 + self.entry.insert(self.key, value).1 } } @@ -2671,7 +3337,7 @@ impl super::Recover for HashMap match self.entry(key) { Occupied(mut occupied) => { let key = occupied.take_key().unwrap(); - Some(mem::replace(occupied.elem.read_mut().0, key)) + Some(mem::replace(occupied.entry.key_mut(), key)) } Vacant(vacant) => { vacant.insert(()); diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index d41739ab02c6a..edae4b50efa2d 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -291,6 +291,7 @@ #![feature(ptr_internals)] #![feature(rand)] #![feature(raw)] +#![feature(raw_entry)] #![feature(rustc_attrs)] #![feature(std_internals)] #![feature(stdsimd)] From 0ef49706c216200bb2aac1832b01dcaff394ec07 Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Fri, 25 May 2018 14:56:21 -0400 Subject: [PATCH 2/4] progress on raw_entry --- src/libstd/collections/hash/map.rs | 460 +++++++++++++++-------------- src/libstd/lib.rs | 3 +- 2 files changed, 233 insertions(+), 230 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 0333421050d33..7c8550931c242 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1525,19 +1525,39 @@ impl HashMap /// Creates a raw entry builder for the HashMap. /// /// Raw entries provide the lowest level of control for searching and - /// manipulating a map. They must be manually initialized with hash and - /// then manually searched. After this, insertions into the entry also + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. After this, insertions into a vacant entry /// still require an owned key to be provided. /// /// Raw entries are useful for such exotic situations as: /// /// * Hash memoization /// * Deferring the creation of an owned key until it is known to be required - /// * Using a HashMap where the key type can't or shouldn't be hashed and/or compared + /// * Using a search key that doesn't work with the Borrow trait + /// * Using custom comparison logic without newtype wrappers + /// + /// Because raw entries provide much more low-level control, it's much easier + /// to put the HashMap into an inconsistent state which, while memory-safe, + /// will cause the map to produce seemingly random results. Higher-level and + /// more foolproof APIs like `entry` should be preferred when possible. + /// + /// In particular, the hash used to initialized the raw entry must still be + /// consistent with the hash of the key that is ultimately stored in the entry. + /// This is because implementations of HashMap may need to recompute hashes + /// when resizing, at which point only the keys are available. + /// + /// Raw entries give mutable access to the keys. This must not be used + /// to modify how the key would compare or hash, as the map will not re-evaluate + /// where the key should go, meaning the keys may become "lost" if their + /// location does not reflect their state. For instance, if you change a key + /// so that the map now contains keys which compare equal, search may start + /// acting eratically, with two keys randomly masking eachother. Implementations + /// are free to assume this doesn't happen (within the limits of memory-safety). /// - /// Unless you are in such a situation, higher-level and more foolproof APIs like - /// `entry` should be preferred. - #[unstable(feature = "raw_entry", issue = "42069")] + /// # Examples + /// + /// + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn raw_entry(&mut self) -> RawEntryBuilder { self.reserve(1); RawEntryBuilder { map: self } @@ -1545,15 +1565,20 @@ impl HashMap /// Creates a raw immutable entry builder for the HashMap. /// + /// Raw entries provide the lowest level of control for searching and + /// manipulating a map. They must be manually initialized with a hash and + /// then manually searched. + /// /// This is useful for /// * Hash memoization - /// * Querying a HashMap where the key type can't or shouldn't be hashed and/or compared + /// * Using a search key that doesn't work with the Borrow trait + /// * Using custom comparison logic without newtype wrappers /// /// Unless you are in such a situation, higher-level and more foolproof APIs like - /// `entry` should be preferred. + /// `get` should be preferred. /// /// Immutable raw entries have very limited use; you might instead want `raw_entry`. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn raw_entry_immut(&self) -> RawImmutableEntryBuilder { RawImmutableEntryBuilder { map: self } } @@ -1798,49 +1823,73 @@ impl<'a, K, V> InternalEntry> { } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A builder for computing where in a HashMap a key-value pair would be stored. +/// +/// See the [`HashMap::raw_entry`][] docs for usage examples. +#[unstable(feature = "hash_raw_entry", issue = "42069")] pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> { map: &'a mut HashMap, } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A builder for computing where in a HashMap a key-value pair would be stored, +/// where the hash has already been specified. +/// +/// See the [`HashMap::raw_entry`][] docs for usage examples. +#[unstable(feature = "hash_raw_entry", issue = "42069")] pub struct RawEntryBuilderHashed<'a, K: 'a, V: 'a> { map: &'a mut RawTable, hash: SafeHash, } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A view into a single entry in a map, which may either be vacant or occupied. +/// +/// This is a lower-level version of [`Entry`]. +/// +/// This `enum` is constructed from the [`raw_entry`] method on [`HashMap`]. +/// +/// [`HashMap`]: struct.HashMap.html +/// [`Entry`]: struct.Entry.html +/// [`raw_entry`]: struct.HashMap.html#method.raw_entry +#[unstable(feature = "hash_raw_entry", issue = "42069")] pub enum RawEntry<'a, K: 'a, V: 'a> { - /// WIP + /// An occupied entry. Occupied(RawOccupiedEntry<'a, K, V>), - /// WIP + /// A vacant entry. Vacant(RawVacantEntry<'a, K, V>), } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A view into an occupied entry in a `HashMap`. +/// It is part of the [`RawEntry`] enum. +/// +/// [`RawEntry`]: enum.RawEntry.html +#[unstable(feature = "hash_raw_entry", issue = "42069")] pub struct RawOccupiedEntry<'a, K: 'a, V: 'a> { elem: FullBucket>, } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A view into a vacant entry in a `HashMap`. +/// It is part of the [`RawEntry`] enum. +/// +/// [`RawEntry`]: enum.RawEntry.html +#[unstable(feature = "hash_raw_entry", issue = "42069")] pub struct RawVacantEntry<'a, K: 'a, V: 'a> { hash: SafeHash, elem: VacantEntryState>, } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A builder for computing where in a HashMap a key-value pair would be stored. +/// +/// See the [`HashMap::raw_entry_immut`][] docs for usage examples. +#[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub struct RawImmutableEntryBuilder<'a, K: 'a, V: 'a, S: 'a> { map: &'a HashMap, } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +/// A builder for computing where in a HashMap a key-value pair would be stored, +/// where the hash has already been specified. +/// +/// See the [`HashMap::raw_entry_immut`][] docs for usage examples. +#[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub struct RawImmutableEntryBuilderHashed<'a, K: 'a, V: 'a> { map: &'a RawTable, hash: SafeHash, @@ -1850,7 +1899,7 @@ impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> where S: BuildHasher, { /// Initializes the raw entry builder with the hash of the given query value. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn hash_by(self, k: &Q) -> RawEntryBuilderHashed<'a, K, V> where Q: Hash { @@ -1861,7 +1910,7 @@ impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> } /// Initializes the raw entry builder with the hash yielded by the given function. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn hash_with(self, func: F) -> RawEntryBuilderHashed<'a, K, V> where F: FnOnce(S::Hasher) -> u64 { @@ -1872,7 +1921,7 @@ impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> } /// Searches for the location of the raw entry with the given query value. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn search_by(self, k: &Q) -> RawEntry<'a, K, V> where K: Borrow, Q: Eq + Hash @@ -1887,7 +1936,7 @@ impl<'a, K, V> RawEntryBuilderHashed<'a, K, V> /// /// Note that it isn't required that the query value be hashable, as the /// builder's hash is used. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn search_by(self, k: &Q) -> RawEntry<'a, K, V> where K: Borrow, Q: Eq, @@ -1900,7 +1949,7 @@ impl<'a, K, V> RawEntryBuilderHashed<'a, K, V> /// /// Note that mutable access is given to each key that is visited, because /// this land is truly godless, and *someone* might have a use for this. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn search_with(self, func: F) -> RawEntry<'a, K, V> where F: FnMut(&mut K) -> bool, { @@ -1922,7 +1971,7 @@ impl<'a, K, V, S> RawImmutableEntryBuilder<'a, K, V, S> where S: BuildHasher, { /// Initializes the raw entry builder with the hash of the given query value. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn hash_by(self, k: &Q) -> RawImmutableEntryBuilderHashed<'a, K, V> where Q: Hash { @@ -1933,7 +1982,7 @@ impl<'a, K, V, S> RawImmutableEntryBuilder<'a, K, V, S> } /// Initializes the raw entry builder with the hash yielded by the given function. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn hash_with(self, func: F) -> RawImmutableEntryBuilderHashed<'a, K, V> where F: FnOnce(S::Hasher) -> u64 { @@ -1944,7 +1993,7 @@ impl<'a, K, V, S> RawImmutableEntryBuilder<'a, K, V, S> } /// Searches for the location of the raw entry with the given query value. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn search_by(self, k: &Q) -> Option<(&'a K, &'a V)> where K: Borrow, Q: Eq + Hash @@ -1959,7 +2008,7 @@ impl<'a, K, V> RawImmutableEntryBuilderHashed<'a, K, V> /// /// Note that it isn't required that the query value be hashable, as the /// builder's hash is used. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn search_by(self, k: &Q) -> Option<(&'a K, &'a V)> where K: Borrow, Q: Eq, @@ -1971,7 +2020,7 @@ impl<'a, K, V> RawImmutableEntryBuilderHashed<'a, K, V> /// /// Note that mutable access is given to each key that is visited, because /// this land is truly godless, and *someone* might have a use for this. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry_immut", issue = "42069")] pub fn search_with(self, func: F) -> Option<(&'a K, &'a V)> where F: FnMut(&K) -> bool, { @@ -1988,7 +2037,7 @@ impl<'a, K, V> RawImmutableEntryBuilderHashed<'a, K, V> impl<'a, K, V> RawEntry<'a, K, V> { /// Ensures a value is in the entry by inserting the default if empty, and returns - /// a mutable reference to the value in the entry. + /// mutable references to the key and value in the entry. /// /// # Examples /// @@ -1996,14 +2045,14 @@ impl<'a, K, V> RawEntry<'a, K, V> { /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); + /// map.raw_entry().search_by("poneyland").or_insert("poneyland", 12); /// /// assert_eq!(map["poneyland"], 12); /// - /// *map.entry("poneyland").or_insert(12) += 10; + /// *map.raw_entry().search_by("poneyland").or_insert("poneyland", 12).1 += 10; /// assert_eq!(map["poneyland"], 22); /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V) { match self { RawEntry::Occupied(entry) => entry.into_kv(), @@ -2012,7 +2061,7 @@ impl<'a, K, V> RawEntry<'a, K, V> { } /// Ensures a value is in the entry by inserting the result of the default function if empty, - /// and returns a mutable reference to the value in the entry. + /// and returns mutable references to the key and value in the entry. /// /// # Examples /// @@ -2020,13 +2069,14 @@ impl<'a, K, V> RawEntry<'a, K, V> { /// use std::collections::HashMap; /// /// let mut map: HashMap<&str, String> = HashMap::new(); - /// let s = "hoho".to_string(); /// - /// map.entry("poneyland").or_insert_with(|| s); + /// map.raw_entry().search_by("poneyland").or_insert_with(|| { + /// ("poneyland".to_string(), "hoho".to_string()) + /// }); /// /// assert_eq!(map["poneyland"], "hoho".to_string()); /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn or_insert_with(self, default: F) -> (&'a mut K, &'a mut V) where F: FnOnce() -> (K, V), { @@ -2049,17 +2099,19 @@ impl<'a, K, V> RawEntry<'a, K, V> { /// /// let mut map: HashMap<&str, u32> = HashMap::new(); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.raw_entry() + /// .search_by("poneyland") + /// .and_modify(|_k, v| { *v += 1 }) + /// .or_insert("poneyland", 42); /// assert_eq!(map["poneyland"], 42); /// - /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) - /// .or_insert(42); + /// map.raw_entry() + /// .search_by("poneyland") + /// .and_modify(|_k, v| { *v += 1 }) + /// .or_insert("poneyland", 42); /// assert_eq!(map["poneyland"], 43); /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn and_modify(self, f: F) -> Self where F: FnOnce(&mut K, &mut V) { @@ -2078,206 +2130,83 @@ impl<'a, K, V> RawEntry<'a, K, V> { impl<'a, K, V> RawOccupiedEntry<'a, K, V> { /// Gets a reference to the key in the entry. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn key(&self) -> &K { self.elem.read().0 } /// Gets a mutable reference to the key in the entry. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn key_mut(&mut self) -> &mut K { self.elem.read_mut().0 } /// Converts the entry into a mutable reference to the key in the entry /// with a lifetime bound to the map itself. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn into_key(self) -> &'a mut K { self.elem.into_mut_refs().0 } /// Gets a reference to the value in the entry. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// if let Entry::Occupied(o) = map.entry("poneyland") { - /// assert_eq!(o.get(), &12); - /// } - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn get(&self) -> &V { self.elem.read().1 } /// Converts the OccupiedEntry into a mutable reference to the value in the entry /// with a lifetime bound to the map itself. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// assert_eq!(map["poneyland"], 12); - /// if let Entry::Occupied(o) = map.entry("poneyland") { - /// *o.into_mut() += 10; - /// } - /// - /// assert_eq!(map["poneyland"], 22); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn into_mut(self) -> &'a mut V { self.elem.into_mut_refs().1 } /// Gets a mutable reference to the value in the entry. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// assert_eq!(map["poneyland"], 12); - /// if let Entry::Occupied(mut o) = map.entry("poneyland") { - /// *o.get_mut() += 10; - /// } - /// - /// assert_eq!(map["poneyland"], 22); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn get_mut(&mut self) -> &mut V { self.elem.read_mut().1 } /// Gets a reference to the key and value in the entry. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn kv(&mut self) -> (&K, &V) { self.elem.read() } /// Gets a mutable reference to the key and value in the entry. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn kv_mut(&mut self) -> (&mut K, &mut V) { self.elem.read_mut() } /// Converts the OccupiedEntry into a mutable reference to the key and value in the entry /// with a lifetime bound to the map itself. - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn into_kv(self) -> (&'a mut K, &'a mut V) { self.elem.into_mut_refs() } /// Sets the value of the entry, and returns the entry's old value. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// if let Entry::Occupied(mut o) = map.entry("poneyland") { - /// assert_eq!(o.insert(15), 12); - /// } - /// - /// assert_eq!(map["poneyland"], 15); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn insert(&mut self, value: V) -> V { mem::replace(self.get_mut(), value) } /// Sets the value of the entry, and returns the entry's old value. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// if let Entry::Occupied(mut o) = map.entry("poneyland") { - /// assert_eq!(o.insert(15), 12); - /// } - /// - /// assert_eq!(map["poneyland"], 15); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn insert_key(&mut self, key: K) -> K { mem::replace(self.key_mut(), key) } /// Takes the value out of the entry, and returns it. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// if let Entry::Occupied(o) = map.entry("poneyland") { - /// assert_eq!(o.remove(), 12); - /// } - /// - /// assert_eq!(map.contains_key("poneyland"), false); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn remove(self) -> V { pop_internal(self.elem).1 } /// Take the ownership of the key and value from the map. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// map.entry("poneyland").or_insert(12); - /// - /// if let Entry::Occupied(o) = map.entry("poneyland") { - /// // We delete the entry from the map. - /// o.remove_entry(); - /// } - /// - /// assert_eq!(map.contains_key("poneyland"), false); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn remove_entry(self) -> (K, V) { let (k, v, _) = pop_internal(self.elem); (k, v) @@ -2287,21 +2216,7 @@ impl<'a, K, V> RawOccupiedEntry<'a, K, V> { impl<'a, K, V> RawVacantEntry<'a, K, V> { /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it. - /// - /// # Examples - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hash_map::Entry; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// - /// if let Entry::Vacant(o) = map.entry("poneyland") { - /// o.insert(37); - /// } - /// assert_eq!(map["poneyland"], 37); - /// ``` - #[unstable(feature = "raw_entry", issue = "42069")] + #[unstable(feature = "hash_raw_entry", issue = "42069")] pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) { let b = match self.elem { NeqElem(mut bucket, disp) => { @@ -2321,58 +2236,74 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> { } } -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry", issue = "42069")] impl<'a, K, V, S> Debug for RawEntryBuilder<'a, K, V, S> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawEntryBuilder") + .finish() } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry", issue = "42069")] impl<'a, K, V> Debug for RawEntryBuilderHashed<'a, K, V> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawEntryBuilderHashed") + .field("hash", &self.hash.inspect()) + .finish() } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry", issue = "42069")] impl<'a, K, V> Debug for RawEntry<'a, K, V> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + RawEntry::Vacant(ref v) => { + f.debug_tuple("RawEntry") + .field(v) + .finish() + } + RawEntry::Occupied(ref o) => { + f.debug_tuple("RawEntry") + .field(o) + .finish() + } + } } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry", issue = "42069")] impl<'a, K, V> Debug for RawOccupiedEntry<'a, K, V> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawOccupiedEntry") + .field("key", self.key()) + .field("value", self.get()) + .finish() } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry", issue = "42069")] impl<'a, K, V> Debug for RawVacantEntry<'a, K, V> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawVacantEntry") + .field("hash", &self.hash.inspect()) + .finish() } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry_immut", issue = "42069")] impl<'a, K, V, S> Debug for RawImmutableEntryBuilder<'a, K, V, S> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawImmutableEntryBuilder") + .finish() } } -/// WIP -#[unstable(feature = "raw_entry", issue = "42069")] +#[unstable(feature = "hash_raw_entry_immut", issue = "42069")] impl<'a, K, V> Debug for RawImmutableEntryBuilderHashed<'a, K, V> { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("RawImmutableEntryBuilderHashed") + .field("hash", &self.hash.inspect()) + .finish() } } @@ -3388,7 +3319,6 @@ fn assert_covariance() { #[cfg(test)] mod test_map { use super::HashMap; - use super::Entry::{Occupied, Vacant}; use super::RandomState; use cell::RefCell; use rand::{thread_rng, Rng}; @@ -3627,6 +3557,8 @@ mod test_map { #[test] fn test_empty_entry() { + use super::Entry::{Occupied, Vacant}; + let mut m: HashMap = HashMap::new(); match m.entry(0) { Occupied(_) => panic!(), @@ -4085,6 +4017,8 @@ mod test_map { #[test] fn test_entry() { + use super::Entry::{Occupied, Vacant}; + let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; let mut map: HashMap<_, _> = xs.iter().cloned().collect(); @@ -4138,6 +4072,9 @@ mod test_map { #[test] fn test_entry_take_doesnt_corrupt() { #![allow(deprecated)] //rand + + use super::Entry::{Occupied, Vacant}; + // Test for #19292 fn check(m: &HashMap) { for k in m.keys() { @@ -4212,6 +4149,8 @@ mod test_map { #[test] fn test_occupied_entry_key() { + use super::Entry::{Occupied, Vacant}; + let mut a = HashMap::new(); let key = "hello there"; let value = "value goes here"; @@ -4230,6 +4169,8 @@ mod test_map { #[test] fn test_vacant_entry_key() { + use super::Entry::{Occupied, Vacant}; + let mut a = HashMap::new(); let key = "hello there"; let value = "value goes here"; @@ -4305,4 +4246,65 @@ mod test_map { } } + #[test] + fn test_raw_entry() { + use super::RawEntry::{Occupied, Vacant}; + + let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; + + let mut map: HashMap<_, _> = xs.iter().cloned().collect(); + + // Existing key (insert) + match map.raw_entry().search_by(&1) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + assert_eq!(view.get(), &10); + assert_eq!(view.insert(100), 10); + } + } + assert_eq!(map.raw_entry_immut().hash_with(|mut h| { + 1.hash(&mut h); + h.finish() + }).search_with(|k| *k == 1) + .unwrap(), (&10, &100)); + assert_eq!(map.len(), 6); + + + // Existing key (update) + match map.raw_entry().hash_by(&2).search_by(&2) { + Vacant(_) => unreachable!(), + Occupied(mut view) => { + let v = view.get_mut(); + let new_v = (*v) * 10; + *v = new_v; + } + } + assert_eq!(map.raw_entry_immut().search_by(&2).unwrap(), (&2, &200)); + assert_eq!(map.len(), 6); + + // Existing key (take) + match map.raw_entry().hash_with(|mut h| { + 3.hash(&mut h); + h.finish() + }).search_with(|k| *k == 3) { + Vacant(_) => unreachable!(), + Occupied(view) => { + assert_eq!(view.remove_kv(), (3, 30)); + } + } + assert_eq!(map.raw_entry_immut().search_by(&3), None); + assert_eq!(map.len(), 5); + + + // Inexistent key (insert) + match map.raw_entry().search_by(&10) { + Occupied(_) => unreachable!(), + Vacant(view) => { + assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000)); + } + } + assert_eq!(map.raw_entry_immut().hash_by(&10).search_by(&10).unwrap(), (&10, &1000)); + assert_eq!(map.len(), 6); + } + } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index edae4b50efa2d..83144c5b324dc 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -291,7 +291,8 @@ #![feature(ptr_internals)] #![feature(rand)] #![feature(raw)] -#![feature(raw_entry)] +#![feature(hash_raw_entry)] +#![feature(hash_raw_entry_immut)] #![feature(rustc_attrs)] #![feature(std_internals)] #![feature(stdsimd)] From fd4593fcdff233d0658162ec7859f988c0656393 Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Fri, 25 May 2018 16:03:50 -0400 Subject: [PATCH 3/4] fixup Debug bounds --- src/libstd/collections/hash/map.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 7c8550931c242..2bcc57adc4883 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -2254,7 +2254,7 @@ impl<'a, K, V> Debug for RawEntryBuilderHashed<'a, K, V> { } #[unstable(feature = "hash_raw_entry", issue = "42069")] -impl<'a, K, V> Debug for RawEntry<'a, K, V> { +impl<'a, K: Debug, V: Debug> Debug for RawEntry<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RawEntry::Vacant(ref v) => { @@ -2272,7 +2272,7 @@ impl<'a, K, V> Debug for RawEntry<'a, K, V> { } #[unstable(feature = "hash_raw_entry", issue = "42069")] -impl<'a, K, V> Debug for RawOccupiedEntry<'a, K, V> { +impl<'a, K: Debug, V: Debug> Debug for RawOccupiedEntry<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("RawOccupiedEntry") .field("key", self.key()) From 8ec7bdda90285505c205b012de13088d1d1d8efe Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Fri, 25 May 2018 19:10:25 -0400 Subject: [PATCH 4/4] disambiguate hashes --- src/libstd/collections/hash/map.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 2bcc57adc4883..1f58c6876cae4 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -4250,7 +4250,7 @@ mod test_map { fn test_raw_entry() { use super::RawEntry::{Occupied, Vacant}; - let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; + let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; let mut map: HashMap<_, _> = xs.iter().cloned().collect(); @@ -4263,7 +4263,7 @@ mod test_map { } } assert_eq!(map.raw_entry_immut().hash_with(|mut h| { - 1.hash(&mut h); + 1i32.hash(&mut h); h.finish() }).search_with(|k| *k == 1) .unwrap(), (&10, &100)); @@ -4284,7 +4284,7 @@ mod test_map { // Existing key (take) match map.raw_entry().hash_with(|mut h| { - 3.hash(&mut h); + 3i32.hash(&mut h); h.finish() }).search_with(|k| *k == 3) { Vacant(_) => unreachable!(),