a2s-protocol 0.1.0

A protocol core for building A2S server query clients
Documentation
use bzip2::read::BzDecoder;
use crc32fast::Hasher;
use std::io::Read;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    #[error("decompressed size mismatch: expected {expected} bytes, got {actual}")]
    SizeMismatch { expected: usize, actual: usize },
    #[error("checksum mismatch: expected {expected}, got {actual}")]
    CrcMismatch { expected: u32, actual: u32 },
    #[error("uncompressed payload exceeds the maximum allowed size")]
    SizeTooLarge
}

const MAX_UNCOMPRESSED_SIZE: usize = 1024 * 1024 * 16;

pub fn decode(
    compressed_payload: &[u8],
    expected_size: usize,
    expected_crc: u32,
) -> Result<Vec<u8>, Error> {
    if expected_size > MAX_UNCOMPRESSED_SIZE {
        return Err(Error::SizeTooLarge);
    }

    let mut decompressed = Vec::with_capacity(expected_size);

    let mut decoder = BzDecoder::new(compressed_payload);
    decoder.read_to_end(&mut decompressed)?;

    if decompressed.len() != expected_size {
        return Err(Error::SizeMismatch {
            expected: expected_size,
            actual: decompressed.len(),
        });
    }

    let mut hasher = Hasher::new();
    hasher.update(&decompressed);
    let actual_crc = hasher.finalize();

    if actual_crc != expected_crc {
        return Err(Error::CrcMismatch {
            expected: expected_crc,
            actual: actual_crc,
        });
    }

    Ok(decompressed)
}