Skip to content

Commit 13a1f21

Browse files
committed
hashmap: Store hashes as usize internally
We can't use more than usize's bits of a hash to select a bucket anyway, so we only need to store that part in the table. This should be an improvement for the size of the data structure on 32-bit platforms. Smaller data means better cache utilization and hopefully better performance.
1 parent da7f8c5 commit 13a1f21

File tree

1 file changed

+44
-25
lines changed

1 file changed

+44
-25
lines changed

src/libstd/collections/hash/table.rs

+44-25
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,18 @@ use ptr::{self, Unique, Shared};
2121

2222
use self::BucketState::*;
2323

24-
const EMPTY_BUCKET: u64 = 0;
24+
/// Integer type used for stored hash values.
25+
///
26+
/// No more than bit_width(usize) bits are needed to select a bucket.
27+
///
28+
/// The most significant bit is ours to use for tagging `SafeHash`.
29+
///
30+
/// (Even if we could have usize::MAX bytes allocated for buckets,
31+
/// each bucket stores at least a `HashUint`, so there can be no more than
32+
/// usize::MAX / size_of(usize) buckets.)
33+
type HashUint = usize;
34+
35+
const EMPTY_BUCKET: HashUint = 0;
2536

2637
/// The raw hashtable, providing safe-ish access to the unzipped and highly
2738
/// optimized arrays of hashes, and key-value pairs.
@@ -64,7 +75,7 @@ const EMPTY_BUCKET: u64 = 0;
6475
pub struct RawTable<K, V> {
6576
capacity: usize,
6677
size: usize,
67-
hashes: Unique<u64>,
78+
hashes: Unique<HashUint>,
6879

6980
// Because K/V do not appear directly in any of the types in the struct,
7081
// inform rustc that in fact instances of K and V are reachable from here.
@@ -75,7 +86,7 @@ unsafe impl<K: Send, V: Send> Send for RawTable<K, V> {}
7586
unsafe impl<K: Sync, V: Sync> Sync for RawTable<K, V> {}
7687

7788
struct RawBucket<K, V> {
78-
hash: *mut u64,
89+
hash: *mut HashUint,
7990
// We use *const to ensure covariance with respect to K and V
8091
pair: *const (K, V),
8192
_marker: marker::PhantomData<(K, V)>,
@@ -136,15 +147,27 @@ pub struct GapThenFull<K, V, M> {
136147
/// buckets.
137148
#[derive(PartialEq, Copy, Clone)]
138149
pub struct SafeHash {
139-
hash: u64,
150+
hash: HashUint,
140151
}
141152

142153
impl SafeHash {
143154
/// Peek at the hash value, which is guaranteed to be non-zero.
144155
#[inline(always)]
145-
pub fn inspect(&self) -> u64 {
156+
pub fn inspect(&self) -> HashUint {
146157
self.hash
147158
}
159+
160+
#[inline(always)]
161+
pub fn new(hash: u64) -> Self {
162+
// We need to avoid 0 in order to prevent collisions with
163+
// EMPTY_HASH. We can maintain our precious uniform distribution
164+
// of initial indexes by unconditionally setting the MSB,
165+
// effectively reducing the hashes by one bit.
166+
//
167+
// Truncate hash to fit in `HashUint`.
168+
let hash_bits = size_of::<HashUint>() * 8;
169+
SafeHash { hash: (1 << (hash_bits - 1)) | (hash as HashUint) }
170+
}
148171
}
149172

150173
/// We need to remove hashes of 0. That's reserved for empty buckets.
@@ -156,25 +179,21 @@ pub fn make_hash<T: ?Sized, S>(hash_state: &S, t: &T) -> SafeHash
156179
{
157180
let mut state = hash_state.build_hasher();
158181
t.hash(&mut state);
159-
// We need to avoid 0 in order to prevent collisions with
160-
// EMPTY_HASH. We can maintain our precious uniform distribution
161-
// of initial indexes by unconditionally setting the MSB,
162-
// effectively reducing 64-bits hashes to 63 bits.
163-
SafeHash { hash: 0x8000_0000_0000_0000 | state.finish() }
182+
SafeHash::new(state.finish())
164183
}
165184

166-
// `replace` casts a `*u64` to a `*SafeHash`. Since we statically
185+
// `replace` casts a `*HashUint` to a `*SafeHash`. Since we statically
167186
// ensure that a `FullBucket` points to an index with a non-zero hash,
168-
// and a `SafeHash` is just a `u64` with a different name, this is
187+
// and a `SafeHash` is just a `HashUint` with a different name, this is
169188
// safe.
170189
//
171190
// This test ensures that a `SafeHash` really IS the same size as a
172-
// `u64`. If you need to change the size of `SafeHash` (and
191+
// `HashUint`. If you need to change the size of `SafeHash` (and
173192
// consequently made this test fail), `replace` needs to be
174193
// modified to no longer assume this.
175194
#[test]
176-
fn can_alias_safehash_as_u64() {
177-
assert_eq!(size_of::<SafeHash>(), size_of::<u64>())
195+
fn can_alias_safehash_as_hash() {
196+
assert_eq!(size_of::<SafeHash>(), size_of::<HashUint>())
178197
}
179198

180199
impl<K, V> RawBucket<K, V> {
@@ -605,14 +624,14 @@ impl<K, V> RawTable<K, V> {
605624
return RawTable {
606625
size: 0,
607626
capacity: 0,
608-
hashes: Unique::new(EMPTY as *mut u64),
627+
hashes: Unique::new(EMPTY as *mut HashUint),
609628
marker: marker::PhantomData,
610629
};
611630
}
612631

613632
// No need for `checked_mul` before a more restrictive check performed
614633
// later in this method.
615-
let hashes_size = capacity.wrapping_mul(size_of::<u64>());
634+
let hashes_size = capacity.wrapping_mul(size_of::<HashUint>());
616635
let pairs_size = capacity.wrapping_mul(size_of::<(K, V)>());
617636

618637
// Allocating hashmaps is a little tricky. We need to allocate two
@@ -624,13 +643,13 @@ impl<K, V> RawTable<K, V> {
624643
// right is a little subtle. Therefore, calculating offsets has been
625644
// factored out into a different function.
626645
let (alignment, hash_offset, size, oflo) = calculate_allocation(hashes_size,
627-
align_of::<u64>(),
646+
align_of::<HashUint>(),
628647
pairs_size,
629648
align_of::<(K, V)>());
630649
assert!(!oflo, "capacity overflow");
631650

632651
// One check for overflow that covers calculation and rounding of size.
633-
let size_of_bucket = size_of::<u64>().checked_add(size_of::<(K, V)>()).unwrap();
652+
let size_of_bucket = size_of::<HashUint>().checked_add(size_of::<(K, V)>()).unwrap();
634653
assert!(size >=
635654
capacity.checked_mul(size_of_bucket)
636655
.expect("capacity overflow"),
@@ -641,7 +660,7 @@ impl<K, V> RawTable<K, V> {
641660
::alloc::oom()
642661
}
643662

644-
let hashes = buffer.offset(hash_offset as isize) as *mut u64;
663+
let hashes = buffer.offset(hash_offset as isize) as *mut HashUint;
645664

646665
RawTable {
647666
capacity: capacity,
@@ -652,7 +671,7 @@ impl<K, V> RawTable<K, V> {
652671
}
653672

654673
fn first_bucket_raw(&self) -> RawBucket<K, V> {
655-
let hashes_size = self.capacity * size_of::<u64>();
674+
let hashes_size = self.capacity * size_of::<HashUint>();
656675
let pairs_size = self.capacity * size_of::<(K, V)>();
657676

658677
let buffer = *self.hashes as *mut u8;
@@ -756,7 +775,7 @@ impl<K, V> RawTable<K, V> {
756775
/// this interface is safe, it's not used outside this module.
757776
struct RawBuckets<'a, K, V> {
758777
raw: RawBucket<K, V>,
759-
hashes_end: *mut u64,
778+
hashes_end: *mut HashUint,
760779

761780
// Strictly speaking, this should be &'a (K,V), but that would
762781
// require that K:'a, and we often use RawBuckets<'static...> for
@@ -802,7 +821,7 @@ impl<'a, K, V> Iterator for RawBuckets<'a, K, V> {
802821
/// the table's remaining entries. It's used in the implementation of Drop.
803822
struct RevMoveBuckets<'a, K, V> {
804823
raw: RawBucket<K, V>,
805-
hashes_end: *mut u64,
824+
hashes_end: *mut HashUint,
806825
elems_left: usize,
807826

808827
// As above, `&'a (K,V)` would seem better, but we often use
@@ -1036,10 +1055,10 @@ impl<K, V> Drop for RawTable<K, V> {
10361055
}
10371056
}
10381057

1039-
let hashes_size = self.capacity * size_of::<u64>();
1058+
let hashes_size = self.capacity * size_of::<HashUint>();
10401059
let pairs_size = self.capacity * size_of::<(K, V)>();
10411060
let (align, _, size, oflo) = calculate_allocation(hashes_size,
1042-
align_of::<u64>(),
1061+
align_of::<HashUint>(),
10431062
pairs_size,
10441063
align_of::<(K, V)>());
10451064

0 commit comments

Comments
 (0)