mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Streaming Murmur2 file fingerprint calculation compatible with CurseForge mod matching.

use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;

use crate::error::{Error, Result};

/// Seed fixed by the CurseForge file fingerprint specification.
const CF_MURMUR2_SEED: u32 = 1;
const MURMUR2_M: u32 = 0x5bd1_e995;
const MURMUR2_R: u32 = 24;
const STREAM_BUF_SIZE: usize = 64 * 1024;

#[inline]
const fn is_cf_whitespace(byte: u8) -> bool {
    matches!(byte, 9 | 10 | 13 | 32)
}

/// Streaming Murmur2 hasher matching the CurseForge file fingerprint specification.
///
/// The CurseForge variant mixes the filtered (non-whitespace) byte length into the initial hash
/// state (`1 ^ filtered_len`), so `filtered_len` must be known up front (for example via
/// [`filtered_len`] or [`filtered_len_reader`]).
///
/// ```
/// use mcapi::curseforge::murmur2::{Murmur2Hasher, filtered_len, fingerprint};
///
/// let data = b"hello world";
/// let len = u32::try_from(filtered_len(data)).unwrap();
/// let mut hasher = Murmur2Hasher::new(len);
/// hasher.update(b"hello ");
/// hasher.update(b"world");
/// assert_eq!(hasher.finish()?, fingerprint(data));
/// # Ok::<(), mcapi::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct Murmur2Hasher {
    h: u32,
    expected_len: u32,
    fed_len: u64,
    tail: [u8; 4],
    tail_len: usize,
}

impl Murmur2Hasher {
    /// Creates a new [`Murmur2Hasher`] expecting `filtered_len` non-whitespace bytes.
    ///
    /// Note that `filtered_len` is the count of bytes remaining after stripping ASCII whitespace
    /// (`\t`, `\n`, `\r`, `' '`), as computed by [`filtered_len`] or [`filtered_len_reader`],
    /// not the raw byte length of the input.
    #[must_use]
    pub const fn new(filtered_len: u32) -> Self {
        Self {
            h: CF_MURMUR2_SEED ^ filtered_len,
            expected_len: filtered_len,
            fed_len: 0,
            tail: [0; 4],
            tail_len: 0,
        }
    }

    /// Feeds a chunk of raw bytes into the hasher, skipping CurseForge ASCII whitespace bytes.
    pub fn update(&mut self, bytes: &[u8]) {
        for &b in bytes {
            if is_cf_whitespace(b) {
                continue;
            }
            self.fed_len += 1;
            self.tail[self.tail_len] = b;
            self.tail_len += 1;
            if self.tail_len == 4 {
                self.mix_block(self.tail);
                self.tail_len = 0;
            }
        }
    }

    #[inline]
    fn mix_block(&mut self, block: [u8; 4]) {
        let mut k = u32::from_le_bytes(block);
        k = k.wrapping_mul(MURMUR2_M);
        k ^= k >> MURMUR2_R;
        k = k.wrapping_mul(MURMUR2_M);
        self.h = self.h.wrapping_mul(MURMUR2_M);
        self.h ^= k;
    }

    const fn finish_inner(mut self) -> u32 {
        match self.tail_len {
            3 => {
                self.h ^= (self.tail[2] as u32) << 16;
                self.h ^= (self.tail[1] as u32) << 8;
                self.h ^= self.tail[0] as u32;
                self.h = self.h.wrapping_mul(MURMUR2_M);
            }
            2 => {
                self.h ^= (self.tail[1] as u32) << 8;
                self.h ^= self.tail[0] as u32;
                self.h = self.h.wrapping_mul(MURMUR2_M);
            }
            1 => {
                self.h ^= self.tail[0] as u32;
                self.h = self.h.wrapping_mul(MURMUR2_M);
            }
            _ => {}
        }
        self.h ^= self.h >> 13;
        self.h = self.h.wrapping_mul(MURMUR2_M);
        self.h ^= self.h >> 15;
        self.h
    }

    /// Finalizes the hash and returns the 32-bit CurseForge fingerprint.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] if the total number of non-whitespace bytes fed via
    /// [`update`](Self::update) or [`Write::write`] does not equal `filtered_len`.
    pub fn finish(self) -> Result<u32> {
        if self.fed_len != u64::from(self.expected_len) {
            return Err(Error::InvalidInput(format!(
                "Murmur2Hasher expected {} non-whitespace bytes, got {}",
                self.expected_len, self.fed_len
            )));
        }
        Ok(self.finish_inner())
    }
}

impl Write for Murmur2Hasher {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.update(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Counts non-whitespace bytes in `bytes` according to the CurseForge fingerprint specification
/// (stripping `\t`, `\n`, `\r`, and `' '`).
#[must_use]
pub fn filtered_len(bytes: &[u8]) -> usize {
    bytes.iter().filter(|&&b| !is_cf_whitespace(b)).count()
}

fn count_filtered_reader<R: Read>(reader: &mut R, buf: &mut [u8]) -> Result<u32> {
    let mut total: u64 = 0;
    loop {
        let n = reader.read(buf)?;
        if n == 0 {
            break;
        }
        total += filtered_len(&buf[..n]) as u64;
    }

    u32::try_from(total).map_err(|_| {
        Error::InvalidInput(format!(
            "CurseForge fingerprint input exceeds 4 GiB limit ({total} filtered bytes)"
        ))
    })
}

/// Counts non-whitespace bytes from a [`Read`] source using constant 64 KiB memory.
///
/// # Errors
///
/// Returns [`Error::Io`] on stream read failures, or [`Error::InvalidInput`] if the
/// filtered non-whitespace byte count exceeds `u32::MAX` (4 GiB).
pub fn filtered_len_reader<R: Read>(mut reader: R) -> Result<u32> {
    let mut buf = vec![0_u8; STREAM_BUF_SIZE];
    count_filtered_reader(&mut reader, &mut buf)
}

fn hash_reader<R: Read>(reader: &mut R, filtered_len: u32, buf: &mut [u8]) -> Result<u32> {
    let mut hasher = Murmur2Hasher::new(filtered_len);
    loop {
        let n = reader.read(buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    hasher.finish()
}

/// Computes the CurseForge Murmur2 file fingerprint for raw file bytes without allocation.
///
/// Per CurseForge specification, ASCII whitespace bytes (`\t` = 9, `\n` = 10,
/// `\r` = 13, `' '` = 32) are stripped before hashing with seed `1`.
///
/// ```
/// use mcapi::curseforge::fingerprint;
///
/// assert_eq!(fingerprint(b"hello world"), fingerprint(b"helloworld"));
/// ```
///
/// # Panics
///
/// Panics if the filtered byte count exceeds `u32::MAX` (4 GiB).
#[must_use]
pub fn fingerprint(bytes: &[u8]) -> u32 {
    let len = filtered_len(bytes);
    let len = u32::try_from(len).expect("CurseForge fingerprint input exceeds 4 GiB limit");
    let mut hasher = Murmur2Hasher::new(len);
    hasher.update(bytes);
    hasher.finish_inner()
}

/// Computes the CurseForge Murmur2 file fingerprint from a [`Read`] source in a single pass
/// using constant 64 KiB memory, given a pre-computed `filtered_len`.
///
/// Useful when reading non-seekable streams (such as `zip::ZipFile`) or when `filtered_len`
/// has already been counted in an earlier pass.
///
/// # Errors
///
/// Returns [`Error::Io`] on stream read failures, or [`Error::InvalidInput`] if the actual
/// number of non-whitespace bytes read from `reader` does not match `filtered_len`.
pub fn fingerprint_reader_with_len<R: Read>(mut reader: R, filtered_len: u32) -> Result<u32> {
    let mut buf = vec![0_u8; STREAM_BUF_SIZE];
    hash_reader(&mut reader, filtered_len, &mut buf)
}

/// Computes the CurseForge Murmur2 file fingerprint from a [`Read`] + [`Seek`] source
/// using constant 64 KiB memory (two sequential passes from the current stream position).
///
/// # Errors
///
/// Returns [`Error::Io`] on stream read/seek failures, or [`Error::InvalidInput`] if the
/// filtered non-whitespace byte count exceeds `u32::MAX` (4 GiB).
pub fn fingerprint_reader<R: Read + Seek>(mut reader: R) -> Result<u32> {
    let start = reader.stream_position()?;
    let mut buf = vec![0_u8; STREAM_BUF_SIZE];
    let filtered_len = count_filtered_reader(&mut reader, &mut buf)?;
    reader.seek(SeekFrom::Start(start))?;
    hash_reader(&mut reader, filtered_len, &mut buf)
}

/// Computes the CurseForge Murmur2 file fingerprint for a file on disk using constant
/// 64 KiB memory.
///
/// # Errors
///
/// Returns [`Error::Io`] if opening or reading `path` fails, or [`Error::InvalidInput`] if
/// the filtered non-whitespace byte count exceeds `u32::MAX` (4 GiB).
pub fn fingerprint_file(path: impl AsRef<Path>) -> Result<u32> {
    fingerprint_reader(File::open(path)?)
}