kona_protocol/compression/
zlib.rs

1//! Contains ZLIB compression and decompression primitives for Optimism.
2
3use crate::{ChannelCompressor, CompressorResult, CompressorWriter};
4use alloc::vec::Vec;
5use miniz_oxide::inflate::DecompressError;
6
7/// The best compression.
8const BEST_ZLIB_COMPRESSION: u8 = 9;
9
10/// Method to compress data using ZLIB.
11pub fn compress_zlib(data: &[u8]) -> Vec<u8> {
12    miniz_oxide::deflate::compress_to_vec(data, BEST_ZLIB_COMPRESSION)
13}
14
15/// Method to decompress data using ZLIB.
16pub fn decompress_zlib(data: &[u8]) -> Result<Vec<u8>, DecompressError> {
17    miniz_oxide::inflate::decompress_to_vec(data)
18}
19
20/// The ZLIB compressor.
21#[derive(Debug, Clone, Default)]
22#[non_exhaustive]
23pub struct ZlibCompressor {
24    /// Holds a non-compressed buffer.
25    buffer: Vec<u8>,
26    /// The compressed buffer.
27    compressed: Vec<u8>,
28}
29
30impl ZlibCompressor {
31    /// Create a new ZLIB compressor.
32    pub const fn new() -> Self {
33        Self { buffer: Vec::new(), compressed: Vec::new() }
34    }
35}
36
37impl CompressorWriter for ZlibCompressor {
38    fn write(&mut self, data: &[u8]) -> CompressorResult<usize> {
39        self.buffer.extend_from_slice(data);
40        self.compressed.clear();
41        self.compressed.extend_from_slice(&compress_zlib(&self.buffer));
42        Ok(data.len())
43    }
44
45    fn flush(&mut self) -> CompressorResult<()> {
46        Ok(())
47    }
48
49    fn close(&mut self) -> CompressorResult<()> {
50        Ok(())
51    }
52
53    fn reset(&mut self) {
54        self.buffer.clear();
55        self.compressed.clear();
56    }
57
58    fn len(&self) -> usize {
59        self.compressed.len()
60    }
61
62    fn read(&mut self, buf: &mut [u8]) -> CompressorResult<usize> {
63        let len = self.compressed.len().min(buf.len());
64        buf[..len].copy_from_slice(&self.compressed[..len]);
65        Ok(len)
66    }
67}
68
69impl ChannelCompressor for ZlibCompressor {
70    fn get_compressed(&self) -> Vec<u8> {
71        self.compressed.clone()
72    }
73}