Format hashglobe #21373

This commit is contained in:
kingdido999 2018-09-09 10:14:36 +08:00
parent 2c9e32a09e
commit 951bda3600
7 changed files with 552 additions and 434 deletions

View file

@ -1,25 +1,26 @@
// FORK NOTE: Copied from liballoc_system, removed unnecessary APIs, // FORK NOTE: Copied from liballoc_system, removed unnecessary APIs,
// APIs take size/align directly instead of Layout // APIs take size/align directly instead of Layout
// The minimum alignment guaranteed by the architecture. This value is used to // 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 // 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. // constant at the call site and the branch will be optimized out.
#[cfg(all(any(target_arch = "x86", #[cfg(all(any(
target_arch = "x86",
target_arch = "arm", target_arch = "arm",
target_arch = "mips", target_arch = "mips",
target_arch = "powerpc", target_arch = "powerpc",
target_arch = "powerpc64", target_arch = "powerpc64",
target_arch = "asmjs", target_arch = "asmjs",
target_arch = "wasm32")))] target_arch = "wasm32"
)))]
const MIN_ALIGN: usize = 8; const MIN_ALIGN: usize = 8;
#[cfg(all(any(target_arch = "x86_64", #[cfg(all(any(
target_arch = "x86_64",
target_arch = "aarch64", target_arch = "aarch64",
target_arch = "mips64", target_arch = "mips64",
target_arch = "s390x", target_arch = "s390x",
target_arch = "sparc64")))] target_arch = "sparc64"
)))]
const MIN_ALIGN: usize = 16; const MIN_ALIGN: usize = 16;
pub use self::platform::{alloc, dealloc, realloc}; pub use self::platform::{alloc, dealloc, realloc};
@ -100,7 +101,6 @@ mod platform {
type DWORD = u32; type DWORD = u32;
type BOOL = i32; type BOOL = i32;
extern "system" { extern "system" {
fn GetProcessHeap() -> HANDLE; fn GetProcessHeap() -> HANDLE;
fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID; fn HeapAlloc(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T) -> LPVOID;
@ -123,8 +123,7 @@ mod platform {
} }
#[inline] #[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 { if align <= MIN_ALIGN {
HeapAlloc(GetProcessHeap(), flags, size) HeapAlloc(GetProcessHeap(), flags, size)
} else { } else {
@ -147,21 +146,16 @@ mod platform {
pub unsafe fn dealloc(ptr: *mut u8, align: usize) { pub unsafe fn dealloc(ptr: *mut u8, align: usize) {
if align <= MIN_ALIGN { if align <= MIN_ALIGN {
let err = HeapFree(GetProcessHeap(), 0, ptr as LPVOID); let err = HeapFree(GetProcessHeap(), 0, ptr as LPVOID);
debug_assert!(err != 0, "Failed to free heap memory: {}", debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError());
GetLastError());
} else { } else {
let header = get_header(ptr); let header = get_header(ptr);
let err = HeapFree(GetProcessHeap(), 0, header.0 as LPVOID); let err = HeapFree(GetProcessHeap(), 0, header.0 as LPVOID);
debug_assert!(err != 0, "Failed to free heap memory: {}", debug_assert!(err != 0, "Failed to free heap memory: {}", GetLastError());
GetLastError());
} }
} }
#[inline] #[inline]
pub unsafe fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8 { pub unsafe fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8 {
HeapReAlloc(GetProcessHeap(), HeapReAlloc(GetProcessHeap(), 0, ptr as LPVOID, new_size) as *mut u8
0,
ptr as LPVOID,
new_size) as *mut u8
} }
} }

View file

@ -26,7 +26,6 @@ pub use std::collections::hash_set::{Iter as SetIter, IntoIter as SetIntoIter};
#[derive(Clone)] #[derive(Clone)]
pub struct HashMap<K, V, S = RandomState>(StdMap<K, V, S>); pub struct HashMap<K, V, S = RandomState>(StdMap<K, V, S>);
use FailedAllocationError; use FailedAllocationError;
impl<K, V, S> Deref for HashMap<K, V, S> { impl<K, V, S> Deref for HashMap<K, V, S> {
@ -43,8 +42,9 @@ impl<K, V, S> DerefMut for HashMap<K, V, S> {
} }
impl<K, V, S> HashMap<K, V, S> impl<K, V, S> HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
#[inline] #[inline]
pub fn try_with_hasher(hash_builder: S) -> Result<HashMap<K, V, S>, FailedAllocationError> { pub fn try_with_hasher(hash_builder: S) -> Result<HashMap<K, V, S>, FailedAllocationError> {
@ -52,17 +52,20 @@ impl<K, V, S> HashMap<K, V, S>
} }
#[inline] #[inline]
pub fn try_with_capacity_and_hasher(capacity: usize, pub fn try_with_capacity_and_hasher(
hash_builder: S) capacity: usize,
-> Result<HashMap<K, V, S>, FailedAllocationError> { hash_builder: S,
Ok(HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder))) ) -> Result<HashMap<K, V, S>, FailedAllocationError> {
Ok(HashMap(StdMap::with_capacity_and_hasher(
capacity,
hash_builder,
)))
} }
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> { pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S> {
HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder)) HashMap(StdMap::with_capacity_and_hasher(capacity, hash_builder))
} }
#[inline] #[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> { pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> {
Ok(self.reserve(additional)) Ok(self.reserve(additional))
@ -85,7 +88,6 @@ impl<K, V, S> HashMap<K, V, S>
#[derive(Clone)] #[derive(Clone)]
pub struct HashSet<T, S = RandomState>(StdSet<T, S>); pub struct HashSet<T, S = RandomState>(StdSet<T, S>);
impl<T, S> Deref for HashSet<T, S> { impl<T, S> Deref for HashSet<T, S> {
type Target = StdSet<T, S>; type Target = StdSet<T, S>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@ -111,17 +113,16 @@ impl<T: Hash + Eq> HashSet<T, RandomState> {
} }
} }
impl<T, S> HashSet<T, S> impl<T, S> HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
#[inline] #[inline]
pub fn with_hasher(hasher: S) -> HashSet<T, S> { pub fn with_hasher(hasher: S) -> HashSet<T, S> {
HashSet(StdSet::with_hasher(hasher)) HashSet(StdSet::with_hasher(hasher))
} }
#[inline] #[inline]
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> { pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
HashSet(StdSet::with_capacity_and_hasher(capacity, hasher)) HashSet(StdSet::with_capacity_and_hasher(capacity, hasher))
@ -153,18 +154,21 @@ impl<K: Hash + Eq, V, S: BuildHasher + Default> Default for HashMap<K, V, S> {
} }
impl<K, V, S> fmt::Debug for HashMap<K, V, S> impl<K, V, S> fmt::Debug for HashMap<K, V, S>
where K: Eq + Hash + fmt::Debug, where
K: Eq + Hash + fmt::Debug,
V: fmt::Debug, V: fmt::Debug,
S: BuildHasher { S: BuildHasher,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
} }
} }
impl<K, V, S> PartialEq for HashMap<K, V, S> impl<K, V, S> PartialEq for HashMap<K, V, S>
where K: Eq + Hash, where
K: Eq + Hash,
V: PartialEq, V: PartialEq,
S: BuildHasher S: BuildHasher,
{ {
fn eq(&self, other: &HashMap<K, V, S>) -> bool { fn eq(&self, other: &HashMap<K, V, S>) -> bool {
self.0.eq(&other.0) self.0.eq(&other.0)
@ -172,15 +176,17 @@ impl<K, V, S> PartialEq for HashMap<K, V, S>
} }
impl<K, V, S> Eq for HashMap<K, V, S> impl<K, V, S> Eq for HashMap<K, V, S>
where K: Eq + Hash, where
K: Eq + Hash,
V: Eq, V: Eq,
S: BuildHasher S: BuildHasher,
{ {
} }
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
type Item = (&'a K, &'a V); type Item = (&'a K, &'a V);
type IntoIter = MapIter<'a, K, V>; type IntoIter = MapIter<'a, K, V>;
@ -191,8 +197,9 @@ impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
} }
impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
type Item = (&'a K, &'a mut V); type Item = (&'a K, &'a mut V);
type IntoIter = MapIterMut<'a, K, V>; type IntoIter = MapIterMut<'a, K, V>;
@ -209,8 +216,9 @@ impl<T: Eq + Hash, S: BuildHasher + Default> Default for HashSet<T, S> {
} }
impl<T, S> fmt::Debug for HashSet<T, S> impl<T, S> fmt::Debug for HashSet<T, S>
where T: Eq + Hash + fmt::Debug, where
S: BuildHasher T: Eq + Hash + fmt::Debug,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f) self.0.fmt(f)
@ -218,8 +226,9 @@ impl<T, S> fmt::Debug for HashSet<T, S>
} }
impl<T, S> PartialEq for HashSet<T, S> impl<T, S> PartialEq for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
fn eq(&self, other: &HashSet<T, S>) -> bool { fn eq(&self, other: &HashSet<T, S>) -> bool {
self.0.eq(&other.0) self.0.eq(&other.0)
@ -227,14 +236,16 @@ impl<T, S> PartialEq for HashSet<T, S>
} }
impl<T, S> Eq for HashSet<T, S> impl<T, S> Eq for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
} }
impl<'a, T, S> IntoIterator for &'a HashSet<T, S> impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; type Item = &'a T;
type IntoIter = SetIter<'a, T>; type IntoIter = SetIter<'a, T>;
@ -245,16 +256,14 @@ impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
} }
impl<T, S> IntoIterator for HashSet<T, S> impl<T, S> IntoIterator for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = T; type Item = T;
type IntoIter = SetIntoIter<T>; type IntoIter = SetIntoIter<T>;
fn into_iter(self) -> SetIntoIter<T> { fn into_iter(self) -> SetIntoIter<T> {
self.0.into_iter() self.0.into_iter()
} }
} }

View file

@ -50,7 +50,9 @@ impl DefaultResizePolicy {
// 3. Ensure it is at least the minimum size. // 3. Ensure it is at least the minimum size.
let mut raw_cap = len * 11 / 10; let mut raw_cap = len * 11 / 10;
assert!(raw_cap >= len, "raw_cap overflow"); 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 = max(MIN_NONZERO_RAW_CAPACITY, raw_cap);
raw_cap raw_cap
} }
@ -398,8 +400,9 @@ pub struct HashMap<K, V, S = RandomState> {
/// Search for a pre-hashed key. /// Search for a pre-hashed key.
#[inline] #[inline]
fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M> fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> InternalEntry<K, V, M>
where M: Deref<Target = RawTable<K, V>>, where
F: FnMut(&K) -> bool M: Deref<Target = RawTable<K, V>>,
F: FnMut(&K) -> bool,
{ {
// This is the only function where capacity can be zero. To avoid // This is the only function where capacity can be zero. To avoid
// undefined behavior when Bucket::new gets the raw bucket in this // undefined behavior when Bucket::new gets the raw bucket in this
@ -420,7 +423,7 @@ fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> Inter
hash, hash,
elem: NoElem(bucket, displacement), elem: NoElem(bucket, displacement),
}; };
} },
Full(bucket) => bucket, Full(bucket) => bucket,
}; };
@ -449,9 +452,7 @@ fn search_hashed<K, V, M, F>(table: M, hash: SafeHash, mut is_match: F) -> Inter
} }
} }
fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>) -> (K, V, &mut RawTable<K, V>) {
-> (K, V, &mut RawTable<K, V>)
{
let (empty, retkey, retval) = starting_bucket.take(); let (empty, retkey, retval) = starting_bucket.take();
let mut gap = match empty.gap_peek() { let mut gap = match empty.gap_peek() {
Ok(b) => b, Ok(b) => b,
@ -475,12 +476,13 @@ fn pop_internal<K, V>(starting_bucket: FullBucketMut<K, V>)
/// also pass that bucket's displacement so we don't have to recalculate it. /// 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. /// `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>, fn robin_hood<'a, K: 'a, V: 'a>(
bucket: FullBucketMut<'a, K, V>,
mut displacement: usize, mut displacement: usize,
mut hash: SafeHash, mut hash: SafeHash,
mut key: K, mut key: K,
mut val: V) mut val: V,
-> FullBucketMut<'a, K, V> { ) -> FullBucketMut<'a, K, V> {
let size = bucket.table().size(); let size = bucket.table().size();
let raw_capacity = bucket.table().capacity(); let raw_capacity = bucket.table().capacity();
// There can be at most `size - dib` buckets to displace, because // 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" // FullBucketMut, into just one FullBucketMut. The "table"
// refers to the inner FullBucketMut in this context. // refers to the inner FullBucketMut in this context.
return bucket.into_table(); return bucket.into_table();
} },
Full(bucket) => bucket, Full(bucket) => bucket,
}; };
@ -531,11 +533,13 @@ fn robin_hood<'a, K: 'a, V: 'a>(bucket: FullBucketMut<'a, K, V>,
} }
impl<K, V, S> HashMap<K, V, S> impl<K, V, S> HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash fn make_hash<X: ?Sized>(&self, x: &X) -> SafeHash
where X: Hash where
X: Hash,
{ {
table::make_hash(&self.hash_builder, x) table::make_hash(&self.hash_builder, x)
} }
@ -545,8 +549,9 @@ impl<K, V, S> HashMap<K, V, S>
/// search_hashed. /// search_hashed.
#[inline] #[inline]
fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>> fn search<'a, Q: ?Sized>(&'a self, q: &Q) -> InternalEntry<K, V, &'a RawTable<K, V>>
where K: Borrow<Q>, where
Q: Eq + Hash K: Borrow<Q>,
Q: Eq + Hash,
{ {
let hash = self.make_hash(q); let hash = self.make_hash(q);
search_hashed(&self.table, hash, |k| q.eq(k.borrow())) search_hashed(&self.table, hash, |k| q.eq(k.borrow()))
@ -554,8 +559,9 @@ impl<K, V, S> HashMap<K, V, S>
#[inline] #[inline]
fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>> fn search_mut<'a, Q: ?Sized>(&'a mut self, q: &Q) -> InternalEntry<K, V, &'a mut RawTable<K, V>>
where K: Borrow<Q>, where
Q: Eq + Hash K: Borrow<Q>,
Q: Eq + Hash,
{ {
let hash = self.make_hash(q); let hash = self.make_hash(q);
search_hashed(&mut self.table, hash, |k| q.eq(k.borrow())) search_hashed(&mut self.table, hash, |k| q.eq(k.borrow()))
@ -574,7 +580,7 @@ impl<K, V, S> HashMap<K, V, S>
Empty(empty) => { Empty(empty) => {
empty.put(hash, k, v); empty.put(hash, k, v);
return; return;
} },
Full(b) => b.into_bucket(), Full(b) => b.into_bucket(),
}; };
buckets.next(); buckets.next();
@ -584,8 +590,9 @@ impl<K, V, S> HashMap<K, V, S>
} }
impl<K, V, S> HashMap<K, V, S> impl<K, V, S> HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
/// Creates an empty `HashMap` which will use the given hash builder to hash /// Creates an empty `HashMap` which will use the given hash builder to hash
/// keys. /// keys.
@ -643,7 +650,10 @@ impl<K, V, S> HashMap<K, V, S>
/// map.insert(1, 2); /// map.insert(1, 2);
/// ``` /// ```
#[inline] #[inline]
pub fn try_with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Result<HashMap<K, V, S>, FailedAllocationError> { pub fn try_with_capacity_and_hasher(
capacity: usize,
hash_builder: S,
) -> Result<HashMap<K, V, S>, FailedAllocationError> {
let resize_policy = DefaultResizePolicy::new(); let resize_policy = DefaultResizePolicy::new();
let raw_cap = resize_policy.raw_capacity(capacity); let raw_cap = resize_policy.raw_capacity(capacity);
Ok(HashMap { Ok(HashMap {
@ -708,12 +718,14 @@ impl<K, V, S> HashMap<K, V, S>
self.try_reserve(additional).unwrap(); self.try_reserve(additional).unwrap();
} }
#[inline] #[inline]
pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> { pub fn try_reserve(&mut self, additional: usize) -> Result<(), FailedAllocationError> {
let remaining = self.capacity() - self.len(); // this can't overflow let remaining = self.capacity() - self.len(); // this can't overflow
if remaining < additional { 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); let raw_cap = self.resize_policy.raw_capacity(min_cap);
self.try_resize(raw_cap)?; self.try_resize(raw_cap)?;
} else if self.table.tag() && remaining <= self.len() { } else if self.table.tag() && remaining <= self.len() {
@ -763,7 +775,7 @@ impl<K, V, S> HashMap<K, V, S>
break; break;
} }
b.into_bucket() b.into_bucket()
} },
Empty(b) => b.into_bucket(), Empty(b) => b.into_bucket(),
}; };
bucket.next(); bucket.next();
@ -822,7 +834,7 @@ impl<K, V, S> HashMap<K, V, S>
Some(Vacant(elem)) => { Some(Vacant(elem)) => {
elem.insert(v); elem.insert(v);
None None
} },
None => unreachable!(), None => unreachable!(),
} }
} }
@ -892,7 +904,9 @@ impl<K, V, S> HashMap<K, V, S>
/// } /// }
/// ``` /// ```
pub fn values_mut(&mut self) -> ValuesMut<K, V> { pub fn values_mut(&mut self) -> ValuesMut<K, V> {
ValuesMut { inner: self.iter_mut() } ValuesMut {
inner: self.iter_mut(),
}
} }
/// An iterator visiting all key-value pairs in arbitrary order. /// An iterator visiting all key-value pairs in arbitrary order.
@ -913,7 +927,9 @@ impl<K, V, S> HashMap<K, V, S>
/// } /// }
/// ``` /// ```
pub fn iter(&self) -> Iter<K, V> { pub fn iter(&self) -> Iter<K, V> {
Iter { inner: self.table.iter() } Iter {
inner: self.table.iter(),
}
} }
/// An iterator visiting all key-value pairs in arbitrary order, /// An iterator visiting all key-value pairs in arbitrary order,
@ -940,7 +956,9 @@ impl<K, V, S> HashMap<K, V, S>
/// } /// }
/// ``` /// ```
pub fn iter_mut(&mut self) -> IterMut<K, V> { pub fn iter_mut(&mut self) -> IterMut<K, V> {
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. /// Gets the given key's corresponding entry in the map for in-place manipulation.
@ -972,7 +990,8 @@ impl<K, V, S> HashMap<K, V, S>
self.try_reserve(1)?; self.try_reserve(1)?;
let hash = self.make_hash(&key); let hash = self.make_hash(&key);
Ok(search_hashed(&mut self.table, hash, |q| q.eq(&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. /// Returns the number of elements in the map.
@ -1028,8 +1047,14 @@ impl<K, V, S> HashMap<K, V, S>
/// assert!(a.is_empty()); /// assert!(a.is_empty());
/// ``` /// ```
#[inline] #[inline]
pub fn drain(&mut self) -> Drain<K, V> where K: 'static, V: 'static { pub fn drain(&mut self) -> Drain<K, V>
Drain { inner: self.table.drain() } where
K: 'static,
V: 'static,
{
Drain {
inner: self.table.drain(),
}
} }
/// Clears the map, removing all key-value pairs. Keeps the allocated memory /// Clears the map, removing all key-value pairs. Keeps the allocated memory
@ -1046,7 +1071,11 @@ impl<K, V, S> HashMap<K, V, S>
/// assert!(a.is_empty()); /// assert!(a.is_empty());
/// ``` /// ```
#[inline] #[inline]
pub fn clear(&mut self) where K: 'static, V: 'static { pub fn clear(&mut self)
where
K: 'static,
V: 'static,
{
self.drain(); self.drain();
} }
@ -1070,10 +1099,13 @@ impl<K, V, S> HashMap<K, V, S>
/// assert_eq!(map.get(&2), None); /// assert_eq!(map.get(&2), None);
/// ``` /// ```
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, where
Q: Hash + Eq K: Borrow<Q>,
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. /// Returns true if the map contains a value for the specified key.
@ -1096,8 +1128,9 @@ impl<K, V, S> HashMap<K, V, S>
/// assert_eq!(map.contains_key(&2), false); /// assert_eq!(map.contains_key(&2), false);
/// ``` /// ```
pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
where K: Borrow<Q>, where
Q: Hash + Eq K: Borrow<Q>,
Q: Hash + Eq,
{ {
self.search(k).into_occupied_bucket().is_some() self.search(k).into_occupied_bucket().is_some()
} }
@ -1124,10 +1157,13 @@ impl<K, V, S> HashMap<K, V, S>
/// assert_eq!(map[&1], "b"); /// assert_eq!(map[&1], "b");
/// ``` /// ```
pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
where K: Borrow<Q>, where
Q: Hash + Eq K: Borrow<Q>,
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. /// Inserts a key-value pair into the map.
@ -1187,14 +1223,17 @@ impl<K, V, S> HashMap<K, V, S>
/// assert_eq!(map.remove(&1), None); /// assert_eq!(map.remove(&1), None);
/// ``` /// ```
pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
where K: Borrow<Q>, where
Q: Hash + Eq K: Borrow<Q>,
Q: Hash + Eq,
{ {
if self.table.size() == 0 { if self.table.size() == 0 {
return None; 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. /// Retains only the elements specified by the predicate.
@ -1211,7 +1250,8 @@ impl<K, V, S> HashMap<K, V, S>
/// assert_eq!(map.len(), 4); /// assert_eq!(map.len(), 4);
/// ``` /// ```
pub fn retain<F>(&mut self, mut f: F) pub fn retain<F>(&mut self, mut f: F)
where F: FnMut(&K, &mut V) -> bool where
F: FnMut(&K, &mut V) -> bool,
{ {
if self.table.size() == 0 { if self.table.size() == 0 {
return; return;
@ -1236,9 +1276,7 @@ impl<K, V, S> HashMap<K, V, S>
full.into_bucket() full.into_bucket()
} }
}, },
Empty(b) => { Empty(b) => b.into_bucket(),
b.into_bucket()
}
}; };
bucket.prev(); // reverse iteration bucket.prev(); // reverse iteration
debug_assert!(elems_left == 0 || bucket.index() != start_index); debug_assert!(elems_left == 0 || bucket.index() != start_index);
@ -1247,30 +1285,34 @@ impl<K, V, S> HashMap<K, V, S>
} }
impl<K, V, S> PartialEq for HashMap<K, V, S> impl<K, V, S> PartialEq for HashMap<K, V, S>
where K: Eq + Hash, where
K: Eq + Hash,
V: PartialEq, V: PartialEq,
S: BuildHasher S: BuildHasher,
{ {
fn eq(&self, other: &HashMap<K, V, S>) -> bool { fn eq(&self, other: &HashMap<K, V, S>) -> bool {
if self.len() != other.len() { if self.len() != other.len() {
return false; 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<K, V, S> Eq for HashMap<K, V, S> impl<K, V, S> Eq for HashMap<K, V, S>
where K: Eq + Hash, where
K: Eq + Hash,
V: Eq, V: Eq,
S: BuildHasher S: BuildHasher,
{ {
} }
impl<K, V, S> Debug for HashMap<K, V, S> impl<K, V, S> Debug for HashMap<K, V, S>
where K: Eq + Hash + Debug, where
K: Eq + Hash + Debug,
V: Debug, V: Debug,
S: BuildHasher S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_map().entries(self.iter()).finish() f.debug_map().entries(self.iter()).finish()
@ -1278,8 +1320,9 @@ impl<K, V, S> Debug for HashMap<K, V, S>
} }
impl<K, V, S> Default for HashMap<K, V, S> impl<K, V, S> Default for HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher + Default K: Eq + Hash,
S: BuildHasher + Default,
{ {
/// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher. /// Creates an empty `HashMap<K, V, S>`, with the `Default` value for the hasher.
fn default() -> HashMap<K, V, S> { fn default() -> HashMap<K, V, S> {
@ -1288,9 +1331,10 @@ impl<K, V, S> Default for HashMap<K, V, S>
} }
impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S> impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S>
where K: Eq + Hash + Borrow<Q>, where
K: Eq + Hash + Borrow<Q>,
Q: Eq + Hash, Q: Eq + Hash,
S: BuildHasher S: BuildHasher,
{ {
type Output = V; type Output = V;
@ -1314,15 +1358,15 @@ pub struct Iter<'a, K: 'a, V: 'a> {
// FIXME(#19839) Remove in favor of `#[derive(Clone)]` // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Iter<'a, K, V> { impl<'a, K, V> Clone for Iter<'a, K, V> {
fn clone(&self) -> 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> { impl<'a, K: Debug, V: Debug> fmt::Debug for Iter<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.clone()).finish()
.entries(self.clone())
.finish()
} }
} }
@ -1362,15 +1406,15 @@ pub struct Keys<'a, K: 'a, V: 'a> {
// FIXME(#19839) Remove in favor of `#[derive(Clone)]` // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Keys<'a, K, V> { impl<'a, K, V> Clone for Keys<'a, K, V> {
fn clone(&self) -> 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> { impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.clone()).finish()
.entries(self.clone())
.finish()
} }
} }
@ -1388,15 +1432,15 @@ pub struct Values<'a, K: 'a, V: 'a> {
// FIXME(#19839) Remove in favor of `#[derive(Clone)]` // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
impl<'a, K, V> Clone for Values<'a, K, V> { impl<'a, K, V> Clone for Values<'a, K, V> {
fn clone(&self) -> 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> { impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.clone()).finish()
.entries(self.clone())
.finish()
} }
} }
@ -1423,7 +1467,9 @@ pub struct ValuesMut<'a, K: 'a, V: 'a> {
} }
enum InternalEntry<K, V, M> { enum InternalEntry<K, V, M> {
Occupied { elem: FullBucket<K, V, M> }, Occupied {
elem: FullBucket<K, V, M>,
},
Vacant { Vacant {
hash: SafeHash, hash: SafeHash,
elem: VacantEntryState<K, V, M>, elem: VacantEntryState<K, V, M>,
@ -1445,19 +1491,11 @@ impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
#[inline] #[inline]
fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> { fn into_entry(self, key: K) -> Option<Entry<'a, K, V>> {
match self { match self {
InternalEntry::Occupied { elem } => { InternalEntry::Occupied { elem } => Some(Occupied(OccupiedEntry {
Some(Occupied(OccupiedEntry {
key: Some(key), key: Some(key),
elem, elem,
})) })),
} InternalEntry::Vacant { hash, elem } => Some(Vacant(VacantEntry { hash, key, elem })),
InternalEntry::Vacant { hash, elem } => {
Some(Vacant(VacantEntry {
hash,
key,
elem,
}))
}
InternalEntry::TableIsEmpty => None, InternalEntry::TableIsEmpty => None,
} }
} }
@ -1471,25 +1509,17 @@ impl<'a, K, V> InternalEntry<K, V, &'a mut RawTable<K, V>> {
/// [`entry`]: struct.HashMap.html#method.entry /// [`entry`]: struct.HashMap.html#method.entry
pub enum Entry<'a, K: 'a, V: 'a> { pub enum Entry<'a, K: 'a, V: 'a> {
/// An occupied entry. /// An occupied entry.
Occupied( OccupiedEntry<'a, K, V>), Occupied(OccupiedEntry<'a, K, V>),
/// A vacant entry. /// 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> { impl<'a, K: 'a + Debug, V: 'a + Debug> Debug for Entry<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Vacant(ref v) => { Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
f.debug_tuple("Entry") Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
.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> { impl<'a, K: 'a + Debug, V: 'a> Debug for VacantEntry<'a, K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("VacantEntry") f.debug_tuple("VacantEntry").field(self.key()).finish()
.field(self.key())
.finish()
} }
} }
@ -1540,8 +1568,9 @@ enum VacantEntryState<K, V, M> {
} }
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
type Item = (&'a K, &'a V); type Item = (&'a K, &'a V);
type IntoIter = Iter<'a, K, V>; type IntoIter = Iter<'a, K, V>;
@ -1552,8 +1581,9 @@ impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S>
} }
impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
type Item = (&'a K, &'a mut V); type Item = (&'a K, &'a mut V);
type IntoIter = IterMut<'a, K, V>; type IntoIter = IterMut<'a, K, V>;
@ -1564,8 +1594,9 @@ impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S>
} }
impl<K, V, S> IntoIterator for HashMap<K, V, S> impl<K, V, S> IntoIterator for HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
type Item = (K, V); type Item = (K, V);
type IntoIter = IntoIter<K, V>; type IntoIter = IntoIter<K, V>;
@ -1588,7 +1619,9 @@ impl<K, V, S> IntoIterator for HashMap<K, V, S>
/// let vec: Vec<(&str, isize)> = map.into_iter().collect(); /// let vec: Vec<(&str, isize)> = map.into_iter().collect();
/// ``` /// ```
fn into_iter(self) -> IntoIter<K, V> { fn into_iter(self) -> IntoIter<K, V> {
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> { impl<'a, K, V> Iterator for IterMut<'a, K, V> {
type Item = (&'a K, &'a mut 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> impl<'a, K, V> fmt::Debug for IterMut<'a, K, V>
where K: fmt::Debug, where
K: fmt::Debug,
V: fmt::Debug, V: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.inner.iter()).finish()
.entries(self.inner.iter())
.finish()
} }
} }
@ -1663,9 +1694,7 @@ impl<K, V> ExactSizeIterator for IntoIter<K, V> {
impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> { impl<K: Debug, V: Debug> fmt::Debug for IntoIter<K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.inner.iter()).finish()
.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> impl<'a, K, V> fmt::Debug for ValuesMut<'a, K, V>
where K: fmt::Debug, where
K: fmt::Debug,
V: fmt::Debug, V: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.inner.inner.iter()).finish()
.entries(self.inner.inner.iter())
.finish()
} }
} }
@ -1756,13 +1784,12 @@ impl<'a, K, V> ExactSizeIterator for Drain<'a, K, V> {
} }
impl<'a, K, V> fmt::Debug for Drain<'a, K, V> impl<'a, K, V> fmt::Debug for Drain<'a, K, V>
where K: fmt::Debug, where
K: fmt::Debug,
V: fmt::Debug, V: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list().entries(self.inner.iter()).finish()
.entries(self.inner.iter())
.finish()
} }
} }
@ -2057,8 +2084,9 @@ impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {
} }
impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S> impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher + Default K: Eq + Hash,
S: BuildHasher + Default,
{ {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> { fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
let mut map = HashMap::with_hasher(Default::default()); let mut map = HashMap::with_hasher(Default::default());
@ -2068,8 +2096,9 @@ impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
} }
impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S> impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
where K: Eq + Hash, where
S: BuildHasher K: Eq + Hash,
S: BuildHasher,
{ {
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) { fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
// Keys may be already present or show multiple times in the iterator. // Keys may be already present or show multiple times in the iterator.
@ -2090,9 +2119,10 @@ impl<K, V, S> Extend<(K, V)> for HashMap<K, V, S>
} }
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S> impl<'a, K, V, S> Extend<(&'a K, &'a V)> for HashMap<K, V, S>
where K: Eq + Hash + Copy, where
K: Eq + Hash + Copy,
V: Copy, V: Copy,
S: BuildHasher S: BuildHasher,
{ {
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) { fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); 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<K, V, S>
// FORK NOTE: These can be reused // FORK NOTE: These can be reused
pub use std::collections::hash_map::{DefaultHasher, RandomState}; pub use std::collections::hash_map::{DefaultHasher, RandomState};
impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S> impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
where K: Eq + Hash + Borrow<Q>, where
K: Eq + Hash + Borrow<Q>,
S: BuildHasher, S: BuildHasher,
Q: Eq + Hash Q: Eq + Hash,
{ {
type Key = K; type Key = K;
fn get(&self, key: &Q) -> Option<&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<K> { fn take(&mut self, key: &Q) -> Option<K> {
@ -2119,7 +2151,9 @@ impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
return None; 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<K> { fn replace(&mut self, key: K) -> Option<K> {
@ -2129,11 +2163,11 @@ impl<K, S, Q: ?Sized> super::Recover<Q> for HashMap<K, (), S>
Occupied(mut occupied) => { Occupied(mut occupied) => {
let key = occupied.take_key().unwrap(); let key = occupied.take_key().unwrap();
Some(mem::replace(occupied.elem.read_mut().0, key)) Some(mem::replace(occupied.elem.read_mut().0, key))
} },
Vacant(vacant) => { Vacant(vacant) => {
vacant.insert(()); vacant.insert(());
None None
} },
} }
} }
} }
@ -2170,8 +2204,9 @@ fn assert_covariance() {
fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> { fn values_val<'a, 'new>(v: Values<'a, u8, &'static str>) -> Values<'a, u8, &'new str> {
v v
} }
fn drain<'new>(d: Drain<'static, &'static str, &'static str>) fn drain<'new>(
-> Drain<'new, &'new str, &'new str> { d: Drain<'static, &'static str, &'static str>,
) -> Drain<'new, &'new str, &'new str> {
d d
} }
} }
@ -2319,19 +2354,19 @@ mod test_map {
DROP_VECTOR.with(|v| { DROP_VECTOR.with(|v| {
assert_eq!(v.borrow()[i], 1); assert_eq!(v.borrow()[i], 1);
assert_eq!(v.borrow()[i+100], 1); assert_eq!(v.borrow()[i + 100], 1);
}); });
} }
DROP_VECTOR.with(|v| { DROP_VECTOR.with(|v| {
for i in 0..50 { for i in 0..50 {
assert_eq!(v.borrow()[i], 0); 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 { for i in 50..100 {
assert_eq!(v.borrow()[i], 1); 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() {} for _ in half.by_ref() {}
DROP_VECTOR.with(|v| { DROP_VECTOR.with(|v| {
let nk = (0..100) let nk = (0..100).filter(|&i| v.borrow()[i] == 1).count();
.filter(|&i| v.borrow()[i] == 1)
.count();
let nv = (0..100) let nv = (0..100).filter(|&i| v.borrow()[i + 100] == 1).count();
.filter(|&i| v.borrow()[i + 100] == 1)
.count();
assert_eq!(nk, 50); assert_eq!(nk, 50);
assert_eq!(nv, 50); assert_eq!(nv, 50);
@ -2419,7 +2450,7 @@ mod test_map {
let mut m: HashMap<isize, bool> = HashMap::new(); let mut m: HashMap<isize, bool> = HashMap::new();
match m.entry(0) { match m.entry(0) {
Occupied(_) => panic!(), Occupied(_) => panic!(),
Vacant(_) => {} Vacant(_) => {},
} }
assert!(*m.entry(0).or_insert(true)); assert!(*m.entry(0).or_insert(true));
assert_eq!(m.len(), 1); assert_eq!(m.len(), 1);
@ -2574,7 +2605,7 @@ mod test_map {
fn test_iterate() { fn test_iterate() {
let mut m = HashMap::with_capacity(4); let mut m = HashMap::with_capacity(4);
for i in 0..32 { 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); assert_eq!(m.len(), 32);
@ -2662,8 +2693,7 @@ mod test_map {
let map_str = format!("{:?}", map); let map_str = format!("{:?}", map);
assert!(map_str == "{1: 2, 3: 4}" || assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
map_str == "{3: 4, 1: 2}");
assert_eq!(format!("{:?}", empty), "{}"); assert_eq!(format!("{:?}", empty), "{}");
} }
@ -2876,12 +2906,11 @@ mod test_map {
Occupied(mut view) => { Occupied(mut view) => {
assert_eq!(view.get(), &10); assert_eq!(view.get(), &10);
assert_eq!(view.insert(100), 10); assert_eq!(view.insert(100), 10);
} },
} }
assert_eq!(map.get(&1).unwrap(), &100); assert_eq!(map.get(&1).unwrap(), &100);
assert_eq!(map.len(), 6); assert_eq!(map.len(), 6);
// Existing key (update) // Existing key (update)
match map.entry(2) { match map.entry(2) {
Vacant(_) => unreachable!(), Vacant(_) => unreachable!(),
@ -2889,7 +2918,7 @@ mod test_map {
let v = view.get_mut(); let v = view.get_mut();
let new_v = (*v) * 10; let new_v = (*v) * 10;
*v = new_v; *v = new_v;
} },
} }
assert_eq!(map.get(&2).unwrap(), &200); assert_eq!(map.get(&2).unwrap(), &200);
assert_eq!(map.len(), 6); assert_eq!(map.len(), 6);
@ -2899,18 +2928,17 @@ mod test_map {
Vacant(_) => unreachable!(), Vacant(_) => unreachable!(),
Occupied(view) => { Occupied(view) => {
assert_eq!(view.remove(), 30); assert_eq!(view.remove(), 30);
} },
} }
assert_eq!(map.get(&3), None); assert_eq!(map.get(&3), None);
assert_eq!(map.len(), 5); assert_eq!(map.len(), 5);
// Inexistent key (insert) // Inexistent key (insert)
match map.entry(10) { match map.entry(10) {
Occupied(_) => unreachable!(), Occupied(_) => unreachable!(),
Vacant(view) => { Vacant(view) => {
assert_eq!(*view.insert(1000), 1000); assert_eq!(*view.insert(1000), 1000);
} },
} }
assert_eq!(map.get(&10).unwrap(), &1000); assert_eq!(map.get(&10).unwrap(), &1000);
assert_eq!(map.len(), 6); assert_eq!(map.len(), 6);
@ -2922,8 +2950,7 @@ mod test_map {
// Test for #19292 // Test for #19292
fn check(m: &HashMap<isize, ()>) { fn check(m: &HashMap<isize, ()>) {
for k in m.keys() { for k in m.keys() {
assert!(m.contains_key(k), assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
"{} is in keys() but not in the map?", k);
} }
} }
@ -2939,11 +2966,11 @@ mod test_map {
for i in 0..1000 { for i in 0..1000 {
let x = rng.gen_range(-10, 10); let x = rng.gen_range(-10, 10);
match m.entry(x) { match m.entry(x) {
Vacant(_) => {} Vacant(_) => {},
Occupied(e) => { Occupied(e) => {
println!("{}: remove {}", i, x); println!("{}: remove {}", i, x);
e.remove(); e.remove();
} },
} }
check(&m); check(&m);
@ -3021,7 +3048,7 @@ mod test_map {
Vacant(e) => { Vacant(e) => {
assert_eq!(key, *e.key()); assert_eq!(key, *e.key());
e.insert(value.clone()); e.insert(value.clone());
} },
} }
assert_eq!(a.len(), 1); assert_eq!(a.len(), 1);
assert_eq!(a[key], value); assert_eq!(a[key], value);
@ -3029,7 +3056,7 @@ mod test_map {
#[test] #[test]
fn test_retain() { fn test_retain() {
let mut map: HashMap<isize, isize> = (0..100).map(|x|(x, x*10)).collect(); let mut map: HashMap<isize, isize> = (0..100).map(|x| (x, x * 10)).collect();
map.retain(|&k, _| k % 2 == 0); map.retain(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 50); assert_eq!(map.len(), 50);

View file

@ -122,8 +122,9 @@ pub struct HashSet<T, S = RandomState> {
} }
impl<T, S> HashSet<T, S> impl<T, S> HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
/// Creates a new empty hash set which will use the given hasher to hash /// Creates a new empty hash set which will use the given hasher to hash
/// keys. /// keys.
@ -147,7 +148,9 @@ impl<T, S> HashSet<T, S>
/// ``` /// ```
#[inline] #[inline]
pub fn with_hasher(hasher: S) -> HashSet<T, S> { pub fn with_hasher(hasher: S) -> HashSet<T, S> {
HashSet { map: HashMap::with_hasher(hasher) } HashSet {
map: HashMap::with_hasher(hasher),
}
} }
/// Creates an empty `HashSet` with with the specified capacity, using /// Creates an empty `HashSet` with with the specified capacity, using
@ -173,7 +176,9 @@ impl<T, S> HashSet<T, S>
/// ``` /// ```
#[inline] #[inline]
pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> { pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
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`]. /// Returns a reference to the set's [`BuildHasher`].
@ -265,7 +270,9 @@ impl<T, S> HashSet<T, S>
/// } /// }
/// ``` /// ```
pub fn iter(&self) -> Iter<T> { pub fn iter(&self) -> Iter<T> {
Iter { iter: self.map.keys() } Iter {
iter: self.map.keys(),
}
} }
/// Visits the values representing the difference, /// Visits the values representing the difference,
@ -319,10 +326,13 @@ impl<T, S> HashSet<T, S>
/// assert_eq!(diff1, diff2); /// assert_eq!(diff1, diff2);
/// assert_eq!(diff1, [1, 4].iter().collect()); /// assert_eq!(diff1, [1, 4].iter().collect());
/// ``` /// ```
pub fn symmetric_difference<'a>(&'a self, pub fn symmetric_difference<'a>(
other: &'a HashSet<T, S>) &'a self,
-> SymmetricDifference<'a, T, S> { other: &'a HashSet<T, S>,
SymmetricDifference { iter: self.difference(other).chain(other.difference(self)) } ) -> SymmetricDifference<'a, T, S> {
SymmetricDifference {
iter: self.difference(other).chain(other.difference(self)),
}
} }
/// Visits the values representing the intersection, /// Visits the values representing the intersection,
@ -369,7 +379,9 @@ impl<T, S> HashSet<T, S>
/// assert_eq!(union, [1, 2, 3, 4].iter().collect()); /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
/// ``` /// ```
pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> { pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> 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. /// Returns the number of elements in the set.
@ -423,7 +435,9 @@ impl<T, S> HashSet<T, S>
/// ``` /// ```
#[inline] #[inline]
pub fn drain(&mut self) -> Drain<T> { pub fn drain(&mut self) -> Drain<T> {
Drain { iter: self.map.drain() } Drain {
iter: self.map.drain(),
}
} }
/// Clears the set, removing all values. /// Clears the set, removing all values.
@ -438,7 +452,10 @@ impl<T, S> HashSet<T, S>
/// v.clear(); /// v.clear();
/// assert!(v.is_empty()); /// assert!(v.is_empty());
/// ``` /// ```
pub fn clear(&mut self) where T: 'static { pub fn clear(&mut self)
where
T: 'static,
{
self.map.clear() self.map.clear()
} }
@ -461,8 +478,9 @@ impl<T, S> HashSet<T, S>
/// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Eq`]: ../../std/cmp/trait.Eq.html
/// [`Hash`]: ../../std/hash/trait.Hash.html /// [`Hash`]: ../../std/hash/trait.Hash.html
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where T: Borrow<Q>, where
Q: Hash + Eq T: Borrow<Q>,
Q: Hash + Eq,
{ {
self.map.contains_key(value) self.map.contains_key(value)
} }
@ -476,8 +494,9 @@ impl<T, S> HashSet<T, S>
/// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Eq`]: ../../std/cmp/trait.Eq.html
/// [`Hash`]: ../../std/hash/trait.Hash.html /// [`Hash`]: ../../std/hash/trait.Hash.html
pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
where T: Borrow<Q>, where
Q: Hash + Eq T: Borrow<Q>,
Q: Hash + Eq,
{ {
Recover::get(&self.map, value) Recover::get(&self.map, value)
} }
@ -598,8 +617,9 @@ impl<T, S> HashSet<T, S>
/// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Eq`]: ../../std/cmp/trait.Eq.html
/// [`Hash`]: ../../std/hash/trait.Hash.html /// [`Hash`]: ../../std/hash/trait.Hash.html
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
where T: Borrow<Q>, where
Q: Hash + Eq T: Borrow<Q>,
Q: Hash + Eq,
{ {
self.map.remove(value).is_some() self.map.remove(value).is_some()
} }
@ -613,8 +633,9 @@ impl<T, S> HashSet<T, S>
/// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Eq`]: ../../std/cmp/trait.Eq.html
/// [`Hash`]: ../../std/hash/trait.Hash.html /// [`Hash`]: ../../std/hash/trait.Hash.html
pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T> pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
where T: Borrow<Q>, where
Q: Hash + Eq T: Borrow<Q>,
Q: Hash + Eq,
{ {
Recover::take(&mut self.map, value) Recover::take(&mut self.map, value)
} }
@ -634,15 +655,17 @@ impl<T, S> HashSet<T, S>
/// assert_eq!(set.len(), 3); /// assert_eq!(set.len(), 3);
/// ``` /// ```
pub fn retain<F>(&mut self, mut f: F) pub fn retain<F>(&mut self, mut f: F)
where F: FnMut(&T) -> bool where
F: FnMut(&T) -> bool,
{ {
self.map.retain(|k, _| f(k)); self.map.retain(|k, _| f(k));
} }
} }
impl<T, S> PartialEq for HashSet<T, S> impl<T, S> PartialEq for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
fn eq(&self, other: &HashSet<T, S>) -> bool { fn eq(&self, other: &HashSet<T, S>) -> bool {
if self.len() != other.len() { if self.len() != other.len() {
@ -654,14 +677,16 @@ impl<T, S> PartialEq for HashSet<T, S>
} }
impl<T, S> Eq for HashSet<T, S> impl<T, S> Eq for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
} }
impl<T, S> fmt::Debug for HashSet<T, S> impl<T, S> fmt::Debug for HashSet<T, S>
where T: Eq + Hash + fmt::Debug, where
S: BuildHasher T: Eq + Hash + fmt::Debug,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_set().entries(self.iter()).finish() f.debug_set().entries(self.iter()).finish()
@ -669,8 +694,9 @@ impl<T, S> fmt::Debug for HashSet<T, S>
} }
impl<T, S> FromIterator<T> for HashSet<T, S> impl<T, S> FromIterator<T> for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher + Default T: Eq + Hash,
S: BuildHasher + Default,
{ {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> HashSet<T, S> {
let mut set = HashSet::with_hasher(Default::default()); let mut set = HashSet::with_hasher(Default::default());
@ -680,8 +706,9 @@ impl<T, S> FromIterator<T> for HashSet<T, S>
} }
impl<T, S> Extend<T> for HashSet<T, S> impl<T, S> Extend<T> for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
self.map.extend(iter.into_iter().map(|k| (k, ()))); self.map.extend(iter.into_iter().map(|k| (k, ())));
@ -689,8 +716,9 @@ impl<T, S> Extend<T> for HashSet<T, S>
} }
impl<'a, T, S> Extend<&'a T> for HashSet<T, S> impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
where T: 'a + Eq + Hash + Copy, where
S: BuildHasher T: 'a + Eq + Hash + Copy,
S: BuildHasher,
{ {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned()); self.extend(iter.into_iter().cloned());
@ -698,18 +726,22 @@ impl<'a, T, S> Extend<&'a T> for HashSet<T, S>
} }
impl<T, S> Default for HashSet<T, S> impl<T, S> Default for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher + Default T: Eq + Hash,
S: BuildHasher + Default,
{ {
/// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher. /// Creates an empty `HashSet<T, S>` with the `Default` value for the hasher.
fn default() -> HashSet<T, S> { fn default() -> HashSet<T, S> {
HashSet { map: HashMap::default() } HashSet {
map: HashMap::default(),
}
} }
} }
impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S> impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
where T: Eq + Hash + Clone, where
S: BuildHasher + Default T: Eq + Hash + Clone,
S: BuildHasher + Default,
{ {
type Output = HashSet<T, S>; type Output = HashSet<T, S>;
@ -739,8 +771,9 @@ impl<'a, 'b, T, S> BitOr<&'b HashSet<T, S>> for &'a HashSet<T, S>
} }
impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S> impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
where T: Eq + Hash + Clone, where
S: BuildHasher + Default T: Eq + Hash + Clone,
S: BuildHasher + Default,
{ {
type Output = HashSet<T, S>; type Output = HashSet<T, S>;
@ -770,8 +803,9 @@ impl<'a, 'b, T, S> BitAnd<&'b HashSet<T, S>> for &'a HashSet<T, S>
} }
impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S> impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
where T: Eq + Hash + Clone, where
S: BuildHasher + Default T: Eq + Hash + Clone,
S: BuildHasher + Default,
{ {
type Output = HashSet<T, S>; type Output = HashSet<T, S>;
@ -801,8 +835,9 @@ impl<'a, 'b, T, S> BitXor<&'b HashSet<T, S>> for &'a HashSet<T, S>
} }
impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S> impl<'a, 'b, T, S> Sub<&'b HashSet<T, S>> for &'a HashSet<T, S>
where T: Eq + Hash + Clone, where
S: BuildHasher + Default T: Eq + Hash + Clone,
S: BuildHasher + Default,
{ {
type Output = HashSet<T, S>; type Output = HashSet<T, S>;
@ -915,8 +950,9 @@ pub struct Union<'a, T: 'a, S: 'a> {
} }
impl<'a, T, S> IntoIterator for &'a HashSet<T, S> impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; type Item = &'a T;
type IntoIter = Iter<'a, T>; type IntoIter = Iter<'a, T>;
@ -927,8 +963,9 @@ impl<'a, T, S> IntoIterator for &'a HashSet<T, S>
} }
impl<T, S> IntoIterator for HashSet<T, S> impl<T, S> IntoIterator for HashSet<T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = T; type Item = T;
type IntoIter = IntoIter<T>; type IntoIter = IntoIter<T>;
@ -954,13 +991,17 @@ impl<T, S> IntoIterator for HashSet<T, S>
/// } /// }
/// ``` /// ```
fn into_iter(self) -> IntoIter<T> { fn into_iter(self) -> IntoIter<T> {
IntoIter { iter: self.map.into_iter() } IntoIter {
iter: self.map.into_iter(),
}
} }
} }
impl<'a, K> Clone for Iter<'a, K> { impl<'a, K> Clone for Iter<'a, K> {
fn clone(&self) -> 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> { impl<'a, K> Iterator for Iter<'a, K> {
@ -1003,10 +1044,7 @@ impl<K> ExactSizeIterator for IntoIter<K> {
impl<K: fmt::Debug> fmt::Debug for IntoIter<K> { impl<K: fmt::Debug> fmt::Debug for IntoIter<K> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let entries_iter = self.iter let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
.inner
.iter()
.map(|(k, _)| k);
f.debug_list().entries(entries_iter).finish() 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> { impl<'a, K: fmt::Debug> fmt::Debug for Drain<'a, K> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let entries_iter = self.iter let entries_iter = self.iter.inner.iter().map(|(k, _)| k);
.inner
.iter()
.map(|(k, _)| k);
f.debug_list().entries(entries_iter).finish() f.debug_list().entries(entries_iter).finish()
} }
} }
impl<'a, T, S> Clone for Intersection<'a, T, S> { impl<'a, T, S> Clone for Intersection<'a, T, S> {
fn clone(&self) -> 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> impl<'a, T, S> Iterator for Intersection<'a, T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; 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> impl<'a, T, S> fmt::Debug for Intersection<'a, T, S>
where T: fmt::Debug + Eq + Hash, where
S: BuildHasher T: fmt::Debug + Eq + Hash,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.clone()).finish() 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> { impl<'a, T, S> Clone for Difference<'a, T, S> {
fn clone(&self) -> 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> impl<'a, T, S> Iterator for Difference<'a, T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; 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> impl<'a, T, S> fmt::Debug for Difference<'a, T, S>
where T: fmt::Debug + Eq + Hash, where
S: BuildHasher T: fmt::Debug + Eq + Hash,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.clone()).finish() 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> { impl<'a, T, S> Clone for SymmetricDifference<'a, T, S> {
fn clone(&self) -> 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> impl<'a, T, S> Iterator for SymmetricDifference<'a, T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; 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> impl<'a, T, S> fmt::Debug for SymmetricDifference<'a, T, S>
where T: fmt::Debug + Eq + Hash, where
S: BuildHasher T: fmt::Debug + Eq + Hash,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.clone()).finish() 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> { impl<'a, T, S> Clone for Union<'a, T, S> {
fn clone(&self) -> 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> impl<'a, T, S> fmt::Debug for Union<'a, T, S>
where T: fmt::Debug + Eq + Hash, where
S: BuildHasher T: fmt::Debug + Eq + Hash,
S: BuildHasher,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.clone()).finish() 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> impl<'a, T, S> Iterator for Union<'a, T, S>
where T: Eq + Hash, where
S: BuildHasher T: Eq + Hash,
S: BuildHasher,
{ {
type Item = &'a T; type Item = &'a T;
@ -1178,20 +1231,24 @@ fn assert_covariance() {
fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> { fn into_iter<'new>(v: IntoIter<&'static str>) -> IntoIter<&'new str> {
v v
} }
fn difference<'a, 'new>(v: Difference<'a, &'static str, RandomState>) fn difference<'a, 'new>(
-> Difference<'a, &'new str, RandomState> { v: Difference<'a, &'static str, RandomState>,
) -> Difference<'a, &'new str, RandomState> {
v v
} }
fn symmetric_difference<'a, 'new>(v: SymmetricDifference<'a, &'static str, RandomState>) fn symmetric_difference<'a, 'new>(
-> SymmetricDifference<'a, &'new str, RandomState> { v: SymmetricDifference<'a, &'static str, RandomState>,
) -> SymmetricDifference<'a, &'new str, RandomState> {
v v
} }
fn intersection<'a, 'new>(v: Intersection<'a, &'static str, RandomState>) fn intersection<'a, 'new>(
-> Intersection<'a, &'new str, RandomState> { v: Intersection<'a, &'static str, RandomState>,
) -> Intersection<'a, &'new str, RandomState> {
v v
} }
fn union<'a, 'new>(v: Union<'a, &'static str, RandomState>) fn union<'a, 'new>(
-> Union<'a, &'new str, RandomState> { v: Union<'a, &'static str, RandomState>,
) -> Union<'a, &'new str, RandomState> {
v v
} }
fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> { fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {

View file

@ -44,7 +44,10 @@ pub struct FailedAllocationError {
impl FailedAllocationError { impl FailedAllocationError {
#[inline] #[inline]
pub fn new(reason: &'static str) -> Self { 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 { impl fmt::Display for FailedAllocationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.allocation_info { match self.allocation_info {
Some(ref info) => { Some(ref info) => write!(
write!(f, "{}, allocation: (size: {}, alignment: {})", self.reason, info.size, info.alignment) f,
}, "{}, allocation: (size: {}, alignment: {})",
self.reason, info.size, info.alignment
),
None => self.reason.fmt(f), None => self.reason.fmt(f),
} }
} }

View file

@ -29,9 +29,9 @@ impl<T: 'static> Unique<T> {
} }
} }
unsafe impl<T: Send + 'static> Send for Unique<T> { } unsafe impl<T: Send + 'static> Send for Unique<T> {}
unsafe impl<T: Sync + 'static> Sync for Unique<T> { } unsafe impl<T: Sync + 'static> Sync for Unique<T> {}
pub struct Shared<T: 'static> { pub struct Shared<T: 'static> {
ptr: NonZeroPtr<T>, ptr: NonZeroPtr<T>,

View file

@ -203,7 +203,9 @@ impl SafeHash {
// //
// Truncate hash to fit in `HashUint`. // Truncate hash to fit in `HashUint`.
let hash_bits = size_of::<HashUint>() * 8; let hash_bits = size_of::<HashUint>() * 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 /// This function wraps up `hash_keyed` to be the only way outside this
/// module to generate a SafeHash. /// module to generate a SafeHash.
pub fn make_hash<T: ?Sized, S>(hash_state: &S, t: &T) -> SafeHash pub fn make_hash<T: ?Sized, S>(hash_state: &S, t: &T) -> SafeHash
where T: Hash, where
S: BuildHasher T: Hash,
S: BuildHasher,
{ {
let mut state = hash_state.build_hasher(); let mut state = hash_state.build_hasher();
t.hash(&mut state); t.hash(&mut state);
@ -294,7 +297,8 @@ impl<K, V, M> Bucket<K, V, M> {
} }
impl<K, V, M> Deref for FullBucket<K, V, M> impl<K, V, M> Deref for FullBucket<K, V, M>
where M: Deref<Target = RawTable<K, V>> where
M: Deref<Target = RawTable<K, V>>,
{ {
type Target = RawTable<K, V>; type Target = RawTable<K, V>;
fn deref(&self) -> &RawTable<K, V> { fn deref(&self) -> &RawTable<K, V> {
@ -308,7 +312,6 @@ pub trait Put<K, V> {
unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V>; unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V>;
} }
impl<'t, K, V> Put<K, V> for &'t mut RawTable<K, V> { impl<'t, K, V> Put<K, V> for &'t mut RawTable<K, V> {
unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
*self *self
@ -316,7 +319,8 @@ impl<'t, K, V> Put<K, V> for &'t mut RawTable<K, V> {
} }
impl<K, V, M> Put<K, V> for Bucket<K, V, M> impl<K, V, M> Put<K, V> for Bucket<K, V, M>
where M: Put<K, V> where
M: Put<K, V>,
{ {
unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
self.table.borrow_table_mut() self.table.borrow_table_mut()
@ -324,7 +328,8 @@ impl<K, V, M> Put<K, V> for Bucket<K, V, M>
} }
impl<K, V, M> Put<K, V> for FullBucket<K, V, M> impl<K, V, M> Put<K, V> for FullBucket<K, V, M>
where M: Put<K, V> where
M: Put<K, V>,
{ {
unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> { unsafe fn borrow_table_mut(&mut self) -> &mut RawTable<K, V> {
self.table.borrow_table_mut() self.table.borrow_table_mut()
@ -336,20 +341,17 @@ impl<K, V, M: Deref<Target = RawTable<K, V>>> Bucket<K, V, M> {
Bucket::at_index(table, hash.inspect() as usize) Bucket::at_index(table, hash.inspect() as usize)
} }
pub fn new_from(r: RawBucket<K, V>, t: M) pub fn new_from(r: RawBucket<K, V>, t: M) -> Bucket<K, V, M> {
-> Bucket<K, V, M> Bucket { raw: r, table: t }
{
Bucket {
raw: r,
table: t,
}
} }
pub fn at_index(table: M, ib_index: usize) -> Bucket<K, V, M> { pub fn at_index(table: M, ib_index: usize) -> Bucket<K, V, M> {
// if capacity is 0, then the RawBucket will be populated with bogus pointers. // 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. // This is an uncommon case though, so avoid it in release builds.
debug_assert!(table.capacity() > 0, debug_assert!(
"Table should have capacity at this point"); table.capacity() > 0,
"Table should have capacity at this point"
);
let ib_index = ib_index & table.capacity_mask; let ib_index = ib_index & table.capacity_mask;
Bucket { Bucket {
raw: table.raw_bucket_at(ib_index), raw: table.raw_bucket_at(ib_index),
@ -387,11 +389,11 @@ impl<K, V, M: Deref<Target = RawTable<K, V>>> Bucket<K, V, M> {
} }
// Leaving this bucket in the last cluster for later. // Leaving this bucket in the last cluster for later.
full.into_bucket() full.into_bucket()
} },
Empty(b) => { Empty(b) => {
// Encountered a hole between clusters. // Encountered a hole between clusters.
b.into_bucket() b.into_bucket()
} },
}; };
bucket.next(); bucket.next();
} }
@ -404,18 +406,14 @@ impl<K, V, M: Deref<Target = RawTable<K, V>>> Bucket<K, V, M> {
/// this module. /// this module.
pub fn peek(self) -> BucketState<K, V, M> { pub fn peek(self) -> BucketState<K, V, M> {
match unsafe { *self.raw.hash() } { match unsafe { *self.raw.hash() } {
EMPTY_BUCKET => { EMPTY_BUCKET => Empty(EmptyBucket {
Empty(EmptyBucket {
raw: self.raw, raw: self.raw,
table: self.table, table: self.table,
}) }),
} _ => Full(FullBucket {
_ => {
Full(FullBucket {
raw: self.raw, raw: self.raw,
table: self.table, table: self.table,
}) }),
}
} }
} }
@ -453,19 +451,15 @@ impl<K, V, M: Deref<Target = RawTable<K, V>>> EmptyBucket<K, V, M> {
}; };
match self.next().peek() { match self.next().peek() {
Full(bucket) => { Full(bucket) => Ok(GapThenFull { gap, full: bucket }),
Ok(GapThenFull {
gap,
full: bucket,
})
}
Empty(e) => Err(e.into_bucket()), Empty(e) => Err(e.into_bucket()),
} }
} }
} }
impl<K, V, M> EmptyBucket<K, V, M> impl<K, V, M> EmptyBucket<K, V, M>
where M: Put<K, V> where
M: Put<K, V>,
{ {
/// Puts given key and value pair, along with the key's hash, /// Puts given key and value pair, along with the key's hash,
/// into this bucket in the hashtable. Note how `self` is 'moved' into /// into this bucket in the hashtable. Note how `self` is 'moved' into
@ -528,7 +522,11 @@ impl<K, V, M: Deref<Target = RawTable<K, V>>> FullBucket<K, V, M> {
#[inline] #[inline]
pub fn hash(&self) -> SafeHash { 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. /// Gets references to the key and value at a given index.
@ -554,12 +552,14 @@ impl<'t, K, V> FullBucket<K, V, &'t mut RawTable<K, V>> {
unsafe { unsafe {
*self.raw.hash() = EMPTY_BUCKET; *self.raw.hash() = EMPTY_BUCKET;
let (k, v) = ptr::read(self.raw.pair()); let (k, v) = ptr::read(self.raw.pair());
(EmptyBucket { (
EmptyBucket {
raw: self.raw, raw: self.raw,
table: self.table, table: self.table,
}, },
k, k,
v) v,
)
} }
} }
} }
@ -567,7 +567,8 @@ impl<'t, K, V> FullBucket<K, V, &'t mut RawTable<K, V>> {
// This use of `Put` is misleading and restrictive, but safe and sufficient for our use cases // 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. // where `M` is a full bucket or table reference type with mutable access to the table.
impl<K, V, M> FullBucket<K, V, M> impl<K, V, M> FullBucket<K, V, M>
where M: Put<K, V> where
M: Put<K, V>,
{ {
pub fn replace(&mut self, h: SafeHash, k: K, v: V) -> (SafeHash, K, V) { pub fn replace(&mut self, h: SafeHash, k: K, v: V) -> (SafeHash, K, V) {
unsafe { unsafe {
@ -580,7 +581,8 @@ impl<K, V, M> FullBucket<K, V, M>
} }
impl<K, V, M> FullBucket<K, V, M> impl<K, V, M> FullBucket<K, V, M>
where M: Deref<Target = RawTable<K, V>> + DerefMut where
M: Deref<Target = RawTable<K, V>> + DerefMut,
{ {
/// Gets mutable references to the key and value at a given index. /// Gets mutable references to the key and value at a given index.
pub fn read_mut(&mut self) -> (&mut K, &mut V) { pub fn read_mut(&mut self) -> (&mut K, &mut V) {
@ -592,7 +594,8 @@ impl<K, V, M> FullBucket<K, V, M>
} }
impl<'t, K, V, M> FullBucket<K, V, M> impl<'t, K, V, M> FullBucket<K, V, M>
where M: Deref<Target = RawTable<K, V>> + 't where
M: Deref<Target = RawTable<K, V>> + 't,
{ {
/// Exchange a bucket state for immutable references into the table. /// Exchange a bucket state for immutable references into the table.
/// Because the underlying reference to the table is also consumed, /// Because the underlying reference to the table is also consumed,
@ -608,7 +611,8 @@ impl<'t, K, V, M> FullBucket<K, V, M>
} }
impl<'t, K, V, M> FullBucket<K, V, M> impl<'t, K, V, M> FullBucket<K, V, M>
where M: Deref<Target = RawTable<K, V>> + DerefMut + 't where
M: Deref<Target = RawTable<K, V>> + DerefMut + 't,
{ {
/// This works similarly to `into_refs`, exchanging a bucket state /// This works similarly to `into_refs`, exchanging a bucket state
/// for mutable references into the table. /// for mutable references into the table.
@ -621,7 +625,8 @@ impl<'t, K, V, M> FullBucket<K, V, M>
} }
impl<K, V, M> GapThenFull<K, V, M> impl<K, V, M> GapThenFull<K, V, M>
where M: Deref<Target = RawTable<K, V>> where
M: Deref<Target = RawTable<K, V>>,
{ {
#[inline] #[inline]
pub fn full(&self) -> &FullBucket<K, V, M> { pub fn full(&self) -> &FullBucket<K, V, M> {
@ -649,13 +654,12 @@ impl<K, V, M> GapThenFull<K, V, M>
self.full = bucket; self.full = bucket;
Ok(self) Ok(self)
} },
Empty(b) => Err(b.into_bucket()), Empty(b) => Err(b.into_bucket()),
} }
} }
} }
/// Rounds up to a multiple of a power of two. Returns the closest multiple /// Rounds up to a multiple of a power of two. Returns the closest multiple
/// of `target_alignment` that is higher or equal to `unrounded`. /// 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), // Returns a tuple of (pairs_offset, end_of_pairs_offset),
// from the start of a mallocated array. // from the start of a mallocated array.
#[inline] #[inline]
fn calculate_offsets(hashes_size: usize, fn calculate_offsets(
hashes_size: usize,
pairs_size: usize, pairs_size: usize,
pairs_align: usize) pairs_align: usize,
-> (usize, usize, bool) { ) -> (usize, usize, bool) {
let pairs_offset = round_up_to_next(hashes_size, pairs_align); let pairs_offset = round_up_to_next(hashes_size, pairs_align);
let (end_of_pairs, oflo) = pairs_offset.overflowing_add(pairs_size); 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, // Returns a tuple of (minimum required malloc alignment, hash_offset,
// array_size), from the start of a mallocated array. // array_size), from the start of a mallocated array.
fn calculate_allocation(hash_size: usize, fn calculate_allocation(
hash_size: usize,
hash_align: usize, hash_align: usize,
pairs_size: usize, pairs_size: usize,
pairs_align: usize) pairs_align: usize,
-> (usize, usize, usize, bool) { ) -> (usize, usize, usize, bool) {
let hash_offset = 0; let hash_offset = 0;
let (_, end_of_pairs, oflo) = calculate_offsets(hash_size, pairs_size, pairs_align); let (_, end_of_pairs, oflo) = calculate_offsets(hash_size, pairs_size, pairs_align);
@ -728,7 +734,9 @@ impl<K, V> RawTable<K, V> {
/// Does not initialize the buckets. The caller should ensure they, /// Does not initialize the buckets. The caller should ensure they,
/// at the very least, set every hash to EMPTY_BUCKET. /// at the very least, set every hash to EMPTY_BUCKET.
unsafe fn try_new_uninitialized(capacity: usize) -> Result<RawTable<K, V>, FailedAllocationError> { unsafe fn try_new_uninitialized(
capacity: usize,
) -> Result<RawTable<K, V>, FailedAllocationError> {
if capacity == 0 { if capacity == 0 {
return Ok(RawTable { return Ok(RawTable {
size: 0, size: 0,
@ -751,29 +759,38 @@ impl<K, V> RawTable<K, V> {
// This is great in theory, but in practice getting the alignment // This is great in theory, but in practice getting the alignment
// right is a little subtle. Therefore, calculating offsets has been // right is a little subtle. Therefore, calculating offsets has been
// factored out into a different function. // factored out into a different function.
let (alignment, hash_offset, size, oflo) = calculate_allocation(hashes_size, let (alignment, hash_offset, size, oflo) = calculate_allocation(
hashes_size,
align_of::<HashUint>(), align_of::<HashUint>(),
pairs_size, pairs_size,
align_of::<(K, V)>()); align_of::<(K, V)>(),
);
if oflo { 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. // One check for overflow that covers calculation and rounding of size.
let size_of_bucket = size_of::<HashUint>().checked_add(size_of::<(K, V)>()).unwrap(); let size_of_bucket = size_of::<HashUint>()
.checked_add(size_of::<(K, V)>())
.unwrap();
let cap_bytes = capacity.checked_mul(size_of_bucket); let cap_bytes = capacity.checked_mul(size_of_bucket);
if let Some(cap_bytes) = cap_bytes { if let Some(cap_bytes) = cap_bytes {
if size < 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 { } 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 // FORK NOTE: Uses alloc shim instead of Heap.alloc
let buffer = alloc(size, alignment); let buffer = alloc(size, alignment);
@ -857,7 +874,9 @@ impl<K, V> RawTable<K, V> {
} }
pub fn into_iter(self) -> IntoIter<K, V> { pub fn into_iter(self) -> IntoIter<K, V> {
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. // Replace the marker regardless of lifetime bounds on parameters.
IntoIter { IntoIter {
iter: RawBuckets { iter: RawBuckets {
@ -870,7 +889,9 @@ impl<K, V> RawTable<K, V> {
} }
pub fn drain(&mut self) -> Drain<K, V> { pub fn drain(&mut self) -> Drain<K, V> {
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. // Replace the marker regardless of lifetime bounds on parameters.
Drain { Drain {
iter: RawBuckets { 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> { impl<'a, K, V> Iterator for RawBuckets<'a, K, V> {
type Item = RawBucket<K, V>; type Item = RawBucket<K, V>;
@ -1112,12 +1132,16 @@ impl<'a, K, V> Iterator for Drain<'a, K, V> {
#[inline] #[inline]
fn next(&mut self) -> Option<(SafeHash, K, V)> { fn next(&mut self) -> Option<(SafeHash, K, V)> {
self.iter.next().map(|raw| { self.iter.next().map(|raw| unsafe {
unsafe {
self.table.as_mut().size -= 1; self.table.as_mut().size -= 1;
let (k, v) = ptr::read(raw.pair()); let (k, v) = ptr::read(raw.pair());
(SafeHash { hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET) }, k, v) (
} SafeHash {
hash: ptr::replace(&mut *raw.hash(), EMPTY_BUCKET),
},
k,
v,
)
}) })
} }
@ -1188,10 +1212,12 @@ impl<K, V> Drop for RawTable<K, V> {
let hashes_size = self.capacity() * size_of::<HashUint>(); let hashes_size = self.capacity() * size_of::<HashUint>();
let pairs_size = self.capacity() * size_of::<(K, V)>(); let pairs_size = self.capacity() * size_of::<(K, V)>();
let (align, _, _, oflo) = calculate_allocation(hashes_size, let (align, _, _, oflo) = calculate_allocation(
hashes_size,
align_of::<HashUint>(), align_of::<HashUint>(),
pairs_size, pairs_size,
align_of::<(K, V)>()); align_of::<(K, V)>(),
);
debug_assert!(!oflo, "should be impossible"); debug_assert!(!oflo, "should be impossible");