Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

shims/zstd/src/lib.rs

//! The part of the `zstd` crate's API that arrow-ipc 60, parquet 60, apache-avro 0.22 and
//! iceberg-rust call (`bulk::Compressor`, `bulk::Decompressor` with their `*_to_buffer`
//! forms, `compression_level_range`, `Encoder` / `Decoder` over a writer or reader,
//! `stream::decode_all`, `zstd_safe::{CompressionLevel, DCtx::in_size, compress_bound,
//! get_frame_content_size}`), on [mzstd](https://crates.io/crates/mzstd): Zstandard in safe
//! Rust, no C library. The stream forms hold the whole input and write one frame at
//! `finish` (Iceberg's and Avro's blocks are small and whole).
//!
//! The workspace patches crates.io's `zstd` with this package, so nothing in the build
//! compiles C.

use std::io;
use std::marker::PhantomData;
use std::ops::RangeInclusive;

/// The names arrow-ipc takes from `zstd::zstd_safe`.
pub mod zstd_safe {
    /// A compression level, as the C library numbers them.
    pub type CompressionLevel = i32;

    /// A decompression context: only its input size is asked for.
    pub struct DCtx;

    impl DCtx {
        /// The input buffer size a reader of compressed bytes is given (the C library's
        /// `ZSTD_DStreamInSize`: a block plus its header).
        pub fn in_size() -> usize {
            (1 << 17) + 3
        }
    }

    /// The largest frame `size` bytes can compress to (the C library's `ZSTD_COMPRESSBOUND`).
    pub fn compress_bound(size: usize) -> usize {
        let small = if size < (128 << 10) {
            ((128 << 10) - size) >> 11
        } else {
            0
        };
        size + (size >> 8) + small
    }

    /// The frame header did not hold a size: too short, not a Zstandard frame.
    #[derive(Debug)]
    pub struct ContentSizeError;

    impl std::fmt::Display for ContentSizeError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("not a Zstandard frame header")
        }
    }

    impl std::error::Error for ContentSizeError {}

    /// The content size a frame's header gives (`None` when the frame does not say).
    pub fn get_frame_content_size(src: &[u8]) -> Result<Option<u64>, ContentSizeError> {
        if src.len() < 5 || src[..4] != [0x28, 0xB5, 0x2F, 0xFD] {
            return Err(ContentSizeError);
        }
        let fhd = src[4];
        let single = fhd & 0x20 != 0;
        let dict = [0usize, 1, 2, 4][(fhd & 3) as usize];
        let fcs = match fhd >> 6 {
            0 if single => 1,
            0 => 0,
            1 => 2,
            2 => 4,
            _ => 8,
        };
        let at = 5 + usize::from(!single) + dict;
        let field = src.get(at..at + fcs).ok_or(ContentSizeError)?;
        let mut v = 0u64;
        for (i, b) in field.iter().enumerate() {
            v |= u64::from(*b) << (8 * i);
        }
        Ok(match fcs {
            0 => None,
            2 => Some(v + 256),
            _ => Some(v),
        })
    }
}

/// Where a `*_to_buffer` call writes: a vector, or a cursor over one (at its position).
pub trait WriteBuf {
    /// Put `bytes` at the write position.
    fn put(&mut self, bytes: &[u8]);
}

impl WriteBuf for Vec<u8> {
    fn put(&mut self, bytes: &[u8]) {
        self.extend_from_slice(bytes);
    }
}

impl WriteBuf for io::Cursor<&mut Vec<u8>> {
    fn put(&mut self, bytes: &[u8]) {
        let at = self.position() as usize;
        let v = self.get_mut();
        v.truncate(at);
        v.extend_from_slice(bytes);
        self.set_position((at + bytes.len()) as u64);
    }
}

fn level_config(level: zstd_safe::CompressionLevel) -> io::Result<mzstd::EncoderConfig> {
    // the C library's level 0 is its default level
    let level = if level == 0 { 3 } else { level };
    let level = mzstd::Level::try_from(level).map_err(other)?;
    Ok(mzstd::EncoderConfig::default().with_level(level))
}

/// A writer that compresses what it is given into one frame, written to `W` at
/// [`Encoder::finish`].
pub struct Encoder<'a, W: io::Write> {
    out: W,
    held: Vec<u8>,
    config: mzstd::EncoderConfig,
    _dictionary: PhantomData<&'a [u8]>,
}

impl<W: io::Write> Encoder<'static, W> {
    /// An encoder at `level` (0: the default level) writing to `out`.
    pub fn new(out: W, level: zstd_safe::CompressionLevel) -> io::Result<Self> {
        Ok(Self {
            out,
            held: Vec::new(),
            config: level_config(level)?,
            _dictionary: PhantomData,
        })
    }
}

impl<W: io::Write> Encoder<'_, W> {
    /// Whether the frame carries a checksum of its content.
    pub fn include_checksum(&mut self, on: bool) -> io::Result<()> {
        self.config = self.config.with_checksum(on);
        Ok(())
    }

    /// The content's size, told ahead (the frame states the size it compresses anyway).
    pub fn set_pledged_src_size(&mut self, _size: Option<u64>) -> io::Result<()> {
        Ok(())
    }

    /// Compress what was written as one frame into the writer, and give the writer back.
    pub fn finish(mut self) -> io::Result<W> {
        let frame = mzstd::Compressor::new(self.config)
            .map_err(other)?
            .compress(&self.held)
            .map_err(other)?;
        self.out.write_all(&frame)?;
        Ok(self.out)
    }
}

impl<W: io::Write> io::Write for Encoder<'_, W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.held.extend_from_slice(buf);
        Ok(buf.len())
    }

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

/// A reader of the content of the frames `R` gives (read whole at the first read).
pub struct Decoder<'a, R: io::Read> {
    from: Option<R>,
    content: io::Cursor<Vec<u8>>,
    _dictionary: PhantomData<&'a [u8]>,
}

impl<R: io::Read> Decoder<'static, R> {
    /// A decoder of the frames `from` gives.
    pub fn new(from: R) -> io::Result<Self> {
        Ok(Self {
            from: Some(from),
            content: io::Cursor::new(Vec::new()),
            _dictionary: PhantomData,
        })
    }
    /// A decoder of the frames a buffered reader gives (the same as [`Decoder::new`] here).
    pub fn with_buffer(from: R) -> io::Result<Self> {
        Self::new(from)
    }
}

impl<R: io::Read> io::Read for Decoder<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Some(mut from) = self.from.take() {
            let mut frames = Vec::new();
            from.read_to_end(&mut frames)?;
            self.content = io::Cursor::new(decode_all(&frames[..])?);
        }
        self.content.read(buf)
    }
}

/// The content of all the frames `from` gives.
pub fn decode_all<R: io::Read>(mut from: R) -> io::Result<Vec<u8>> {
    let mut frames = Vec::new();
    from.read_to_end(&mut frames)?;
    let limits = mzstd::DecodeLimits::DEFAULT.with_max_output_bytes(None);
    mzstd::Decompressor::new(mzstd::DecoderConfig::default().with_limits(limits))
        .decompress(&frames)
        .map_err(other)
}

/// The stream forms, by the names the `zstd` crate gives them there too.
pub mod stream {
    pub use super::{Decoder, Encoder, decode_all};

    /// The reading forms (`zstd::stream::read`).
    pub mod read {
        pub use super::super::Decoder;
    }

    /// The writing forms (`zstd::stream::write`).
    pub mod write {
        pub use super::super::Encoder;
    }
}

/// The levels a compressor accepts.
pub fn compression_level_range() -> RangeInclusive<zstd_safe::CompressionLevel> {
    mzstd::Level::MIN.get()..=mzstd::Level::MAX.get()
}

fn other(e: impl std::error::Error + Send + Sync + 'static) -> io::Error {
    io::Error::other(e)
}

/// One-shot compression and decompression with a reusable context.
pub mod bulk {
    use super::*;

    /// A compressor at one level, reused between calls.
    pub struct Compressor<'a> {
        inner: mzstd::Compressor,
        _dictionary: PhantomData<&'a [u8]>,
    }

    impl Compressor<'_> {
        /// A compressor at `level`; a level outside [`compression_level_range`] is refused.
        pub fn new(level: zstd_safe::CompressionLevel) -> io::Result<Self> {
            let level = mzstd::Level::try_from(level).map_err(other)?;
            let inner = mzstd::Compressor::new(mzstd::EncoderConfig::default().with_level(level))
                .map_err(other)?;
            Ok(Self {
                inner,
                _dictionary: PhantomData,
            })
        }

        /// `source` as one Zstandard frame.
        pub fn compress(&mut self, source: &[u8]) -> io::Result<Vec<u8>> {
            self.inner.compress(source).map_err(other)
        }

        /// [`Compressor::compress`] appended to `out` (no buffer of its own: a vector with
        /// room allocates nothing); the frame's length. Not in the `zstd` crate.
        pub fn compress_append(&mut self, source: &[u8], out: &mut Vec<u8>) -> io::Result<usize> {
            self.inner
                .compress_into(source, out)
                .map(|r| r.len())
                .map_err(other)
        }

        /// [`Compressor::compress`] written into `out`; the frame's length.
        pub fn compress_to_buffer<C: WriteBuf + ?Sized>(
            &mut self,
            source: &[u8],
            out: &mut C,
        ) -> io::Result<usize> {
            let frame = self.compress(source)?;
            out.put(&frame);
            Ok(frame.len())
        }
    }

    /// A decompressor, reused between calls.
    pub struct Decompressor<'a> {
        /// The decoder [`Decompressor::decompress_append`] keeps, with its output limit.
        kept: Option<(usize, mzstd::Decompressor)>,
        _dictionary: PhantomData<&'a [u8]>,
    }

    impl Decompressor<'_> {
        /// A decompressor with no dictionary.
        pub fn new() -> io::Result<Self> {
            Ok(Self {
                kept: None,
                _dictionary: PhantomData,
            })
        }

        /// The frames in `source` appended to `out`, refused when they hold more than
        /// `capacity` bytes; the decoder is kept for the next call of the same capacity (a
        /// vector with room allocates nothing). Their content's length. Not in the `zstd`
        /// crate.
        pub fn decompress_append(
            &mut self,
            source: &[u8],
            capacity: usize,
            out: &mut Vec<u8>,
        ) -> io::Result<usize> {
            if self.kept.as_ref().is_none_or(|k| k.0 != capacity) {
                let limits =
                    mzstd::DecodeLimits::DEFAULT.with_max_output_bytes(Some(capacity as u64));
                let d =
                    mzstd::Decompressor::new(mzstd::DecoderConfig::default().with_limits(limits));
                self.kept = Some((capacity, d));
            }
            let (_, d) = self.kept.as_mut().expect("kept above");
            d.decompress_into(source, out)
                .map(|r| r.len())
                .map_err(other)
        }

        /// The frames in `source`, refused when they hold more than `capacity` bytes.
        pub fn decompress(&mut self, source: &[u8], capacity: usize) -> io::Result<Vec<u8>> {
            let limits = mzstd::DecodeLimits::DEFAULT.with_max_output_bytes(Some(capacity as u64));
            let mut d =
                mzstd::Decompressor::new(mzstd::DecoderConfig::default().with_limits(limits));
            d.decompress(source).map_err(other)
        }

        /// The frames in `source` written into `out`; their content's length.
        pub fn decompress_to_buffer<C: WriteBuf + ?Sized>(
            &mut self,
            source: &[u8],
            out: &mut C,
        ) -> io::Result<usize> {
            let content = super::decode_all(source)?;
            out.put(&content);
            Ok(content.len())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::bulk::{Compressor, Decompressor};

    #[test]
    fn a_frame_comes_back_as_its_bytes() {
        let input = "kleene ".repeat(1000);
        let frame = Compressor::new(3)
            .unwrap()
            .compress(input.as_bytes())
            .unwrap();
        assert!(frame.len() < input.len());
        let back = Decompressor::new()
            .unwrap()
            .decompress(&frame, input.len())
            .unwrap();
        assert_eq!(back, input.as_bytes());
    }

    #[test]
    fn a_frame_larger_than_its_capacity_is_refused() {
        let input = vec![7u8; 4096];
        let frame = Compressor::new(1).unwrap().compress(&input).unwrap();
        assert!(
            Decompressor::new()
                .unwrap()
                .decompress(&frame, 100)
                .is_err()
        );
    }

    #[test]
    fn the_stream_forms_round_trip_and_the_header_states_the_size() {
        use std::io::{Read, Write};
        let input = "iceberg ".repeat(500);
        let mut e = super::Encoder::new(Vec::new(), 0).unwrap();
        e.include_checksum(true).unwrap();
        e.write_all(input.as_bytes()).unwrap();
        let frame = e.finish().unwrap();
        assert_eq!(
            super::zstd_safe::get_frame_content_size(&frame).unwrap(),
            Some(input.len() as u64)
        );
        let mut back = Vec::new();
        super::Decoder::new(&frame[..])
            .unwrap()
            .read_to_end(&mut back)
            .unwrap();
        assert_eq!(back, input.as_bytes());
        assert_eq!(super::stream::decode_all(&frame[..]).unwrap(), back);
        let mut v = vec![9u8];
        let mut c = std::io::Cursor::new(&mut v);
        c.set_position(1);
        let n = Decompressor::new()
            .unwrap()
            .decompress_to_buffer(&frame, &mut c)
            .unwrap();
        assert_eq!((n, v.len(), v[0]), (input.len(), input.len() + 1, 9));
        assert!(super::zstd_safe::compress_bound(input.len()) >= frame.len());
    }

    #[test]
    fn levels_out_of_range_are_refused() {
        assert!(super::compression_level_range().contains(&3));
        assert!(Compressor::new(1000).is_err());
    }
}