1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#![allow(unsafe_code)]
//! This module encapsulates the `unsafe` access to `hashbrown::raw::RawTable`,
//! mostly in dealing with its bucket "pointers".

use super::{equivalent, get_hash, Bucket, HashValue, IndexMapCore};
use hashbrown::raw::RawTable;

type RawBucket = hashbrown::raw::Bucket<usize>;

/// Inserts many entries into a raw table without reallocating.
///
/// ***Panics*** if there is not sufficient capacity already.
pub(super) fn insert_bulk_no_grow<K, V>(indices: &mut RawTable<usize>, entries: &[Bucket<K, V>]) {
    assert!(indices.capacity() - indices.len() >= entries.len());
    for entry in entries {
        // SAFETY: we asserted that sufficient capacity exists for all entries.
        unsafe {
            indices.insert_no_grow(entry.hash.get(), indices.len());
        }
    }
}

#[cfg(feature = "test_debug")]
pub(super) struct DebugIndices<'a>(pub &'a RawTable<usize>);

#[cfg(feature = "test_debug")]
impl core::fmt::Debug for DebugIndices<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // SAFETY: we're not letting any of the buckets escape this function
        let indices = unsafe { self.0.iter().map(|raw_bucket| *raw_bucket.as_ref()) };
        f.debug_list().entries(indices).finish()
    }
}

impl<K, V> IndexMapCore<K, V> {
    /// Sweep the whole table to erase indices start..end
    pub(super) fn erase_indices_sweep(&mut self, start: usize, end: usize) {
        // SAFETY: we're not letting any of the buckets escape this function
        unsafe {
            let offset = end - start;
            for bucket in self.indices.iter() {
                let i = bucket.as_mut();
                if *i >= end {
                    *i -= offset;
                } else if *i >= start {
                    self.indices.erase(bucket);
                }
            }
        }
    }

    /// Search for a key in the table and return `Ok(entry_index)` if found.
    /// Otherwise, insert the key and return `Err(new_index)`.
    ///
    /// Note that hashbrown may resize the table to reserve space for insertion,
    /// even before checking if it's already present, so this is somewhat biased
    /// towards new items.
    pub(crate) fn find_or_insert(&mut self, hash: HashValue, key: &K) -> Result<usize, usize>
    where
        K: Eq,
    {
        let hash = hash.get();
        let eq = equivalent(key, &self.entries);
        let hasher = get_hash(&self.entries);
        // SAFETY: We're not mutating between find and read/insert.
        unsafe {
            match self.indices.find_or_find_insert_slot(hash, eq, hasher) {
                Ok(raw_bucket) => Ok(*raw_bucket.as_ref()),
                Err(slot) => {
                    let index = self.indices.len();
                    self.indices.insert_in_slot(hash, slot, index);
                    Err(index)
                }
            }
        }
    }

    pub(super) fn raw_entry(
        &mut self,
        hash: HashValue,
        mut is_match: impl FnMut(&K) -> bool,
    ) -> Result<RawTableEntry<'_, K, V>, &mut Self> {
        let entries = &*self.entries;
        let eq = move |&i: &usize| is_match(&entries[i].key);
        match self.indices.find(hash.get(), eq) {
            // SAFETY: The bucket is valid because we *just* found it in this map.
            Some(raw_bucket) => Ok(unsafe { RawTableEntry::new(self, raw_bucket) }),
            None => Err(self),
        }
    }

    pub(super) fn index_raw_entry(&mut self, index: usize) -> Option<RawTableEntry<'_, K, V>> {
        let hash = self.entries.get(index)?.hash;
        let raw_bucket = self.indices.find(hash.get(), move |&i| i == index)?;
        // SAFETY: The bucket is valid because we *just* found it in this map.
        Some(unsafe { RawTableEntry::new(self, raw_bucket) })
    }

    pub(super) fn indices_mut(&mut self) -> impl Iterator<Item = &mut usize> {
        // SAFETY: we're not letting any of the buckets escape this function,
        // only the item references that are appropriately bound to `&mut self`.
        unsafe { self.indices.iter().map(|bucket| bucket.as_mut()) }
    }
}

/// A view into an occupied raw entry in an `IndexMap`.
// SAFETY: The lifetime of the map reference also constrains the raw bucket,
// which is essentially a raw pointer into the map indices.
pub(super) struct RawTableEntry<'a, K, V> {
    map: &'a mut IndexMapCore<K, V>,
    raw_bucket: RawBucket,
}

// `hashbrown::raw::Bucket` is only `Send`, not `Sync`.
// SAFETY: `&self` only accesses the bucket to read it.
unsafe impl<K: Sync, V: Sync> Sync for RawTableEntry<'_, K, V> {}

impl<'a, K, V> RawTableEntry<'a, K, V> {
    /// The caller must ensure that the `raw_bucket` is valid in the given `map`,
    /// and then we hold the `&mut` reference for exclusive access.
    #[inline]
    unsafe fn new(map: &'a mut IndexMapCore<K, V>, raw_bucket: RawBucket) -> Self {
        Self { map, raw_bucket }
    }

    /// Return the index of the key-value pair
    #[inline]
    pub(super) fn index(&self) -> usize {
        // SAFETY: we have `&mut map` keeping the bucket stable
        unsafe { *self.raw_bucket.as_ref() }
    }

    #[inline]
    pub(super) fn bucket(&self) -> &Bucket<K, V> {
        &self.map.entries[self.index()]
    }

    #[inline]
    pub(super) fn bucket_mut(&mut self) -> &mut Bucket<K, V> {
        let index = self.index();
        &mut self.map.entries[index]
    }

    #[inline]
    pub(super) fn into_bucket(self) -> &'a mut Bucket<K, V> {
        let index = self.index();
        &mut self.map.entries[index]
    }

    /// Remove the index from indices, leaving the actual entries to the caller.
    pub(super) fn remove_index(self) -> (&'a mut IndexMapCore<K, V>, usize) {
        // SAFETY: This is safe because it can only happen once (self is consumed)
        // and map.indices have not been modified since entry construction
        let (index, _slot) = unsafe { self.map.indices.remove(self.raw_bucket) };
        (self.map, index)
    }

    /// Take no action, just return the index and the original map reference.
    #[inline]
    pub(super) fn into_inner(self) -> (&'a mut IndexMapCore<K, V>, usize) {
        let index = self.index();
        (self.map, index)
    }
}