Skip to main content

http_compress/xx_hash3_64/
impl.rs

1use super::*;
2
3/// Default construction for [`XxHash3_64`].
4impl Default for XxHash3_64 {
5    /// Builds a hasher without initializing unused streaming or prefix storage.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - The allocation-free hasher.
10    #[inline(always)]
11    fn default() -> Self {
12        Self {
13            inner: None,
14            prefix: [const { MaybeUninit::uninit() }; HASH_PREFIX_CAPACITY],
15            prefix_len: 0,
16        }
17    }
18}
19
20/// Clone implementation for [`XxHash3_64`].
21impl Clone for XxHash3_64 {
22    /// Clones the hasher while copying only the initialized prefix bytes.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - A cloned hasher with identical state.
27    #[inline(always)]
28    fn clone(&self) -> Self {
29        let Self {
30            inner,
31            prefix: src_prefix,
32            prefix_len,
33        } = self;
34        let mut prefix: [MaybeUninit<u8>; HASH_PREFIX_CAPACITY] =
35            [const { MaybeUninit::uninit() }; HASH_PREFIX_CAPACITY];
36        let len: usize = *prefix_len;
37        if inner.is_none() && len > 0 {
38            // SAFETY: `0..len` was initialized in `src_prefix` and `len <= HASH_PREFIX_CAPACITY`.
39            unsafe {
40                ptr::copy_nonoverlapping(src_prefix.as_ptr(), prefix.as_mut_ptr(), len);
41            }
42        }
43        Self {
44            inner: inner.clone(),
45            prefix,
46            prefix_len: len,
47        }
48    }
49}
50
51/// Inherent cold helpers for [`XxHash3_64`].
52impl XxHash3_64 {
53    /// Transitions from the inline short-key prefix buffer to a heap-allocated streaming hasher.
54    ///
55    /// # Arguments
56    ///
57    /// - `&[u8]` - The incoming bytes that overflowed `HASH_PREFIX_CAPACITY`.
58    #[cold]
59    #[inline(never)]
60    fn spill_to_raw(&mut self, bytes: &[u8]) {
61        let Self {
62            inner,
63            prefix,
64            prefix_len,
65        } = self;
66        if let Some(hasher) = inner {
67            hasher.write(bytes);
68            return;
69        }
70        let current_len: usize = *prefix_len;
71        let mut hasher: Box<RawHasher<&'static [u8; DEFAULT_SECRET_LENGTH]>> =
72            Box::new(RawHasher::new(SecretBuffer::default()));
73        // SAFETY: `0..current_len` bytes in `prefix` were initialized by prior writes.
74        let initialized: &[u8] =
75            unsafe { slice::from_raw_parts(prefix.as_ptr().cast::<u8>(), current_len) };
76        hasher.write(initialized);
77        hasher.write(bytes);
78        *inner = Some(hasher);
79    }
80}
81
82/// Implements `impl core::hash::Hasher for XxHash3_64`.
83impl core::hash::Hasher for XxHash3_64 {
84    /// Feeds bytes into the same XXH3 stream while deferring large-state setup.
85    ///
86    /// # Arguments
87    ///
88    /// - `&[u8]` - The bytes to hash.
89    #[inline(always)]
90    fn write(&mut self, bytes: &[u8]) {
91        let Self {
92            inner,
93            prefix,
94            prefix_len,
95        } = self;
96        let current_len: usize = *prefix_len;
97        let incoming_len: usize = bytes.len();
98        if inner.is_none() && incoming_len <= HASH_PREFIX_CAPACITY - current_len {
99            // SAFETY: `current_len + incoming_len <= HASH_PREFIX_CAPACITY` and
100            // `MaybeUninit<u8>` has identical layout to `u8`.
101            unsafe {
102                let src: *const u8 = bytes.as_ptr();
103                let dst: *mut u8 = prefix.as_mut_ptr().add(current_len).cast::<u8>();
104                if incoming_len <= 16 {
105                    if incoming_len >= 8 {
106                        ptr::write_unaligned(
107                            dst.cast::<u64>(),
108                            ptr::read_unaligned(src.cast::<u64>()),
109                        );
110                        ptr::write_unaligned(
111                            dst.add(incoming_len - 8).cast::<u64>(),
112                            ptr::read_unaligned(src.add(incoming_len - 8).cast::<u64>()),
113                        );
114                    } else if incoming_len >= 4 {
115                        ptr::write_unaligned(
116                            dst.cast::<u32>(),
117                            ptr::read_unaligned(src.cast::<u32>()),
118                        );
119                        ptr::write_unaligned(
120                            dst.add(incoming_len - 4).cast::<u32>(),
121                            ptr::read_unaligned(src.add(incoming_len - 4).cast::<u32>()),
122                        );
123                    } else if incoming_len >= 2 {
124                        ptr::write_unaligned(
125                            dst.cast::<u16>(),
126                            ptr::read_unaligned(src.cast::<u16>()),
127                        );
128                        dst.add(incoming_len - 1).write(*src.add(incoming_len - 1));
129                    } else if incoming_len == 1 {
130                        dst.write(*src);
131                    }
132                } else {
133                    ptr::copy_nonoverlapping(src, dst, incoming_len);
134                }
135            }
136            *prefix_len = current_len + incoming_len;
137            return;
138        }
139        self.spill_to_raw(bytes);
140    }
141
142    /// Feeds a single byte into the uninitialized prefix buffer without slice copy overhead.
143    ///
144    /// # Arguments
145    ///
146    /// - `u8` - The byte to hash.
147    #[inline(always)]
148    fn write_u8(&mut self, value: u8) {
149        let Self {
150            inner,
151            prefix,
152            prefix_len,
153        } = self;
154        let current_len: usize = *prefix_len;
155        if inner.is_none() && current_len < HASH_PREFIX_CAPACITY {
156            prefix[current_len].write(value);
157            *prefix_len = current_len + 1;
158            return;
159        }
160        self.spill_to_raw(&[value]);
161    }
162
163    /// Feeds a `u32` in native byte order into the prefix buffer.
164    ///
165    /// # Arguments
166    ///
167    /// - `u32` - The integer value to hash.
168    #[inline(always)]
169    fn write_u32(&mut self, value: u32) {
170        self.write(&value.to_ne_bytes());
171    }
172
173    /// Feeds a `u64` in native byte order into the prefix buffer.
174    ///
175    /// # Arguments
176    ///
177    /// - `u64` - The integer value to hash.
178    #[inline(always)]
179    fn write_u64(&mut self, value: u64) {
180        self.write(&value.to_ne_bytes());
181    }
182
183    /// Feeds a `usize` in native byte order into the prefix buffer.
184    ///
185    /// # Arguments
186    ///
187    /// - `usize` - The integer value to hash.
188    #[inline(always)]
189    fn write_usize(&mut self, value: usize) {
190        self.write(&value.to_ne_bytes());
191    }
192
193    /// Reports the same hash irrespective of write boundaries or prefix overflow.
194    ///
195    /// # Returns
196    ///
197    /// - `u64` - The hash of all bytes written so far.
198    #[inline(always)]
199    fn finish(&self) -> u64 {
200        let Self {
201            inner,
202            prefix,
203            prefix_len,
204        } = self;
205        match inner {
206            Some(hasher) => hasher.finish(),
207            None => {
208                // SAFETY: `0..*prefix_len` bytes in `prefix` were initialized by prior writes.
209                let initialized: &[u8] =
210                    unsafe { slice::from_raw_parts(prefix.as_ptr().cast::<u8>(), *prefix_len) };
211                xxhash3_64::Hasher::oneshot(initialized)
212            }
213        }
214    }
215}