mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;

/// Seed fixed by the CurseForge file fingerprint specification
/// (<https://docs.curseforge.com/rest-api/#get-fingerprints-matches>).
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)
}

/// Constant-memory streaming MurmurHash2 (32-bit, seed `1`) hasher following the
/// CurseForge file fingerprint specification.
///
/// Because MurmurHash2 seeds its initial state with `1 ^ filtered_len`, the caller must
/// provide the total number of non-whitespace bytes (`filtered_len`) up front. For files
/// or seekable streams, prefer [`cf_fingerprint_file`] or [`cf_fingerprint_read_seek`].
#[derive(Clone, Debug)]
pub struct Murmur2Hasher {
    h: u32,
    tail: [u8; 4],
    tail_len: usize,
}

impl Murmur2Hasher {
    /// Creates a new CurseForge MurmurHash2 hasher initialized with `filtered_len`
    /// (the total byte count after stripping `\t`, `\n`, `\r`, and `' '`).
    pub const fn new(filtered_len: u32) -> Self {
        Self {
            h: CF_MURMUR2_SEED ^ filtered_len,
            tail: [0; 4],
            tail_len: 0,
        }
    }

    /// Feeds raw bytes into the hasher, automatically skipping CurseForge whitespace
    /// (`\t`, `\n`, `\r`, `' '`).
    pub fn update(&mut self, bytes: &[u8]) {
        for &b in bytes {
            if is_cf_whitespace(b) {
                continue;
            }
            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;
    }

    /// Finalizes the hash and returns the 32-bit CurseForge fingerprint.
    pub const fn finish(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
    }
}

fn hash_reader<R: Read>(reader: &mut R, filtered_len: u32, buf: &mut [u8]) -> io::Result<u32> {
    let mut hasher = Murmur2Hasher::new(filtered_len);
    loop {
        let n = reader.read(buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(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`.
pub fn cf_fingerprint(bytes: &[u8]) -> u32 {
    let filtered_len = bytes.iter().filter(|&&b| !is_cf_whitespace(b)).count() as u32;
    let mut hasher = Murmur2Hasher::new(filtered_len);
    hasher.update(bytes);
    hasher.finish()
}

/// Computes the CurseForge Murmur2 file fingerprint from a [`Read`] source using constant
/// 64 KiB memory when `filtered_len` (non-whitespace byte count) is already known.
pub fn cf_fingerprint_with_len<R: Read>(mut reader: R, filtered_len: u32) -> io::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).
pub fn cf_fingerprint_read_seek<R: Read + Seek>(mut reader: R) -> io::Result<u32> {
    let start = reader.stream_position()?;
    let mut buf = vec![0_u8; STREAM_BUF_SIZE];
    let mut filtered_len: u64 = 0;
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        filtered_len += buf[..n].iter().filter(|&&b| !is_cf_whitespace(b)).count() as u64;
    }

    reader.seek(SeekFrom::Start(start))?;
    hash_reader(&mut reader, filtered_len as u32, &mut buf)
}

/// Computes the CurseForge Murmur2 file fingerprint for a file on disk using constant
/// 64 KiB memory.
pub fn cf_fingerprint_file(path: impl AsRef<Path>) -> io::Result<u32> {
    cf_fingerprint_read_seek(File::open(path)?)
}

/// Computes the CurseForge Murmur2 file fingerprint from any non-seekable [`Read`] source.
///
/// Because MurmurHash2 requires the filtered byte length up front, non-seekable readers must
/// buffer stripped bytes in memory. For large files on disk or seekable streams, prefer
/// [`cf_fingerprint_file`], [`cf_fingerprint_read_seek`], or [`cf_fingerprint_with_len`].
pub fn cf_fingerprint_reader<R: Read>(mut reader: R) -> io::Result<u32> {
    let mut normalized = Vec::new();
    let mut buf = vec![0_u8; STREAM_BUF_SIZE];
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        normalized.extend(buf[..n].iter().copied().filter(|&b| !is_cf_whitespace(b)));
    }
    let mut hasher = Murmur2Hasher::new(normalized.len() as u32);
    hasher.update(&normalized);
    Ok(hasher.finish())
}