logo
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! A helper type that archives index data for hashed collections using
//! [compress, hash and displace](http://cmph.sourceforge.net/papers/esa09.pdf).

use crate::{Archive, Archived, RelPtr};
use core::{
    fmt,
    hash::{Hash, Hasher},
    slice,
};

/// The hash builder for archived hash indexes.
pub use seahash::SeaHasher as HashBuilder;

#[cfg(feature = "validation")]
pub mod validation;

/// An archived hash index.
#[cfg_attr(feature = "strict", repr(C))]
pub struct ArchivedHashIndex {
    len: Archived<usize>,
    displace: RelPtr<Archived<u32>>,
}

impl ArchivedHashIndex {
    /// Gets the number of items in the hash index.
    #[inline]
    pub const fn len(&self) -> usize {
        from_archived!(self.len) as usize
    }

    #[inline]
    fn make_hasher() -> HashBuilder {
        HashBuilder::with_seeds(
            0x08576fb6170b5f5f,
            0x587775eeb84a7e46,
            0xac701115428ee569,
            0x910feb91b92bb1cd,
        )
    }

    /// Gets the hasher for this hash index. The hasher for all archived hash indexes is the same
    /// for reproducibility.
    #[inline]
    pub fn hasher(&self) -> HashBuilder {
        Self::make_hasher()
    }

    #[inline]
    fn displace_slice(&self) -> &[Archived<u32>] {
        unsafe { slice::from_raw_parts(self.displace.as_ptr(), self.len()) }
    }

    #[inline]
    fn displace(&self, index: usize) -> u32 {
        from_archived!(self.displace_slice()[index])
    }

    /// Returns the index where a key may be located in the hash index.
    ///
    /// The hash index does not have access to the keys used to build it, so the key at the returned
    /// index must be checked for equality.
    #[inline]
    pub fn index<K: Hash + ?Sized>(&self, k: &K) -> Option<usize> {
        let mut hasher = self.hasher();
        k.hash(&mut hasher);
        let displace_index = hasher.finish() % self.len() as u64;
        let displace = self.displace(displace_index as usize);

        if displace == u32::MAX {
            None
        } else if displace & 0x80_00_00_00 == 0 {
            Some(displace as usize)
        } else {
            let mut hasher = self.hasher();
            displace.hash(&mut hasher);
            k.hash(&mut hasher);
            let index = hasher.finish() % self.len() as u64;
            Some(index as usize)
        }
    }

    /// Returns whether there are no items in the hash index.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Resolves an archived hash index from a given length and parameters.
    ///
    /// # Safety
    ///
    /// - `len` must be the number of elements in the hash index
    /// - `pos` must be the position of `out` within the archive
    /// - `resolver` must be the result of building and serializing a hash index
    #[inline]
    pub unsafe fn resolve_from_len(
        len: usize,
        pos: usize,
        resolver: HashIndexResolver,
        out: *mut Self,
    ) {
        let (fp, fo) = out_field!(out.len);
        len.resolve(pos + fp, (), fo);

        let (fp, fo) = out_field!(out.displace);
        RelPtr::emplace(pos + fp, resolver.displace_pos, fo);
    }
}

#[cfg(feature = "alloc")]
const _: () = {
    use crate::{
        ser::{ScratchSpace, Serializer},
        ScratchVec,
    };
    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;
    use core::{
        cmp::Reverse,
        mem::{size_of, MaybeUninit},
    };

    impl ArchivedHashIndex {
        /// Builds and serializes a hash index from an iterator of key-value pairs.
        ///
        /// # Safety
        ///
        /// - The keys returned by the iterator must be unique.
        /// - `entries` must have a capacity of `iter.len()` entries.
        #[allow(clippy::type_complexity)]
        pub unsafe fn build_and_serialize<'a, K, V, S, I>(
            iter: I,
            serializer: &mut S,
            entries: &mut ScratchVec<MaybeUninit<(&'a K, &'a V)>>,
        ) -> Result<HashIndexResolver, S::Error>
        where
            K: 'a + Hash,
            V: 'a,
            S: Serializer + ScratchSpace + ?Sized,
            I: ExactSizeIterator<Item = (&'a K, &'a V)>,
        {
            let len = iter.len();

            let mut bucket_size = ScratchVec::new(serializer, len)?;
            for _ in 0..len {
                bucket_size.push(0u32);
            }

            let mut displaces = ScratchVec::new(serializer, len)?;

            for (key, value) in iter {
                let mut hasher = Self::make_hasher();
                key.hash(&mut hasher);
                let displace = (hasher.finish() % len as u64) as u32;
                displaces.push((displace, (key, value)));
                bucket_size[displace as usize] += 1;
            }

            displaces
                .sort_by_key(|&(displace, _)| (Reverse(bucket_size[displace as usize]), displace));

            let mut occupied = ScratchVec::new(serializer, len)?;
            for _ in 0..len {
                occupied.push(false);
            }

            let mut displacements = ScratchVec::new(serializer, len)?;
            for _ in 0..len {
                displacements.push(to_archived!(u32::MAX));
            }

            let mut first_empty = 0;
            let mut assignments = Vec::with_capacity(8);

            let mut start = 0;
            while start < displaces.len() {
                let displace = displaces[start].0;
                let bucket_size = bucket_size[displace as usize] as usize;
                let end = start + bucket_size;
                let bucket = &displaces[start..end];
                start = end;

                if bucket_size > 1 {
                    'find_seed: for seed in 0x80_00_00_00u32..=0xFF_FF_FF_FFu32 {
                        let mut base_hasher = Self::make_hasher();
                        seed.hash(&mut base_hasher);

                        assignments.clear();

                        for &(_, (key, _)) in bucket.iter() {
                            let mut hasher = base_hasher;
                            key.hash(&mut hasher);
                            let index = (hasher.finish() % len as u64) as u32;
                            if occupied[index as usize] || assignments.contains(&index) {
                                continue 'find_seed;
                            } else {
                                assignments.push(index);
                            }
                        }

                        for i in 0..bucket_size {
                            occupied[assignments[i] as usize] = true;
                            entries[assignments[i] as usize]
                                .as_mut_ptr()
                                .write(bucket[i].1);
                        }
                        displacements[displace as usize] = to_archived!(seed);
                        break;
                    }
                } else {
                    let offset = occupied[first_empty..]
                        .iter()
                        .position(|value| !value)
                        .unwrap();
                    first_empty += offset;
                    occupied[first_empty] = true;
                    entries[first_empty].as_mut_ptr().write(bucket[0].1);
                    displacements[displace as usize] = to_archived!(first_empty as u32);
                    first_empty += 1;
                }
            }

            // Write displacements
            let displace_pos = serializer.align_for::<Archived<u32>>()?;
            let displacements_slice = slice::from_raw_parts(
                displacements.as_ptr().cast::<u8>(),
                len * size_of::<Archived<u32>>(),
            );
            serializer.write(displacements_slice)?;

            // Free scratch vecs
            displacements.free(serializer)?;
            occupied.free(serializer)?;
            displaces.free(serializer)?;
            bucket_size.free(serializer)?;

            Ok(HashIndexResolver { displace_pos })
        }
    }
};

impl fmt::Debug for ArchivedHashIndex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.displace_slice()).finish()
    }
}

/// The resolver for an archived hash index.
pub struct HashIndexResolver {
    displace_pos: usize,
}