From 951bda3600bcfd039f4e40b304017b4fc1321aa5 Mon Sep 17 00:00:00 2001 From: kingdido999 Date: Sun, 9 Sep 2018 10:14:36 +0800 Subject: [PATCH] Format hashglobe #21373 --- components/hashglobe/src/alloc.rs | 46 ++- components/hashglobe/src/fake.rs | 87 +++--- components/hashglobe/src/hash_map.rs | 409 ++++++++++++++------------- components/hashglobe/src/hash_set.rs | 229 +++++++++------ components/hashglobe/src/lib.rs | 13 +- components/hashglobe/src/shim.rs | 6 +- components/hashglobe/src/table.rs | 196 +++++++------ 7 files changed, 552 insertions(+), 434 deletions(-) diff --git a/components/hashglobe/src/alloc.rs b/components/hashglobe/src/alloc.rs index b0d622972db1..b1c7a6eca5ee 100644 --- a/components/hashglobe/src/alloc.rs +++ b/components/hashglobe/src/alloc.rs @@ -1,25 +1,26 @@ // FORK NOTE: Copied from liballoc_system, removed unnecessary APIs, // APIs take size/align directly instead of Layout - - - // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. In practice, the alignment is a // constant at the call site and the branch will be optimized out. -#[cfg(all(any(target_arch = "x86", - target_arch = "arm", - target_arch = "mips", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "asmjs", - target_arch = "wasm32")))] +#[cfg(all(any( + target_arch = "x86", + target_arch = "arm", + target_arch = "mips", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "asmjs", + target_arch = "wasm32" +)))] const MIN_ALIGN: usize = 8; -#[cfg(all(any(target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "mips64", - target_arch = "s390x", - target_arch = "sparc64")))] +#[cfg(all(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "mips64", + target_arch = "s390x", + target_arch = "sparc64" +)))] const MIN_ALIGN: usize = 16; pub use self::platform::{alloc, dealloc, realloc}; @@ -100,7 +101,6 @@ mod platform { type DWORD = u32; type BOOL = i32; - extern "system" { fn GetProcessHeap() -> HANDLE; fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; @@ -123,8 +123,7 @@ mod platform { } #[inline] - unsafe fn allocate_with_flags(size: usize, align: usize, flags: DWORD) -> *mut u8 - { + unsafe fn allocate_with_flags(size: usize, align: usize, flags: DWORD) -> *mut u8 { if align <= MIN_ALIGN { HeapAlloc(GetProcessHeap(), flags, size) } else { @@ -147,21 +146,16 @@ mod platform { pub unsafe fn dealloc(ptr: *mut u8, align: usize) { if align <= MIN_ALIGN { let err = HeapFree(GetProcessHeap(), 0, ptr as LPVOID); - debug_assert!(err != 0, "Failed to free heap memory: {}", - GetLastError()); + debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError()); } else { let header = get_header(ptr); let err = HeapFree(GetProcessHeap(), 0, header.0 as LPVOID); - debug_assert!(err != 0, "Failed to free heap memory: {}", - GetLastError()); + debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError()); } } #[inline] pub unsafe fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8 { - HeapReAlloc(GetProcessHeap(), - 0, - ptr as LPVOID, - new_size) as *mut u8 + HeapReAlloc(GetProcessHeap(), 0, ptr as LPVOID, new_size) as *mut u8 } } diff --git a/components/hashglobe/src/fake.rs b/components/hashglobe/src/fake.rs index eba21e041488..c5cd9d39bb75 100644 --- a/components/hashglobe/src/fake.rs +++ b/components/hashglobe/src/fake.rs @@ -26,7 +26,6 @@ pub use std::collections::hash_set::{Iter as SetIter, IntoIter as SetIntoIter}; #[derive(Clone)] pub struct HashMap(StdMap); - use FailedAllocationError; impl Deref for HashMap { @@ -43,8 +42,9 @@ impl DerefMut for HashMap { } impl HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { #[inline] pub fn try_with_hasher(hash_builder: S) -> Result, FailedAllocationError> { @@ -52,17 +52,20 @@ impl HashMap } #[inline] - pub fn try_with_capacity_and_hasher(capacity: usize, - hash_builder: S) - -> Result, FailedAllocationError> { - Ok(HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder))) + pub fn try_with_capacity_and_hasher( + capacity: usize, + hash_builder: S, + ) -> Result, FailedAllocationError> { + Ok(HashMap(StdMap::with_capacity_and_hasher( + capacity, + hash_builder, + ))) } pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap { HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder)) } - #[inline] pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> { Ok(self.reserve(additional)) @@ -85,7 +88,6 @@ impl HashMap #[derive(Clone)] pub struct HashSet(StdSet); - impl Deref for HashSet { type Target = StdSet; fn deref(&self) -> &Self::Target { @@ -111,17 +113,16 @@ impl HashSet { } } - impl HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { #[inline] pub fn with_hasher(hasher: S) -> HashSet { HashSet(StdSet::with_hasher(hasher)) } - #[inline] pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet { HashSet(StdSet::with_capacity_and_hasher(capacity, hasher)) @@ -153,18 +154,21 @@ impl Default for HashMap { } impl fmt::Debug for HashMap - where K: Eq + Hash + fmt::Debug, - V: fmt::Debug, - S: BuildHasher { +where + K: Eq + Hash + fmt::Debug, + V: fmt::Debug, + S: BuildHasher, +{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl PartialEq for HashMap - where K: Eq + Hash, - V: PartialEq, - S: BuildHasher +where + K: Eq + Hash, + V: PartialEq, + S: BuildHasher, { fn eq(&self, other: &HashMap) -> bool { self.0.eq(&other.0) @@ -172,15 +176,17 @@ impl PartialEq for HashMap } impl Eq for HashMap - where K: Eq + Hash, - V: Eq, - S: BuildHasher +where + K: Eq + Hash, + V: Eq, + S: BuildHasher, { } impl<'a, K, V, S> IntoIterator for &'a HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { type Item = (&'a K, &'a V); type IntoIter = MapIter<'a, K, V>; @@ -191,8 +197,9 @@ impl<'a, K, V, S> IntoIterator for &'a HashMap } impl<'a, K, V, S> IntoIterator for &'a mut HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { type Item = (&'a K, &'a mut V); type IntoIter = MapIterMut<'a, K, V>; @@ -209,8 +216,9 @@ impl Default for HashSet { } impl fmt::Debug for HashSet - where T: Eq + Hash + fmt::Debug, - S: BuildHasher +where + T: Eq + Hash + fmt::Debug, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) @@ -218,8 +226,9 @@ impl fmt::Debug for HashSet } impl PartialEq for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { fn eq(&self, other: &HashSet) -> bool { self.0.eq(&other.0) @@ -227,14 +236,16 @@ impl PartialEq for HashSet } impl Eq for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { } impl<'a, T, S> IntoIterator for &'a HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; type IntoIter = SetIter<'a, T>; @@ -245,16 +256,14 @@ impl<'a, T, S> IntoIterator for &'a HashSet } impl IntoIterator for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = T; type IntoIter = SetIntoIter; - fn into_iter(self) -> SetIntoIter { self.0.into_iter() } } - - diff --git a/components/hashglobe/src/hash_map.rs b/components/hashglobe/src/hash_map.rs index 27077526b3ae..57ac9bcc049c 100644 --- a/components/hashglobe/src/hash_map.rs +++ b/components/hashglobe/src/hash_map.rs @@ -25,7 +25,7 @@ use super::table::BucketState::{Empty, Full}; use FailedAllocationError; -const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two +const MIN_NONZERO_RAW_CAPACITY: usize = 32; // must be a power of two /// The default behavior of HashMap implements a maximum load factor of 90.9%. #[derive(Clone)] @@ -50,7 +50,9 @@ impl DefaultResizePolicy { // 3. Ensure it is at least the minimum size. let mut raw_cap = len * 11 / 10; assert!(raw_cap >= len, "raw_cap overflow"); - raw_cap = raw_cap.checked_next_power_of_two().expect("raw_capacity overflow"); + raw_cap = raw_cap + .checked_next_power_of_two() + .expect("raw_capacity overflow"); raw_cap = max(MIN_NONZERO_RAW_CAPACITY, raw_cap); raw_cap } @@ -398,8 +400,9 @@ pub struct HashMap { /// Search for a pre-hashed key. #[inline] fn search_hashed(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry - where M: Deref>, - F: FnMut(&K) -> bool +where + M: Deref>, + F: FnMut(&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 @@ -420,7 +423,7 @@ fn search_hashed(table: M, hash: SafeHash, mut is_match: F) -> Inter hash, elem: NoElem(bucket, displacement), }; - } + }, Full(bucket) => bucket, }; @@ -449,9 +452,7 @@ fn search_hashed(table: M, hash: SafeHash, mut is_match: F) -> Inter } } -fn pop_internal(starting_bucket: FullBucketMut) - -> (K, V, &mut RawTable) -{ +fn pop_internal(starting_bucket: FullBucketMut) -> (K, V, &mut RawTable) { let (empty, retkey, retval) = starting_bucket.take(); let mut gap = match empty.gap_peek() { Ok(b) => b, @@ -475,12 +476,13 @@ fn pop_internal(starting_bucket: FullBucketMut) /// also pass that bucket's displacement so we don't have to recalculate it. /// /// `hash`, `key`, and `val` are the elements to "robin hood" into the hashtable. -fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>, - mut displacement: usize, - mut hash: SafeHash, - mut key: K, - mut val: V) - -> FullBucketMut<'a, K, V> { +fn robin_hood<'a, K: 'a, V: 'a>( + bucket: FullBucketMut<'a, K, V>, + mut displacement: usize, + mut hash: SafeHash, + mut key: K, + mut val: V, +) -> FullBucketMut<'a, K, V> { let size = bucket.table().size(); let raw_capacity = bucket.table().capacity(); // There can be at most `size - dib` buckets to displace, because @@ -513,7 +515,7 @@ fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>, // FullBucketMut, into just one FullBucketMut. The "table" // refers to the inner FullBucketMut in this context. return bucket.into_table(); - } + }, Full(bucket) => bucket, }; @@ -531,11 +533,13 @@ fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>, } impl HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { fn make_hash(&self, x: &X) -> SafeHash - where X: Hash + where + X: Hash, { table::make_hash(&self.hash_builder, x) } @@ -545,8 +549,9 @@ impl HashMap /// search_hashed. #[inline] fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry> - where K: Borrow, - Q: Eq + Hash + where + K: Borrow, + Q: Eq + Hash, { let hash = self.make_hash(q); search_hashed(&self.table, hash, |k| q.eq(k.borrow())) @@ -554,8 +559,9 @@ impl HashMap #[inline] fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry> - where K: Borrow, - Q: Eq + Hash + where + K: Borrow, + Q: Eq + Hash, { let hash = self.make_hash(q); search_hashed(&mut self.table, hash, |k| q.eq(k.borrow())) @@ -574,7 +580,7 @@ impl HashMap Empty(empty) => { empty.put(hash, k, v); return; - } + }, Full(b) => b.into_bucket(), }; buckets.next(); @@ -584,8 +590,9 @@ impl HashMap } impl HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { /// Creates an empty `HashMap` which will use the given hash builder to hash /// keys. @@ -643,7 +650,10 @@ impl HashMap /// map.insert(1, 2); /// ``` #[inline] - pub fn try_with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Result, FailedAllocationError> { + pub fn try_with_capacity_and_hasher( + capacity: usize, + hash_builder: S, + ) -> Result, FailedAllocationError> { let resize_policy = DefaultResizePolicy::new(); let raw_cap = resize_policy.raw_capacity(capacity); Ok(HashMap { @@ -708,12 +718,14 @@ impl HashMap self.try_reserve(additional).unwrap(); } - #[inline] pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> { let remaining = self.capacity() - self.len(); // this can't overflow if remaining < additional { - let min_cap = self.len().checked_add(additional).expect("reserve overflow"); + let min_cap = self + .len() + .checked_add(additional) + .expect("reserve overflow"); let raw_cap = self.resize_policy.raw_capacity(min_cap); self.try_resize(raw_cap)?; } else if self.table.tag() && remaining <= self.len() { @@ -763,7 +775,7 @@ impl HashMap break; } b.into_bucket() - } + }, Empty(b) => b.into_bucket(), }; bucket.next(); @@ -822,7 +834,7 @@ impl HashMap Some(Vacant(elem)) => { elem.insert(v); None - } + }, None => unreachable!(), } } @@ -892,7 +904,9 @@ impl HashMap /// } /// ``` pub fn values_mut(&mut self) -> ValuesMut { - ValuesMut { inner: self.iter_mut() } + ValuesMut { + inner: self.iter_mut(), + } } /// An iterator visiting all key-value pairs in arbitrary order. @@ -913,7 +927,9 @@ impl HashMap /// } /// ``` pub fn iter(&self) -> Iter { - Iter { inner: self.table.iter() } + Iter { + inner: self.table.iter(), + } } /// An iterator visiting all key-value pairs in arbitrary order, @@ -940,7 +956,9 @@ impl HashMap /// } /// ``` pub fn iter_mut(&mut self) -> IterMut { - IterMut { inner: self.table.iter_mut() } + IterMut { + inner: self.table.iter_mut(), + } } /// Gets the given key's corresponding entry in the map for in-place manipulation. @@ -972,7 +990,8 @@ impl HashMap self.try_reserve(1)?; let hash = self.make_hash(&key); Ok(search_hashed(&mut self.table, hash, |q| q.eq(&key)) - .into_entry(key).expect("unreachable")) + .into_entry(key) + .expect("unreachable")) } /// Returns the number of elements in the map. @@ -1028,8 +1047,14 @@ impl HashMap /// assert!(a.is_empty()); /// ``` #[inline] - pub fn drain(&mut self) -> Drain where K: 'static, V: 'static { - Drain { inner: self.table.drain() } + pub fn drain(&mut self) -> Drain + where + K: 'static, + V: 'static, + { + Drain { + inner: self.table.drain(), + } } /// Clears the map, removing all key-value pairs. Keeps the allocated memory @@ -1046,7 +1071,11 @@ impl HashMap /// assert!(a.is_empty()); /// ``` #[inline] - pub fn clear(&mut self) where K: 'static, V: 'static { + pub fn clear(&mut self) + where + K: 'static, + V: 'static, + { self.drain(); } @@ -1070,10 +1099,13 @@ impl HashMap /// assert_eq!(map.get(&2), None); /// ``` pub fn get(&self, k: &Q) -> Option<&V> - where K: Borrow, - Q: Hash + Eq + where + K: Borrow, + Q: Hash + Eq, { - self.search(k).into_occupied_bucket().map(|bucket| bucket.into_refs().1) + self.search(k) + .into_occupied_bucket() + .map(|bucket| bucket.into_refs().1) } /// Returns true if the map contains a value for the specified key. @@ -1096,8 +1128,9 @@ impl HashMap /// assert_eq!(map.contains_key(&2), false); /// ``` pub fn contains_key(&self, k: &Q) -> bool - where K: Borrow, - Q: Hash + Eq + where + K: Borrow, + Q: Hash + Eq, { self.search(k).into_occupied_bucket().is_some() } @@ -1124,10 +1157,13 @@ impl HashMap /// assert_eq!(map[&1], "b"); /// ``` pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> - where K: Borrow, - Q: Hash + Eq + where + K: Borrow, + Q: Hash + Eq, { - self.search_mut(k).into_occupied_bucket().map(|bucket| bucket.into_mut_refs().1) + self.search_mut(k) + .into_occupied_bucket() + .map(|bucket| bucket.into_mut_refs().1) } /// Inserts a key-value pair into the map. @@ -1187,14 +1223,17 @@ impl HashMap /// assert_eq!(map.remove(&1), None); /// ``` pub fn remove(&mut self, k: &Q) -> Option - where K: Borrow, - Q: Hash + Eq + where + K: Borrow, + Q: Hash + Eq, { if self.table.size() == 0 { return None; } - self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1) + self.search_mut(k) + .into_occupied_bucket() + .map(|bucket| pop_internal(bucket).1) } /// Retains only the elements specified by the predicate. @@ -1211,7 +1250,8 @@ impl HashMap /// assert_eq!(map.len(), 4); /// ``` pub fn retain(&mut self, mut f: F) - where F: FnMut(&K, &mut V) -> bool + where + F: FnMut(&K, &mut V) -> bool, { if self.table.size() == 0 { return; @@ -1236,41 +1276,43 @@ impl HashMap full.into_bucket() } }, - Empty(b) => { - b.into_bucket() - } + Empty(b) => b.into_bucket(), }; - bucket.prev(); // reverse iteration + bucket.prev(); // reverse iteration debug_assert!(elems_left == 0 || bucket.index() != start_index); } } } impl PartialEq for HashMap - where K: Eq + Hash, - V: PartialEq, - S: BuildHasher +where + K: Eq + Hash, + V: PartialEq, + S: BuildHasher, { fn eq(&self, other: &HashMap) -> bool { if self.len() != other.len() { return false; } - self.iter().all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) + self.iter() + .all(|(key, value)| other.get(key).map_or(false, |v| *value == *v)) } } impl Eq for HashMap - where K: Eq + Hash, - V: Eq, - S: BuildHasher +where + K: Eq + Hash, + V: Eq, + S: BuildHasher, { } impl Debug for HashMap - where K: Eq + Hash + Debug, - V: Debug, - S: BuildHasher +where + K: Eq + Hash + Debug, + V: Debug, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self.iter()).finish() @@ -1278,8 +1320,9 @@ impl Debug for HashMap } impl Default for HashMap - where K: Eq + Hash, - S: BuildHasher + Default +where + K: Eq + Hash, + S: BuildHasher + Default, { /// Creates an empty `HashMap`, with the `Default` value for the hasher. fn default() -> HashMap { @@ -1288,9 +1331,10 @@ impl Default for HashMap } impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap - where K: Eq + Hash + Borrow, - Q: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash + Borrow, + Q: Eq + Hash, + S: BuildHasher, { type Output = V; @@ -1314,15 +1358,15 @@ pub struct Iter<'a, K: 'a, V: 'a> { // FIXME(#19839) Remove in favor of `#[derive(Clone)]` impl<'a, K, V> Clone for Iter<'a, K, V> { fn clone(&self) -> Iter<'a, K, V> { - Iter { inner: self.inner.clone() } + Iter { + inner: self.inner.clone(), + } } } impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.clone()) - .finish() + f.debug_list().entries(self.clone()).finish() } } @@ -1362,15 +1406,15 @@ pub struct Keys<'a, K: 'a, V: 'a> { // FIXME(#19839) Remove in favor of `#[derive(Clone)]` impl<'a, K, V> Clone for Keys<'a, K, V> { fn clone(&self) -> Keys<'a, K, V> { - Keys { inner: self.inner.clone() } + Keys { + inner: self.inner.clone(), + } } } impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.clone()) - .finish() + f.debug_list().entries(self.clone()).finish() } } @@ -1388,15 +1432,15 @@ pub struct Values<'a, K: 'a, V: 'a> { // FIXME(#19839) Remove in favor of `#[derive(Clone)]` impl<'a, K, V> Clone for Values<'a, K, V> { fn clone(&self) -> Values<'a, K, V> { - Values { inner: self.inner.clone() } + Values { + inner: self.inner.clone(), + } } } impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.clone()) - .finish() + f.debug_list().entries(self.clone()).finish() } } @@ -1423,7 +1467,9 @@ pub struct ValuesMut<'a, K: 'a, V: 'a> { } enum InternalEntry { - Occupied { elem: FullBucket }, + Occupied { + elem: FullBucket, + }, Vacant { hash: SafeHash, elem: VacantEntryState, @@ -1445,19 +1491,11 @@ impl<'a, K, V> InternalEntry> { #[inline] fn into_entry(self, key: K) -> Option> { match self { - InternalEntry::Occupied { elem } => { - Some(Occupied(OccupiedEntry { - key: Some(key), - elem, - })) - } - InternalEntry::Vacant { hash, elem } => { - Some(Vacant(VacantEntry { - hash, - key, - elem, - })) - } + InternalEntry::Occupied { elem } => Some(Occupied(OccupiedEntry { + key: Some(key), + elem, + })), + InternalEntry::Vacant { hash, elem } => Some(Vacant(VacantEntry { hash, key, elem })), InternalEntry::TableIsEmpty => None, } } @@ -1471,25 +1509,17 @@ impl<'a, K, V> InternalEntry> { /// [`entry`]: struct.HashMap.html#method.entry pub enum Entry<'a, K: 'a, V: 'a> { /// An occupied entry. - Occupied( OccupiedEntry<'a, K, V>), + Occupied(OccupiedEntry<'a, K, V>), /// A vacant entry. - Vacant( VacantEntry<'a, K, V>), + Vacant(VacantEntry<'a, K, V>), } impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Vacant(ref v) => { - f.debug_tuple("Entry") - .field(v) - .finish() - } - Occupied(ref o) => { - f.debug_tuple("Entry") - .field(o) - .finish() - } + Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(), + Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(), } } } @@ -1524,9 +1554,7 @@ pub struct VacantEntry<'a, K: 'a, V: 'a> { impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_tuple("VacantEntry") - .field(self.key()) - .finish() + f.debug_tuple("VacantEntry").field(self.key()).finish() } } @@ -1540,8 +1568,9 @@ enum VacantEntryState { } impl<'a, K, V, S> IntoIterator for &'a HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; @@ -1552,8 +1581,9 @@ impl<'a, K, V, S> IntoIterator for &'a HashMap } impl<'a, K, V, S> IntoIterator for &'a mut HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; @@ -1564,8 +1594,9 @@ impl<'a, K, V, S> IntoIterator for &'a mut HashMap } impl IntoIterator for HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { type Item = (K, V); type IntoIter = IntoIter; @@ -1588,7 +1619,9 @@ impl IntoIterator for HashMap /// let vec: Vec<(&str, isize)> = map.into_iter().collect(); /// ``` fn into_iter(self) -> IntoIter { - IntoIter { inner: self.table.into_iter() } + IntoIter { + inner: self.table.into_iter(), + } } } @@ -1611,7 +1644,6 @@ impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> { } } - impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); @@ -1632,13 +1664,12 @@ impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> { } impl<'a, K, V> fmt::Debug for IterMut<'a, K, V> - where K: fmt::Debug, - V: fmt::Debug, +where + K: fmt::Debug, + V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.inner.iter()) - .finish() + f.debug_list().entries(self.inner.iter()).finish() } } @@ -1663,9 +1694,7 @@ impl ExactSizeIterator for IntoIter { impl fmt::Debug for IntoIter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.inner.iter()) - .finish() + f.debug_list().entries(self.inner.iter()).finish() } } @@ -1726,13 +1755,12 @@ impl<'a, K, V> ExactSizeIterator for ValuesMut<'a, K, V> { } impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V> - where K: fmt::Debug, - V: fmt::Debug, +where + K: fmt::Debug, + V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.inner.inner.iter()) - .finish() + f.debug_list().entries(self.inner.inner.iter()).finish() } } @@ -1756,20 +1784,19 @@ impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> { } impl<'a, K, V> fmt::Debug for Drain<'a, K, V> - where K: fmt::Debug, - V: fmt::Debug, +where + K: fmt::Debug, + V: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(self.inner.iter()) - .finish() + f.debug_list().entries(self.inner.iter()).finish() } } // FORK NOTE: Removed Placer impl impl<'a, K, V> Entry<'a, K, V> { - /// Ensures a value is in the entry by inserting the default if empty, and returns + /// 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 @@ -1792,7 +1819,7 @@ impl<'a, K, V> Entry<'a, K, V> { } } - /// Ensures a value is in the entry by inserting the result of the default function if empty, + /// 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 @@ -1824,7 +1851,7 @@ impl<'a, K, V> Entry<'a, K, V> { /// let mut map: HashMap<&str, u32> = HashMap::new(); /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); /// ``` - pub fn key(&self) -> &K { + pub fn key(&self) -> &K { match *self { Occupied(ref entry) => entry.key(), Vacant(ref entry) => entry.key(), @@ -1844,7 +1871,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// map.entry("poneyland").or_insert(12); /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); /// ``` - pub fn key(&self) -> &K { + pub fn key(&self) -> &K { self.elem.read().0 } @@ -1866,7 +1893,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// assert_eq!(map.contains_key("poneyland"), false); /// ``` - pub fn remove_entry(self) -> (K, V) { + pub fn remove_entry(self) -> (K, V) { let (k, v, _) = pop_internal(self.elem); (k, v) } @@ -1886,7 +1913,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// assert_eq!(o.get(), &12); /// } /// ``` - pub fn get(&self) -> &V { + pub fn get(&self) -> &V { self.elem.read().1 } @@ -1908,7 +1935,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// assert_eq!(map["poneyland"], 22); /// ``` - pub fn get_mut(&mut self) -> &mut V { + pub fn get_mut(&mut self) -> &mut V { self.elem.read_mut().1 } @@ -1931,7 +1958,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// assert_eq!(map["poneyland"], 22); /// ``` - pub fn into_mut(self) -> &'a mut V { + pub fn into_mut(self) -> &'a mut V { self.elem.into_mut_refs().1 } @@ -1952,7 +1979,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// assert_eq!(map["poneyland"], 15); /// ``` - pub fn insert(&mut self, mut value: V) -> V { + pub fn insert(&mut self, mut value: V) -> V { let old_value = self.get_mut(); mem::swap(&mut value, old_value); value @@ -1975,7 +2002,7 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> { /// /// assert_eq!(map.contains_key("poneyland"), false); /// ``` - pub fn remove(self) -> V { + pub fn remove(self) -> V { pop_internal(self.elem).1 } @@ -1999,7 +2026,7 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// let mut map: HashMap<&str, u32> = HashMap::new(); /// assert_eq!(map.entry("poneyland").key(), &"poneyland"); /// ``` - pub fn key(&self) -> &K { + pub fn key(&self) -> &K { &self.key } @@ -2017,7 +2044,7 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// v.into_key(); /// } /// ``` - pub fn into_key(self) -> K { + pub fn into_key(self) -> K { self.key } @@ -2037,7 +2064,7 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { /// } /// assert_eq!(map["poneyland"], 37); /// ``` - pub fn insert(self, value: V) -> &'a mut V { + pub fn insert(self, value: V) -> &'a mut V { let b = match self.elem { NeqElem(mut bucket, disp) => { if disp >= DISPLACEMENT_THRESHOLD { @@ -2057,8 +2084,9 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> { } impl FromIterator<(K, V)> for HashMap - where K: Eq + Hash, - S: BuildHasher + Default +where + K: Eq + Hash, + S: BuildHasher + Default, { fn from_iter>(iter: T) -> HashMap { let mut map = HashMap::with_hasher(Default::default()); @@ -2068,8 +2096,9 @@ impl FromIterator<(K, V)> for HashMap } impl Extend<(K, V)> for HashMap - where K: Eq + Hash, - S: BuildHasher +where + K: Eq + Hash, + S: BuildHasher, { fn extend>(&mut self, iter: T) { // Keys may be already present or show multiple times in the iterator. @@ -2090,9 +2119,10 @@ impl Extend<(K, V)> for HashMap } impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap - where K: Eq + Hash + Copy, - V: Copy, - S: BuildHasher +where + K: Eq + Hash + Copy, + V: Copy, + S: BuildHasher, { fn extend>(&mut self, iter: T) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); @@ -2102,16 +2132,18 @@ impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap // FORK NOTE: These can be reused pub use std::collections::hash_map::{DefaultHasher, RandomState}; - impl super::Recover for HashMap - where K: Eq + Hash + Borrow, - S: BuildHasher, - Q: Eq + Hash +where + K: Eq + Hash + Borrow, + S: BuildHasher, + Q: Eq + Hash, { type Key = K; fn get(&self, key: &Q) -> Option<&K> { - self.search(key).into_occupied_bucket().map(|bucket| bucket.into_refs().0) + self.search(key) + .into_occupied_bucket() + .map(|bucket| bucket.into_refs().0) } fn take(&mut self, key: &Q) -> Option { @@ -2119,7 +2151,9 @@ impl super::Recover for HashMap return None; } - self.search_mut(key).into_occupied_bucket().map(|bucket| pop_internal(bucket).0) + self.search_mut(key) + .into_occupied_bucket() + .map(|bucket| pop_internal(bucket).0) } fn replace(&mut self, key: K) -> Option { @@ -2129,11 +2163,11 @@ impl super::Recover for HashMap Occupied(mut occupied) => { let key = occupied.take_key().unwrap(); Some(mem::replace(occupied.elem.read_mut().0, key)) - } + }, Vacant(vacant) => { vacant.insert(()); None - } + }, } } } @@ -2170,8 +2204,9 @@ fn assert_covariance() { fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { v } - fn drain<'new>(d: Drain<'static, &'static str, &'static str>) - -> Drain<'new, &'new str, &'new str> { + fn drain<'new>( + d: Drain<'static, &'static str, &'static str>, + ) -> Drain<'new, &'new str, &'new str> { d } } @@ -2319,19 +2354,19 @@ mod test_map { DROP_VECTOR.with(|v| { assert_eq!(v.borrow()[i], 1); - assert_eq!(v.borrow()[i+100], 1); + assert_eq!(v.borrow()[i + 100], 1); }); } DROP_VECTOR.with(|v| { for i in 0..50 { assert_eq!(v.borrow()[i], 0); - assert_eq!(v.borrow()[i+100], 0); + assert_eq!(v.borrow()[i + 100], 0); } for i in 50..100 { assert_eq!(v.borrow()[i], 1); - assert_eq!(v.borrow()[i+100], 1); + assert_eq!(v.borrow()[i + 100], 1); } }); } @@ -2388,13 +2423,9 @@ mod test_map { for _ in half.by_ref() {} DROP_VECTOR.with(|v| { - let nk = (0..100) - .filter(|&i| v.borrow()[i] == 1) - .count(); + let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count(); - let nv = (0..100) - .filter(|&i| v.borrow()[i + 100] == 1) - .count(); + let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count(); assert_eq!(nk, 50); assert_eq!(nv, 50); @@ -2419,7 +2450,7 @@ mod test_map { let mut m: HashMap = HashMap::new(); match m.entry(0) { Occupied(_) => panic!(), - Vacant(_) => {} + Vacant(_) => {}, } assert!(*m.entry(0).or_insert(true)); assert_eq!(m.len(), 1); @@ -2574,7 +2605,7 @@ mod test_map { fn test_iterate() { let mut m = HashMap::with_capacity(4); for i in 0..32 { - assert!(m.insert(i, i*2).is_none()); + assert!(m.insert(i, i * 2).is_none()); } assert_eq!(m.len(), 32); @@ -2662,8 +2693,7 @@ mod test_map { let map_str = format!("{:?}", map); - assert!(map_str == "{1: 2, 3: 4}" || - map_str == "{3: 4, 1: 2}"); + assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); assert_eq!(format!("{:?}", empty), "{}"); } @@ -2876,12 +2906,11 @@ mod test_map { Occupied(mut view) => { assert_eq!(view.get(), &10); assert_eq!(view.insert(100), 10); - } + }, } assert_eq!(map.get(&1).unwrap(), &100); assert_eq!(map.len(), 6); - // Existing key (update) match map.entry(2) { Vacant(_) => unreachable!(), @@ -2889,7 +2918,7 @@ mod test_map { let v = view.get_mut(); let new_v = (*v) * 10; *v = new_v; - } + }, } assert_eq!(map.get(&2).unwrap(), &200); assert_eq!(map.len(), 6); @@ -2899,18 +2928,17 @@ mod test_map { Vacant(_) => unreachable!(), Occupied(view) => { assert_eq!(view.remove(), 30); - } + }, } assert_eq!(map.get(&3), None); assert_eq!(map.len(), 5); - // Inexistent key (insert) match map.entry(10) { Occupied(_) => unreachable!(), Vacant(view) => { assert_eq!(*view.insert(1000), 1000); - } + }, } assert_eq!(map.get(&10).unwrap(), &1000); assert_eq!(map.len(), 6); @@ -2919,11 +2947,10 @@ mod test_map { #[test] fn test_entry_take_doesnt_corrupt() { #![allow(deprecated)] //rand - // Test for #19292 + // Test for #19292 fn check(m: &HashMap) { for k in m.keys() { - assert!(m.contains_key(k), - "{} is in keys() but not in the map?", k); + assert!(m.contains_key(k), "{} is in keys() but not in the map?", k); } } @@ -2939,11 +2966,11 @@ mod test_map { for i in 0..1000 { let x = rng.gen_range(-10, 10); match m.entry(x) { - Vacant(_) => {} + Vacant(_) => {}, Occupied(e) => { println!("{}: remove {}", i, x); e.remove(); - } + }, } check(&m); @@ -3021,7 +3048,7 @@ mod test_map { Vacant(e) => { assert_eq!(key, *e.key()); e.insert(value.clone()); - } + }, } assert_eq!(a.len(), 1); assert_eq!(a[key], value); @@ -3029,7 +3056,7 @@ mod test_map { #[test] fn test_retain() { - let mut map: HashMap = (0..100).map(|x|(x, x*10)).collect(); + let mut map: HashMap = (0..100).map(|x| (x, x * 10)).collect(); map.retain(|&k, _| k % 2 == 0); assert_eq!(map.len(), 50); diff --git a/components/hashglobe/src/hash_set.rs b/components/hashglobe/src/hash_set.rs index 2139b58a6012..34e657e44fcc 100644 --- a/components/hashglobe/src/hash_set.rs +++ b/components/hashglobe/src/hash_set.rs @@ -122,8 +122,9 @@ pub struct HashSet { } impl HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { /// Creates a new empty hash set which will use the given hasher to hash /// keys. @@ -147,7 +148,9 @@ impl HashSet /// ``` #[inline] pub fn with_hasher(hasher: S) -> HashSet { - HashSet { map: HashMap::with_hasher(hasher) } + HashSet { + map: HashMap::with_hasher(hasher), + } } /// Creates an empty `HashSet` with with the specified capacity, using @@ -173,7 +176,9 @@ impl HashSet /// ``` #[inline] pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet { - HashSet { map: HashMap::with_capacity_and_hasher(capacity, hasher) } + HashSet { + map: HashMap::with_capacity_and_hasher(capacity, hasher), + } } /// Returns a reference to the set's [`BuildHasher`]. @@ -265,7 +270,9 @@ impl HashSet /// } /// ``` pub fn iter(&self) -> Iter { - Iter { iter: self.map.keys() } + Iter { + iter: self.map.keys(), + } } /// Visits the values representing the difference, @@ -319,10 +326,13 @@ impl HashSet /// assert_eq!(diff1, diff2); /// assert_eq!(diff1, [1, 4].iter().collect()); /// ``` - pub fn symmetric_difference<'a>(&'a self, - other: &'a HashSet) - -> SymmetricDifference<'a, T, S> { - SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) } + pub fn symmetric_difference<'a>( + &'a self, + other: &'a HashSet, + ) -> SymmetricDifference<'a, T, S> { + SymmetricDifference { + iter: self.difference(other).chain(other.difference(self)), + } } /// Visits the values representing the intersection, @@ -369,7 +379,9 @@ impl HashSet /// assert_eq!(union, [1, 2, 3, 4].iter().collect()); /// ``` pub fn union<'a>(&'a self, other: &'a HashSet) -> Union<'a, T, S> { - Union { iter: self.iter().chain(other.difference(self)) } + Union { + iter: self.iter().chain(other.difference(self)), + } } /// Returns the number of elements in the set. @@ -423,7 +435,9 @@ impl HashSet /// ``` #[inline] pub fn drain(&mut self) -> Drain { - Drain { iter: self.map.drain() } + Drain { + iter: self.map.drain(), + } } /// Clears the set, removing all values. @@ -438,7 +452,10 @@ impl HashSet /// v.clear(); /// assert!(v.is_empty()); /// ``` - pub fn clear(&mut self) where T: 'static { + pub fn clear(&mut self) + where + T: 'static, + { self.map.clear() } @@ -461,8 +478,9 @@ impl HashSet /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html pub fn contains(&self, value: &Q) -> bool - where T: Borrow, - Q: Hash + Eq + where + T: Borrow, + Q: Hash + Eq, { self.map.contains_key(value) } @@ -476,8 +494,9 @@ impl HashSet /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html pub fn get(&self, value: &Q) -> Option<&T> - where T: Borrow, - Q: Hash + Eq + where + T: Borrow, + Q: Hash + Eq, { Recover::get(&self.map, value) } @@ -598,8 +617,9 @@ impl HashSet /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html pub fn remove(&mut self, value: &Q) -> bool - where T: Borrow, - Q: Hash + Eq + where + T: Borrow, + Q: Hash + Eq, { self.map.remove(value).is_some() } @@ -613,8 +633,9 @@ impl HashSet /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html pub fn take(&mut self, value: &Q) -> Option - where T: Borrow, - Q: Hash + Eq + where + T: Borrow, + Q: Hash + Eq, { Recover::take(&mut self.map, value) } @@ -634,15 +655,17 @@ impl HashSet /// assert_eq!(set.len(), 3); /// ``` pub fn retain(&mut self, mut f: F) - where F: FnMut(&T) -> bool + where + F: FnMut(&T) -> bool, { self.map.retain(|k, _| f(k)); } } impl PartialEq for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { fn eq(&self, other: &HashSet) -> bool { if self.len() != other.len() { @@ -654,14 +677,16 @@ impl PartialEq for HashSet } impl Eq for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { } impl fmt::Debug for HashSet - where T: Eq + Hash + fmt::Debug, - S: BuildHasher +where + T: Eq + Hash + fmt::Debug, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_set().entries(self.iter()).finish() @@ -669,8 +694,9 @@ impl fmt::Debug for HashSet } impl FromIterator for HashSet - where T: Eq + Hash, - S: BuildHasher + Default +where + T: Eq + Hash, + S: BuildHasher + Default, { fn from_iter>(iter: I) -> HashSet { let mut set = HashSet::with_hasher(Default::default()); @@ -680,8 +706,9 @@ impl FromIterator for HashSet } impl Extend for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { fn extend>(&mut self, iter: I) { self.map.extend(iter.into_iter().map(|k| (k, ()))); @@ -689,8 +716,9 @@ impl Extend for HashSet } impl<'a, T, S> Extend<&'a T> for HashSet - where T: 'a + Eq + Hash + Copy, - S: BuildHasher +where + T: 'a + Eq + Hash + Copy, + S: BuildHasher, { fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); @@ -698,18 +726,22 @@ impl<'a, T, S> Extend<&'a T> for HashSet } impl Default for HashSet - where T: Eq + Hash, - S: BuildHasher + Default +where + T: Eq + Hash, + S: BuildHasher + Default, { /// Creates an empty `HashSet` with the `Default` value for the hasher. fn default() -> HashSet { - HashSet { map: HashMap::default() } + HashSet { + map: HashMap::default(), + } } } impl<'a, 'b, T, S> BitOr<&'b HashSet> for &'a HashSet - where T: Eq + Hash + Clone, - S: BuildHasher + Default +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, { type Output = HashSet; @@ -739,8 +771,9 @@ impl<'a, 'b, T, S> BitOr<&'b HashSet> for &'a HashSet } impl<'a, 'b, T, S> BitAnd<&'b HashSet> for &'a HashSet - where T: Eq + Hash + Clone, - S: BuildHasher + Default +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, { type Output = HashSet; @@ -770,8 +803,9 @@ impl<'a, 'b, T, S> BitAnd<&'b HashSet> for &'a HashSet } impl<'a, 'b, T, S> BitXor<&'b HashSet> for &'a HashSet - where T: Eq + Hash + Clone, - S: BuildHasher + Default +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, { type Output = HashSet; @@ -801,8 +835,9 @@ impl<'a, 'b, T, S> BitXor<&'b HashSet> for &'a HashSet } impl<'a, 'b, T, S> Sub<&'b HashSet> for &'a HashSet - where T: Eq + Hash + Clone, - S: BuildHasher + Default +where + T: Eq + Hash + Clone, + S: BuildHasher + Default, { type Output = HashSet; @@ -915,8 +950,9 @@ pub struct Union<'a, T: 'a, S: 'a> { } impl<'a, T, S> IntoIterator for &'a HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; type IntoIter = Iter<'a, T>; @@ -927,8 +963,9 @@ impl<'a, T, S> IntoIterator for &'a HashSet } impl IntoIterator for HashSet - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = T; type IntoIter = IntoIter; @@ -954,13 +991,17 @@ impl IntoIterator for HashSet /// } /// ``` fn into_iter(self) -> IntoIter { - IntoIter { iter: self.map.into_iter() } + IntoIter { + iter: self.map.into_iter(), + } } } impl<'a, K> Clone for Iter<'a, K> { fn clone(&self) -> Iter<'a, K> { - Iter { iter: self.iter.clone() } + Iter { + iter: self.iter.clone(), + } } } impl<'a, K> Iterator for Iter<'a, K> { @@ -1003,10 +1044,7 @@ impl ExactSizeIterator for IntoIter { impl fmt::Debug for IntoIter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let entries_iter = self.iter - .inner - .iter() - .map(|(k, _)| k); + let entries_iter = self.iter.inner.iter().map(|(k, _)| k); f.debug_list().entries(entries_iter).finish() } } @@ -1029,23 +1067,24 @@ impl<'a, K> ExactSizeIterator for Drain<'a, K> { impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let entries_iter = self.iter - .inner - .iter() - .map(|(k, _)| k); + let entries_iter = self.iter.inner.iter().map(|(k, _)| k); f.debug_list().entries(entries_iter).finish() } } impl<'a, T, S> Clone for Intersection<'a, T, S> { fn clone(&self) -> Intersection<'a, T, S> { - Intersection { iter: self.iter.clone(), ..*self } + Intersection { + iter: self.iter.clone(), + ..*self + } } } impl<'a, T, S> Iterator for Intersection<'a, T, S> - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; @@ -1065,8 +1104,9 @@ impl<'a, T, S> Iterator for Intersection<'a, T, S> } impl<'a, T, S> fmt::Debug for Intersection<'a, T, S> - where T: fmt::Debug + Eq + Hash, - S: BuildHasher +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.clone()).finish() @@ -1075,13 +1115,17 @@ impl<'a, T, S> fmt::Debug for Intersection<'a, T, S> impl<'a, T, S> Clone for Difference<'a, T, S> { fn clone(&self) -> Difference<'a, T, S> { - Difference { iter: self.iter.clone(), ..*self } + Difference { + iter: self.iter.clone(), + ..*self + } } } impl<'a, T, S> Iterator for Difference<'a, T, S> - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; @@ -1101,8 +1145,9 @@ impl<'a, T, S> Iterator for Difference<'a, T, S> } impl<'a, T, S> fmt::Debug for Difference<'a, T, S> - where T: fmt::Debug + Eq + Hash, - S: BuildHasher +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.clone()).finish() @@ -1111,13 +1156,16 @@ impl<'a, T, S> fmt::Debug for Difference<'a, T, S> impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> { fn clone(&self) -> SymmetricDifference<'a, T, S> { - SymmetricDifference { iter: self.iter.clone() } + SymmetricDifference { + iter: self.iter.clone(), + } } } impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; @@ -1130,8 +1178,9 @@ impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S> } impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S> - where T: fmt::Debug + Eq + Hash, - S: BuildHasher +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.clone()).finish() @@ -1140,13 +1189,16 @@ impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S> impl<'a, T, S> Clone for Union<'a, T, S> { fn clone(&self) -> Union<'a, T, S> { - Union { iter: self.iter.clone() } + Union { + iter: self.iter.clone(), + } } } impl<'a, T, S> fmt::Debug for Union<'a, T, S> - where T: fmt::Debug + Eq + Hash, - S: BuildHasher +where + T: fmt::Debug + Eq + Hash, + S: BuildHasher, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.clone()).finish() @@ -1154,8 +1206,9 @@ impl<'a, T, S> fmt::Debug for Union<'a, T, S> } impl<'a, T, S> Iterator for Union<'a, T, S> - where T: Eq + Hash, - S: BuildHasher +where + T: Eq + Hash, + S: BuildHasher, { type Item = &'a T; @@ -1178,20 +1231,24 @@ fn assert_covariance() { fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> { v } - fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>) - -> Difference<'a, &'new str, RandomState> { + fn difference<'a, 'new>( + v: Difference<'a, &'static str, RandomState>, + ) -> Difference<'a, &'new str, RandomState> { v } - fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>) - -> SymmetricDifference<'a, &'new str, RandomState> { + fn symmetric_difference<'a, 'new>( + v: SymmetricDifference<'a, &'static str, RandomState>, + ) -> SymmetricDifference<'a, &'new str, RandomState> { v } - fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>) - -> Intersection<'a, &'new str, RandomState> { + fn intersection<'a, 'new>( + v: Intersection<'a, &'static str, RandomState>, + ) -> Intersection<'a, &'new str, RandomState> { v } - fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>) - -> Union<'a, &'new str, RandomState> { + fn union<'a, 'new>( + v: Union<'a, &'static str, RandomState>, + ) -> Union<'a, &'new str, RandomState> { v } fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> { diff --git a/components/hashglobe/src/lib.rs b/components/hashglobe/src/lib.rs index 49038a51859d..cf6e9710f5fe 100644 --- a/components/hashglobe/src/lib.rs +++ b/components/hashglobe/src/lib.rs @@ -44,7 +44,10 @@ pub struct FailedAllocationError { impl FailedAllocationError { #[inline] pub fn new(reason: &'static str) -> Self { - Self { reason, allocation_info: None } + Self { + reason, + allocation_info: None, + } } } @@ -57,9 +60,11 @@ impl error::Error for FailedAllocationError { impl fmt::Display for FailedAllocationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.allocation_info { - Some(ref info) => { - write!(f, "{}, allocation: (size: {}, alignment: {})", self.reason, info.size, info.alignment) - }, + Some(ref info) => write!( + f, + "{}, allocation: (size: {}, alignment: {})", + self.reason, info.size, info.alignment + ), None => self.reason.fmt(f), } } diff --git a/components/hashglobe/src/shim.rs b/components/hashglobe/src/shim.rs index 146ff851a0e5..855dbdcfa155 100644 --- a/components/hashglobe/src/shim.rs +++ b/components/hashglobe/src/shim.rs @@ -29,11 +29,11 @@ impl Unique { } } -unsafe impl Send for Unique { } +unsafe impl Send for Unique {} -unsafe impl Sync for Unique { } +unsafe impl Sync for Unique {} -pub struct Shared { +pub struct Shared { ptr: NonZeroPtr, _marker: PhantomData, // force it to be !Send/!Sync diff --git a/components/hashglobe/src/table.rs b/components/hashglobe/src/table.rs index bd801b43544f..0b8b49001e2d 100644 --- a/components/hashglobe/src/table.rs +++ b/components/hashglobe/src/table.rs @@ -203,7 +203,9 @@ impl SafeHash { // // Truncate hash to fit in `HashUint`. let hash_bits = size_of::() * 8; - SafeHash { hash: (1 << (hash_bits - 1)) | (hash as HashUint) } + SafeHash { + hash: (1 << (hash_bits - 1)) | (hash as HashUint), + } } } @@ -211,8 +213,9 @@ impl SafeHash { /// This function wraps up `hash_keyed` to be the only way outside this /// module to generate a SafeHash. pub fn make_hash(hash_state: &S, t: &T) -> SafeHash - where T: Hash, - S: BuildHasher +where + T: Hash, + S: BuildHasher, { let mut state = hash_state.build_hasher(); t.hash(&mut state); @@ -294,7 +297,8 @@ impl Bucket { } impl Deref for FullBucket - where M: Deref> +where + M: Deref>, { type Target = RawTable; fn deref(&self) -> &RawTable { @@ -308,7 +312,6 @@ pub trait Put { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable; } - impl<'t, K, V> Put for &'t mut RawTable { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable { *self @@ -316,7 +319,8 @@ impl<'t, K, V> Put for &'t mut RawTable { } impl Put for Bucket - where M: Put +where + M: Put, { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable { self.table.borrow_table_mut() @@ -324,7 +328,8 @@ impl Put for Bucket } impl Put for FullBucket - where M: Put +where + M: Put, { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable { self.table.borrow_table_mut() @@ -336,20 +341,17 @@ impl>> Bucket { Bucket::at_index(table, hash.inspect() as usize) } - pub fn new_from(r: RawBucket, t: M) - -> Bucket - { - Bucket { - raw: r, - table: t, - } + pub fn new_from(r: RawBucket, t: M) -> Bucket { + Bucket { raw: r, table: t } } pub fn at_index(table: M, ib_index: usize) -> Bucket { // if capacity is 0, then the RawBucket will be populated with bogus pointers. // This is an uncommon case though, so avoid it in release builds. - debug_assert!(table.capacity() > 0, - "Table should have capacity at this point"); + debug_assert!( + table.capacity() > 0, + "Table should have capacity at this point" + ); let ib_index = ib_index & table.capacity_mask; Bucket { raw: table.raw_bucket_at(ib_index), @@ -387,11 +389,11 @@ impl>> Bucket { } // Leaving this bucket in the last cluster for later. full.into_bucket() - } + }, Empty(b) => { // Encountered a hole between clusters. b.into_bucket() - } + }, }; bucket.next(); } @@ -404,18 +406,14 @@ impl>> Bucket { /// this module. pub fn peek(self) -> BucketState { match unsafe { *self.raw.hash() } { - EMPTY_BUCKET => { - Empty(EmptyBucket { - raw: self.raw, - table: self.table, - }) - } - _ => { - Full(FullBucket { - raw: self.raw, - table: self.table, - }) - } + EMPTY_BUCKET => Empty(EmptyBucket { + raw: self.raw, + table: self.table, + }), + _ => Full(FullBucket { + raw: self.raw, + table: self.table, + }), } } @@ -453,19 +451,15 @@ impl>> EmptyBucket { }; match self.next().peek() { - Full(bucket) => { - Ok(GapThenFull { - gap, - full: bucket, - }) - } + Full(bucket) => Ok(GapThenFull { gap, full: bucket }), Empty(e) => Err(e.into_bucket()), } } } impl EmptyBucket - where M: Put +where + M: Put, { /// Puts given key and value pair, along with the key's hash, /// into this bucket in the hashtable. Note how `self` is 'moved' into @@ -528,7 +522,11 @@ impl>> FullBucket { #[inline] pub fn hash(&self) -> SafeHash { - unsafe { SafeHash { hash: *self.raw.hash() } } + unsafe { + SafeHash { + hash: *self.raw.hash(), + } + } } /// Gets references to the key and value at a given index. @@ -554,12 +552,14 @@ impl<'t, K, V> FullBucket> { unsafe { *self.raw.hash() = EMPTY_BUCKET; let (k, v) = ptr::read(self.raw.pair()); - (EmptyBucket { - raw: self.raw, - table: self.table, - }, - k, - v) + ( + EmptyBucket { + raw: self.raw, + table: self.table, + }, + k, + v, + ) } } } @@ -567,7 +567,8 @@ impl<'t, K, V> FullBucket> { // This use of `Put` is misleading and restrictive, but safe and sufficient for our use cases // where `M` is a full bucket or table reference type with mutable access to the table. impl FullBucket - where M: Put +where + M: Put, { pub fn replace(&mut self, h: SafeHash, k: K, v: V) -> (SafeHash, K, V) { unsafe { @@ -580,7 +581,8 @@ impl FullBucket } impl FullBucket - where M: Deref> + DerefMut +where + M: Deref> + DerefMut, { /// Gets mutable references to the key and value at a given index. pub fn read_mut(&mut self) -> (&mut K, &mut V) { @@ -592,7 +594,8 @@ impl FullBucket } impl<'t, K, V, M> FullBucket - where M: Deref> + 't +where + M: Deref> + 't, { /// Exchange a bucket state for immutable references into the table. /// Because the underlying reference to the table is also consumed, @@ -608,7 +611,8 @@ impl<'t, K, V, M> FullBucket } impl<'t, K, V, M> FullBucket - where M: Deref> + DerefMut + 't +where + M: Deref> + DerefMut + 't, { /// This works similarly to `into_refs`, exchanging a bucket state /// for mutable references into the table. @@ -621,7 +625,8 @@ impl<'t, K, V, M> FullBucket } impl GapThenFull - where M: Deref> +where + M: Deref>, { #[inline] pub fn full(&self) -> &FullBucket { @@ -649,13 +654,12 @@ impl GapThenFull self.full = bucket; Ok(self) - } + }, Empty(b) => Err(b.into_bucket()), } } } - /// Rounds up to a multiple of a power of two. Returns the closest multiple /// of `target_alignment` that is higher or equal to `unrounded`. /// @@ -681,10 +685,11 @@ fn test_rounding() { // Returns a tuple of (pairs_offset, end_of_pairs_offset), // from the start of a mallocated array. #[inline] -fn calculate_offsets(hashes_size: usize, - pairs_size: usize, - pairs_align: usize) - -> (usize, usize, bool) { +fn calculate_offsets( + hashes_size: usize, + pairs_size: usize, + pairs_align: usize, +) -> (usize, usize, bool) { let pairs_offset = round_up_to_next(hashes_size, pairs_align); let (end_of_pairs, oflo) = pairs_offset.overflowing_add(pairs_size); @@ -693,11 +698,12 @@ fn calculate_offsets(hashes_size: usize, // Returns a tuple of (minimum required malloc alignment, hash_offset, // array_size), from the start of a mallocated array. -fn calculate_allocation(hash_size: usize, - hash_align: usize, - pairs_size: usize, - pairs_align: usize) - -> (usize, usize, usize, bool) { +fn calculate_allocation( + hash_size: usize, + hash_align: usize, + pairs_size: usize, + pairs_align: usize, +) -> (usize, usize, usize, bool) { let hash_offset = 0; let (_, end_of_pairs, oflo) = calculate_offsets(hash_size, pairs_size, pairs_align); @@ -728,7 +734,9 @@ impl RawTable { /// Does not initialize the buckets. The caller should ensure they, /// at the very least, set every hash to EMPTY_BUCKET. - unsafe fn try_new_uninitialized(capacity: usize) -> Result, FailedAllocationError> { + unsafe fn try_new_uninitialized( + capacity: usize, + ) -> Result, FailedAllocationError> { if capacity == 0 { return Ok(RawTable { size: 0, @@ -751,29 +759,38 @@ impl RawTable { // This is great in theory, but in practice getting the alignment // right is a little subtle. Therefore, calculating offsets has been // factored out into a different function. - let (alignment, hash_offset, size, oflo) = calculate_allocation(hashes_size, - align_of::(), - pairs_size, - align_of::<(K, V)>()); + let (alignment, hash_offset, size, oflo) = calculate_allocation( + hashes_size, + align_of::(), + pairs_size, + align_of::<(K, V)>(), + ); if oflo { - return Err(FailedAllocationError::new("capacity overflow when allocating RawTable" )); + return Err(FailedAllocationError::new( + "capacity overflow when allocating RawTable", + )); } // One check for overflow that covers calculation and rounding of size. - let size_of_bucket = size_of::().checked_add(size_of::<(K, V)>()).unwrap(); + let size_of_bucket = size_of::() + .checked_add(size_of::<(K, V)>()) + .unwrap(); let cap_bytes = capacity.checked_mul(size_of_bucket); if let Some(cap_bytes) = cap_bytes { if size < cap_bytes { - return Err(FailedAllocationError::new("capacity overflow when allocating RawTable")); + return Err(FailedAllocationError::new( + "capacity overflow when allocating RawTable", + )); } } else { - return Err(FailedAllocationError::new("capacity overflow when allocating RawTable")); + return Err(FailedAllocationError::new( + "capacity overflow when allocating RawTable", + )); } - // FORK NOTE: Uses alloc shim instead of Heap.alloc let buffer = alloc(size, alignment); @@ -857,7 +874,9 @@ impl RawTable { } pub fn into_iter(self) -> IntoIter { - let RawBuckets { raw, elems_left, .. } = self.raw_buckets(); + let RawBuckets { + raw, elems_left, .. + } = self.raw_buckets(); // Replace the marker regardless of lifetime bounds on parameters. IntoIter { iter: RawBuckets { @@ -870,7 +889,9 @@ impl RawTable { } pub fn drain(&mut self) -> Drain { - let RawBuckets { raw, elems_left, .. } = self.raw_buckets(); + let RawBuckets { + raw, elems_left, .. + } = self.raw_buckets(); // Replace the marker regardless of lifetime bounds on parameters. Drain { iter: RawBuckets { @@ -937,7 +958,6 @@ impl<'a, K, V> Clone for RawBuckets<'a, K, V> { } } - impl<'a, K, V> Iterator for RawBuckets<'a, K, V> { type Item = RawBucket; @@ -1112,12 +1132,16 @@ impl<'a, K, V> Iterator for Drain<'a, K, V> { #[inline] fn next(&mut self) -> Option<(SafeHash, K, V)> { - self.iter.next().map(|raw| { - unsafe { - self.table.as_mut().size -= 1; - let (k, v) = ptr::read(raw.pair()); - (SafeHash { hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET) }, k, v) - } + self.iter.next().map(|raw| unsafe { + self.table.as_mut().size -= 1; + let (k, v) = ptr::read(raw.pair()); + ( + SafeHash { + hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET), + }, + k, + v, + ) }) } @@ -1181,17 +1205,19 @@ impl Drop for RawTable { unsafe { // FORK NOTE: Can't needs_drop on stable // if needs_drop::<(K, V)>() { - // avoid linear runtime for types that don't need drop - self.rev_drop_buckets(); + // avoid linear runtime for types that don't need drop + self.rev_drop_buckets(); // } } let hashes_size = self.capacity() * size_of::(); let pairs_size = self.capacity() * size_of::<(K, V)>(); - let (align, _, _, oflo) = calculate_allocation(hashes_size, - align_of::(), - pairs_size, - align_of::<(K, V)>()); + let (align, _, _, oflo) = calculate_allocation( + hashes_size, + align_of::(), + pairs_size, + align_of::<(K, V)>(), + ); debug_assert!(!oflo, "should be impossible");