wacore_binary/
util.rs

1use crate::error::{BinaryError, Result};
2use flate2::read::ZlibDecoder;
3use std::borrow::Cow;
4use std::io::Read;
5
6pub fn unpack(data: &[u8]) -> Result<Cow<'_, [u8]>> {
7    if data.is_empty() {
8        return Err(BinaryError::EmptyData);
9    }
10    let data_type = data[0];
11    let data = &data[1..];
12
13    if (data_type & 2) > 0 {
14        let mut decoder = ZlibDecoder::new(data);
15        // Pre-allocate with estimated decompressed size (typically 4-8x compressed)
16        // Min 256 bytes for small inputs, max 64KB to limit allocation for large inputs
17        let estimated_size = (data.len() * 4).clamp(256, 64 * 1024);
18        let mut decompressed = Vec::with_capacity(estimated_size);
19        decoder
20            .read_to_end(&mut decompressed)
21            .map_err(|e| BinaryError::Zlib(e.to_string()))?;
22        Ok(Cow::Owned(decompressed))
23    } else {
24        Ok(Cow::Borrowed(data))
25    }
26}