coip-reader 0.2.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
//! Block/section decompression with pure-Rust `ruzstd` + `lz4_flex` default,
//! optional `zstd-c` feature, and `Section 3: ZstdDicts` support.

use std::borrow::Cow;

use coip_format::Codec;

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

/// Decompress `input` according to `codec`, returning zero-copy `Cow::Borrowed` for `Codec::None`.
#[inline]
pub fn decompress<'a>(
    codec: Codec,
    input: &'a [u8],
    size_hint: Option<usize>,
) -> Result<Cow<'a, [u8]>> {
    decompress_with_dict(codec, input, size_hint, None)
}

/// Decompress `input` with an optional Zstd dictionary `(dict_crc32c, dict_bytes)`.
#[inline]
pub fn decompress_with_dict<'a>(
    codec: Codec,
    input: &'a [u8],
    size_hint: Option<usize>,
    zstd_dict: Option<(u32, &[u8])>,
) -> Result<Cow<'a, [u8]>> {
    match codec {
        Codec::None => Ok(Cow::Borrowed(input)),
        Codec::Zstd => Ok(Cow::Owned(decompress_zstd(input, size_hint, zstd_dict)?)),
        Codec::Lz4 => Ok(Cow::Owned(
            lz4_flex::decompress_size_prepended(input)
                .map_err(|e| ReaderError::Decompression(e.to_string()))?,
        )),
        other => Err(ReaderError::UnsupportedCodec(other)),
    }
}

#[cfg(feature = "zstd-c")]
#[inline]
fn decompress_zstd(
    input: &[u8],
    size_hint: Option<usize>,
    zstd_dict: Option<(u32, &[u8])>,
) -> Result<Vec<u8>> {
    use std::cell::RefCell;
    use std::collections::HashMap;

    struct ThreadDecomp {
        plain: Option<zstd::bulk::Decompressor<'static>>,
        by_dict: HashMap<u32, zstd::bulk::Decompressor<'static>>,
    }

    thread_local! {
        static DECOMP: RefCell<ThreadDecomp> = RefCell::new(ThreadDecomp {
            plain: None,
            by_dict: HashMap::new(),
        });
    }

    DECOMP.with(|cell| {
        let mut td = cell.borrow_mut();
        let cap = zstd::zstd_safe::get_frame_content_size(input)
            .ok()
            .flatten()
            .and_then(|s| usize::try_from(s).ok())
            .or(size_hint)
            .unwrap_or_else(|| input.len().saturating_mul(8).max(256));

        let decomp: &mut zstd::bulk::Decompressor<'static> = match zstd_dict {
            None => {
                if td.plain.is_none() {
                    td.plain = Some(
                        zstd::bulk::Decompressor::new()
                            .map_err(|e| ReaderError::Decompression(e.to_string()))?,
                    );
                }
                td.plain.as_mut().unwrap()
            }
            Some((dict_key, dict_bytes)) => {
                if !td.by_dict.contains_key(&dict_key) {
                    let d = zstd::bulk::Decompressor::with_dictionary(dict_bytes)
                        .map_err(|e| ReaderError::Decompression(e.to_string()))?;
                    td.by_dict.insert(dict_key, d);
                }
                td.by_dict.get_mut(&dict_key).unwrap()
            }
        };

        match decomp.decompress(input, cap.max(64)) {
            Ok(buf) => Ok(buf),
            Err(e) => match zstd_dict {
                None => zstd::stream::decode_all(input)
                    .map_err(|e2| ReaderError::Decompression(e2.to_string())),
                Some((_, dict_bytes)) => {
                    let mut dec = zstd::stream::Decoder::with_dictionary(input, dict_bytes)
                        .map_err(|_| ReaderError::Decompression(e.to_string()))?;
                    let mut out = Vec::with_capacity(cap);
                    std::io::Read::read_to_end(&mut dec, &mut out)
                        .map_err(|e2| ReaderError::Decompression(e2.to_string()))?;
                    Ok(out)
                }
            },
        }
    })
}

#[cfg(not(feature = "zstd-c"))]
#[inline]
fn decompress_zstd(
    input: &[u8],
    size_hint: Option<usize>,
    zstd_dict: Option<(u32, &[u8])>,
) -> Result<Vec<u8>> {
    use std::cell::RefCell;
    use std::collections::HashSet;

    struct ThreadRuzstd {
        decoder: ruzstd::decoding::FrameDecoder,
        loaded_dicts: HashSet<u32>,
    }

    thread_local! {
        static DECODER: RefCell<ThreadRuzstd> = RefCell::new(ThreadRuzstd {
            decoder: ruzstd::decoding::FrameDecoder::new(),
            loaded_dicts: HashSet::new(),
        });
    }

    DECODER.with(|cell| {
        let mut state = cell.borrow_mut();
        if let Some((dict_key, dict_bytes)) = zstd_dict {
            if !state.loaded_dicts.contains(&dict_key) {
                let dict = ruzstd::decoding::Dictionary::decode_dict(dict_bytes)
                    .map_err(|e| ReaderError::Decompression(e.to_string()))?;
                state
                    .decoder
                    .add_dict(dict)
                    .map_err(|e| ReaderError::Decompression(e.to_string()))?;
                state.loaded_dicts.insert(dict_key);
            }
        }

        let mut src = input;
        state
            .decoder
            .reset(&mut src)
            .map_err(|e| ReaderError::Decompression(e.to_string()))?;

        let cs = state.decoder.content_size();
        let cap = if cs > 0 {
            usize::try_from(cs).unwrap_or(256)
        } else {
            size_hint.unwrap_or_else(|| input.len().saturating_mul(4).max(256))
        };
        let mut out = Vec::with_capacity(cap);

        state
            .decoder
            .decode_blocks(&mut src, ruzstd::decoding::BlockDecodingStrategy::All)
            .map_err(|e| ReaderError::Decompression(e.to_string()))?;

        state
            .decoder
            .collect_to_writer(&mut out)
            .map_err(|e| ReaderError::Decompression(e.to_string()))?;
        Ok(out)
    })
}