http-compress 23.0.0

A high-performance async library for HTTP compression/decompression, supporting Brotli, Deflate, and Gzip algorithms. Provides both compression and decompression capabilities with optimized memory usage, ideal for HTTP clients/servers and network programming.
Documentation
use super::*;

/// Default construction for [`XxHash3_64`].
impl Default for XxHash3_64 {
    /// Builds a hasher without initializing unused streaming or prefix storage.
    ///
    /// # Returns
    ///
    /// - `Self` - The allocation-free hasher.
    #[inline(always)]
    fn default() -> Self {
        Self {
            inner: None,
            prefix: [const { MaybeUninit::uninit() }; HASH_PREFIX_CAPACITY],
            prefix_len: 0,
        }
    }
}

/// Clone implementation for [`XxHash3_64`].
impl Clone for XxHash3_64 {
    /// Clones the hasher while copying only the initialized prefix bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - A cloned hasher with identical state.
    #[inline(always)]
    fn clone(&self) -> Self {
        let Self {
            inner,
            prefix: src_prefix,
            prefix_len,
        } = self;
        let mut prefix: [MaybeUninit<u8>; HASH_PREFIX_CAPACITY] =
            [const { MaybeUninit::uninit() }; HASH_PREFIX_CAPACITY];
        let len: usize = *prefix_len;
        if inner.is_none() && len > 0 {
            // SAFETY: `0..len` was initialized in `src_prefix` and `len <= HASH_PREFIX_CAPACITY`.
            unsafe {
                ptr::copy_nonoverlapping(src_prefix.as_ptr(), prefix.as_mut_ptr(), len);
            }
        }
        Self {
            inner: inner.clone(),
            prefix,
            prefix_len: len,
        }
    }
}

/// Inherent cold helpers for [`XxHash3_64`].
impl XxHash3_64 {
    /// Transitions from the inline short-key prefix buffer to a heap-allocated streaming hasher.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The incoming bytes that overflowed `HASH_PREFIX_CAPACITY`.
    #[cold]
    #[inline(never)]
    fn spill_to_raw(&mut self, bytes: &[u8]) {
        let Self {
            inner,
            prefix,
            prefix_len,
        } = self;
        if let Some(hasher) = inner {
            hasher.write(bytes);
            return;
        }
        let current_len: usize = *prefix_len;
        let mut hasher: Box<RawHasher<&'static [u8; DEFAULT_SECRET_LENGTH]>> =
            Box::new(RawHasher::new(SecretBuffer::default()));
        // SAFETY: `0..current_len` bytes in `prefix` were initialized by prior writes.
        let initialized: &[u8] =
            unsafe { slice::from_raw_parts(prefix.as_ptr().cast::<u8>(), current_len) };
        hasher.write(initialized);
        hasher.write(bytes);
        *inner = Some(hasher);
    }
}

/// Implements `impl core::hash::Hasher for XxHash3_64`.
impl core::hash::Hasher for XxHash3_64 {
    /// Feeds bytes into the same XXH3 stream while deferring large-state setup.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The bytes to hash.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let Self {
            inner,
            prefix,
            prefix_len,
        } = self;
        let current_len: usize = *prefix_len;
        let incoming_len: usize = bytes.len();
        if inner.is_none() && incoming_len <= HASH_PREFIX_CAPACITY - current_len {
            // SAFETY: `current_len + incoming_len <= HASH_PREFIX_CAPACITY` and
            // `MaybeUninit<u8>` has identical layout to `u8`.
            unsafe {
                let src: *const u8 = bytes.as_ptr();
                let dst: *mut u8 = prefix.as_mut_ptr().add(current_len).cast::<u8>();
                if incoming_len <= 16 {
                    if incoming_len >= 8 {
                        ptr::write_unaligned(
                            dst.cast::<u64>(),
                            ptr::read_unaligned(src.cast::<u64>()),
                        );
                        ptr::write_unaligned(
                            dst.add(incoming_len - 8).cast::<u64>(),
                            ptr::read_unaligned(src.add(incoming_len - 8).cast::<u64>()),
                        );
                    } else if incoming_len >= 4 {
                        ptr::write_unaligned(
                            dst.cast::<u32>(),
                            ptr::read_unaligned(src.cast::<u32>()),
                        );
                        ptr::write_unaligned(
                            dst.add(incoming_len - 4).cast::<u32>(),
                            ptr::read_unaligned(src.add(incoming_len - 4).cast::<u32>()),
                        );
                    } else if incoming_len >= 2 {
                        ptr::write_unaligned(
                            dst.cast::<u16>(),
                            ptr::read_unaligned(src.cast::<u16>()),
                        );
                        dst.add(incoming_len - 1).write(*src.add(incoming_len - 1));
                    } else if incoming_len == 1 {
                        dst.write(*src);
                    }
                } else {
                    ptr::copy_nonoverlapping(src, dst, incoming_len);
                }
            }
            *prefix_len = current_len + incoming_len;
            return;
        }
        self.spill_to_raw(bytes);
    }

    /// Feeds a single byte into the uninitialized prefix buffer without slice copy overhead.
    ///
    /// # Arguments
    ///
    /// - `u8` - The byte to hash.
    #[inline(always)]
    fn write_u8(&mut self, value: u8) {
        let Self {
            inner,
            prefix,
            prefix_len,
        } = self;
        let current_len: usize = *prefix_len;
        if inner.is_none() && current_len < HASH_PREFIX_CAPACITY {
            prefix[current_len].write(value);
            *prefix_len = current_len + 1;
            return;
        }
        self.spill_to_raw(&[value]);
    }

    /// Feeds a `u32` in native byte order into the prefix buffer.
    ///
    /// # Arguments
    ///
    /// - `u32` - The integer value to hash.
    #[inline(always)]
    fn write_u32(&mut self, value: u32) {
        self.write(&value.to_ne_bytes());
    }

    /// Feeds a `u64` in native byte order into the prefix buffer.
    ///
    /// # Arguments
    ///
    /// - `u64` - The integer value to hash.
    #[inline(always)]
    fn write_u64(&mut self, value: u64) {
        self.write(&value.to_ne_bytes());
    }

    /// Feeds a `usize` in native byte order into the prefix buffer.
    ///
    /// # Arguments
    ///
    /// - `usize` - The integer value to hash.
    #[inline(always)]
    fn write_usize(&mut self, value: usize) {
        self.write(&value.to_ne_bytes());
    }

    /// Reports the same hash irrespective of write boundaries or prefix overflow.
    ///
    /// # Returns
    ///
    /// - `u64` - The hash of all bytes written so far.
    #[inline(always)]
    fn finish(&self) -> u64 {
        let Self {
            inner,
            prefix,
            prefix_len,
        } = self;
        match inner {
            Some(hasher) => hasher.finish(),
            None => {
                // SAFETY: `0..*prefix_len` bytes in `prefix` were initialized by prior writes.
                let initialized: &[u8] =
                    unsafe { slice::from_raw_parts(prefix.as_ptr().cast::<u8>(), *prefix_len) };
                xxhash3_64::Hasher::oneshot(initialized)
            }
        }
    }
}