Skip to main content

arrow_ipc/
compression.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::CompressionType;
6use arrow_buffer::Buffer;
7use arrow_schema::ArrowError;
8use flatbuffers::FlatBufferBuilder;
9
10const LENGTH_NO_COMPRESSED_DATA: i64 = -1;
11const LENGTH_OF_PREFIX_DATA: i64 = 8;
12const DEFAULT_ZSTD_COMPRESSION_LEVEL: i32 = 3;
13
14/// LZ4 frame block sizes representable by the frame header. See the [LZ4 frame format] for the
15/// block size codes; `lz4_flex`'s 8 MiB option sets a reserved bit, which the decoder rejects.
16///
17/// [LZ4 frame format]: https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub(crate) enum Lz4BlockSize {
20    Max64KiB,
21    Max256KiB,
22    Max1MiB,
23    Max4MiB,
24}
25
26impl Lz4BlockSize {
27    pub(crate) const DEFAULT: Self = Self::Max256KiB;
28
29    pub(crate) const fn from_bytes(bytes: usize) -> Option<Self> {
30        match bytes {
31            65_536 => Some(Self::Max64KiB),
32            262_144 => Some(Self::Max256KiB),
33            1_048_576 => Some(Self::Max1MiB),
34            4_194_304 => Some(Self::Max4MiB),
35            _ => None,
36        }
37    }
38}
39
40/// Additional context that may be needed for compression.
41///
42/// In the case of zstd, this will contain the zstd context, which can be reused between subsequent
43/// compression calls to avoid the performance overhead of initialising a new context for every
44/// compression. In the case of lz4, this will contain the lz4 frame encoder, whose hash table and
45/// block buffers are likewise reused; its block size is configurable through
46/// [`crate::writer::IpcWriteOptions::try_with_lz4_block_size`]. Also holds a [`FlatBufferBuilder`]
47/// that is reused across IPC writes.
48#[derive(Default)]
49pub struct IpcWriteContext {
50    scratch: Vec<u8>,
51    reserve_scratch: bool,
52    fbb: FlatBufferBuilder<'static>,
53    /// The lz4 frame block size to build a cached encoder with; `None` selects the default.
54    lz4_block_size: Option<Lz4BlockSize>,
55    #[cfg(feature = "zstd")]
56    compressor: Option<zstd::bulk::Compressor<'static>>,
57    #[cfg(feature = "lz4")]
58    lz4_compressor: Option<Lz4Compressor>,
59}
60
61impl IpcWriteContext {
62    /// Get a mutable reference to the [`FlatBufferBuilder`] that is reused across IPC writes.
63    pub(crate) fn mut_fbb(&mut self) -> &mut FlatBufferBuilder<'static> {
64        &mut self.fbb
65    }
66
67    /// Set whether the scratch buffer capacity should be reserved after each encode for reuse
68    /// on the next call. Set to `false` for the final batch in a sequence to avoid a
69    /// pointless allocation. by default, this is set to `false`.
70    pub fn set_reserve_scratch(&mut self, reserve: bool) {
71        self.reserve_scratch = reserve;
72    }
73    /// Reserve the scratch buffer capacity for reuse on the next call. This is a no-op if
74    /// `reserve_scratch` is set to `false`.
75    pub(crate) fn reserve_scratch_with_capacity(&mut self, additional: usize) {
76        if self.reserve_scratch {
77            self.scratch.reserve(additional);
78        }
79    }
80    pub(crate) fn scratch(&mut self) -> Vec<u8> {
81        std::mem::take(&mut self.scratch)
82    }
83
84    /// Set the lz4 frame block size used by the cached lz4 encoder.
85    ///
86    /// A cached encoder is dropped when the size changes so the next compression call builds one
87    /// with the new block size.
88    pub(crate) fn set_lz4_block_size(&mut self, block_size: Lz4BlockSize) {
89        if self.lz4_block_size != Some(block_size) {
90            self.lz4_block_size = Some(block_size);
91            #[cfg(feature = "lz4")]
92            {
93                // The cached encoder was configured for the previous block size.
94                self.lz4_compressor = None;
95            }
96        }
97    }
98
99    #[cfg(feature = "zstd")]
100    fn zstd_compressor(&mut self, level: i32) -> &mut zstd::bulk::Compressor<'static> {
101        self.compressor.get_or_insert_with(|| {
102            zstd::bulk::Compressor::new(level).expect("can use default compression level")
103        })
104    }
105
106    #[cfg(feature = "lz4")]
107    fn lz4_compressor(&mut self) -> &mut Lz4Compressor {
108        let block_size = self.lz4_block_size.unwrap_or(Lz4BlockSize::DEFAULT);
109        self.lz4_compressor
110            .get_or_insert_with(|| Lz4Compressor::new(block_size))
111    }
112}
113
114impl std::fmt::Debug for IpcWriteContext {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        let mut ds = f.debug_struct("IpcWriteContext");
117
118        #[cfg(feature = "zstd")]
119        ds.field(
120            "compressor",
121            &self.compressor.as_ref().map(|_| "zstd::bulk::Compressor"),
122        );
123
124        #[cfg(feature = "lz4")]
125        ds.field(
126            "lz4_compressor",
127            &self.lz4_compressor.as_ref().map(|_| "Lz4Compressor"),
128        );
129
130        ds.finish()
131    }
132}
133
134/// Deprecated alias for [`IpcWriteContext`].
135#[deprecated(since = "59.1.0", note = "Use IpcWriteContext instead")]
136pub type CompressionContext = IpcWriteContext;
137
138/// Additional context that may be needed for decompression.
139///
140/// In the case of zstd, this will contain the zstd decompression context, which can be reused
141/// between subsequent decompression calls to avoid the performance overhead of initialising a new
142/// context for every decompression.
143pub struct DecompressionContext {
144    #[cfg(feature = "zstd")]
145    decompressor: Option<zstd::bulk::Decompressor<'static>>,
146}
147
148impl DecompressionContext {
149    pub(crate) fn new() -> Self {
150        Default::default()
151    }
152
153    #[cfg(feature = "zstd")]
154    fn zstd_decompressor(&mut self) -> &mut zstd::bulk::Decompressor<'static> {
155        self.decompressor.get_or_insert_with(|| {
156            zstd::bulk::Decompressor::new().expect("can create zstd decompressor")
157        })
158    }
159}
160
161#[expect(clippy::derivable_impls)]
162impl Default for DecompressionContext {
163    fn default() -> Self {
164        DecompressionContext {
165            #[cfg(feature = "zstd")]
166            decompressor: None,
167        }
168    }
169}
170
171impl std::fmt::Debug for DecompressionContext {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        let mut ds = f.debug_struct("DecompressionContext");
174
175        #[cfg(feature = "zstd")]
176        ds.field(
177            "decompressor",
178            &self
179                .decompressor
180                .as_ref()
181                .map(|_| "zstd::bulk::Decompressor"),
182        );
183
184        ds.finish()
185    }
186}
187
188/// Represents compressing a ipc stream using a particular compression algorithm
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum CompressionCodec {
191    Lz4Frame,
192    Zstd(i32),
193}
194
195impl TryFrom<CompressionType> for CompressionCodec {
196    type Error = ArrowError;
197
198    fn try_from(compression_type: CompressionType) -> Result<Self, ArrowError> {
199        match compression_type {
200            CompressionType::ZSTD => Ok(CompressionCodec::Zstd(DEFAULT_ZSTD_COMPRESSION_LEVEL)),
201            CompressionType::LZ4_FRAME => Ok(CompressionCodec::Lz4Frame),
202            other_type => Err(ArrowError::NotYetImplemented(format!(
203                "compression type {other_type:?} not supported "
204            ))),
205        }
206    }
207}
208
209impl CompressionCodec {
210    /// Creates a [`CompressionCodec`] with an explicit compression level.
211    ///
212    /// The level is used for [`CompressionType::ZSTD`].
213    /// [`CompressionType::LZ4_FRAME`] does not yet support compression levels
214    /// and ignores this value. Returns an error for unsupported compression
215    /// types.
216    pub(crate) fn try_new_with_compression_level(
217        compression_type: CompressionType,
218        compression_level: i32,
219    ) -> Result<Self, ArrowError> {
220        match compression_type {
221            CompressionType::ZSTD => Ok(CompressionCodec::Zstd(compression_level)),
222            CompressionType::LZ4_FRAME => Ok(CompressionCodec::Lz4Frame),
223            other_type => Err(ArrowError::NotYetImplemented(format!(
224                "compression type {other_type:?} not supported "
225            ))),
226        }
227    }
228
229    /// Compresses the data in `input` to `output` and appends the
230    /// data using the specified compression mechanism.
231    ///
232    /// returns the number of bytes written to the stream
233    ///
234    /// Writes this format to output:
235    /// ```text
236    /// [8 bytes]:         uncompressed length
237    /// [remaining bytes]: compressed data stream
238    /// ```
239    pub(crate) fn compress_to_vec(
240        &self,
241        input: &[u8],
242        output: &mut Vec<u8>,
243        context: &mut IpcWriteContext,
244    ) -> Result<usize, ArrowError> {
245        let uncompressed_data_len = input.len();
246        let original_output_len = output.len();
247
248        if input.is_empty() {
249            // empty input, nothing to do
250        } else {
251            // write compressed data directly into the output buffer
252            output.extend_from_slice(&(uncompressed_data_len as i64).to_le_bytes());
253            self.compress(input, output, context)?;
254
255            let compression_len = output.len() - original_output_len;
256            if compression_len > uncompressed_data_len {
257                // length of compressed data was larger than
258                // uncompressed data, use the uncompressed data with
259                // length -1 to indicate that we don't compress the
260                // data
261                output.truncate(original_output_len);
262                output.extend_from_slice(&LENGTH_NO_COMPRESSED_DATA.to_le_bytes());
263                output.extend_from_slice(input);
264            }
265        }
266        Ok(output.len() - original_output_len)
267    }
268
269    /// Decompresses the input into a [`Buffer`]
270    ///
271    /// The input should look like:
272    /// ```text
273    /// [8 bytes]:         uncompressed length
274    /// [remaining bytes]: compressed data stream
275    /// ```
276    pub(crate) fn decompress_to_buffer(
277        &self,
278        input: &Buffer,
279        context: &mut DecompressionContext,
280    ) -> Result<Buffer, ArrowError> {
281        // read the first 8 bytes to determine if the data is
282        // compressed
283        let decompressed_length = read_uncompressed_size(input)?;
284        let buffer = if decompressed_length == 0 {
285            // empty
286            Buffer::from([])
287        } else if decompressed_length == LENGTH_NO_COMPRESSED_DATA {
288            // no compression
289            input.slice(LENGTH_OF_PREFIX_DATA as usize)
290        } else if let Ok(decompressed_length) = usize::try_from(decompressed_length) {
291            // decompress data using the codec
292            let input_data = &input[(LENGTH_OF_PREFIX_DATA as usize)..];
293            let v = self.decompress(input_data, decompressed_length, context)?;
294            Buffer::from_vec(v)
295        } else {
296            return Err(ArrowError::IpcError(format!(
297                "Invalid uncompressed length: {decompressed_length}"
298            )));
299        };
300        Ok(buffer)
301    }
302
303    /// Compress the data in input buffer and write to output buffer
304    /// using the specified compression
305    fn compress(
306        &self,
307        input: &[u8],
308        output: &mut Vec<u8>,
309        context: &mut IpcWriteContext,
310    ) -> Result<(), ArrowError> {
311        match self {
312            CompressionCodec::Lz4Frame => compress_lz4(input, output, context),
313            CompressionCodec::Zstd(level) => compress_zstd(input, output, context, *level),
314        }
315    }
316
317    /// Decompress the data in input buffer and write to output buffer
318    /// using the specified compression
319    fn decompress(
320        &self,
321        input: &[u8],
322        decompressed_size: usize,
323        context: &mut DecompressionContext,
324    ) -> Result<Vec<u8>, ArrowError> {
325        let ret = match self {
326            CompressionCodec::Lz4Frame => decompress_lz4(input, decompressed_size)?,
327            CompressionCodec::Zstd(_) => decompress_zstd(input, decompressed_size, context)?,
328        };
329        if ret.len() != decompressed_size {
330            return Err(ArrowError::IpcError(format!(
331                "Expected decompressed length of {decompressed_size} got {}",
332                ret.len()
333            )));
334        }
335        Ok(ret)
336    }
337}
338
339/// Reusable lz4 frame compressor, the lz4 counterpart of `zstd::bulk::Compressor`.
340///
341/// `lz4_flex` has no bulk frame API, so this wraps a [`lz4_flex::frame::FrameEncoder`] whose hash
342/// table and block buffers are retained across calls to [`Self::compress_to_buffer`].
343#[cfg(feature = "lz4")]
344struct Lz4Compressor {
345    encoder: lz4_flex::frame::FrameEncoder<Vec<u8>>,
346    block_size: Lz4BlockSize,
347}
348
349#[cfg(feature = "lz4")]
350impl Lz4Compressor {
351    fn new(block_size: Lz4BlockSize) -> Self {
352        // `BlockSize::Auto` fixes a reused encoder's size from its first buffer. Pin the selected
353        // size so later frames keep using the block size requested in the write options.
354        let frame_info =
355            lz4_flex::frame::FrameInfo::new().block_size(to_lz4_block_size(block_size));
356        Self {
357            encoder: lz4_flex::frame::FrameEncoder::with_frame_info(frame_info, Vec::new()),
358            block_size,
359        }
360    }
361
362    /// Compresses `input` as a single lz4 frame appended to `output`.
363    fn compress_to_buffer(&mut self, input: &[u8], output: &mut Vec<u8>) -> Result<(), ArrowError> {
364        use std::io::Write;
365        // The encoder skips the frame header on empty input once it has written a frame.
366        debug_assert!(!input.is_empty());
367        // Lend `output` to the encoder so that the frame is written straight into it.
368        std::mem::swap(self.encoder.get_mut(), output);
369        let result = self
370            .encoder
371            .write_all(input)
372            .map_err(ArrowError::from)
373            .and_then(|()| {
374                self.encoder
375                    .try_finish()
376                    .map_err(|e| ArrowError::ExternalError(Box::new(e)))
377            });
378        std::mem::swap(self.encoder.get_mut(), output);
379        if result.is_err() {
380            // The encoder may be left mid-frame, start from a fresh one next time.
381            let block_size = self.block_size;
382            *self = Self::new(block_size);
383        }
384        result
385    }
386}
387
388/// Maps a validated block size to the `lz4_flex` frame header code.
389#[cfg(feature = "lz4")]
390fn to_lz4_block_size(block_size: Lz4BlockSize) -> lz4_flex::frame::BlockSize {
391    match block_size {
392        Lz4BlockSize::Max64KiB => lz4_flex::frame::BlockSize::Max64KB,
393        Lz4BlockSize::Max256KiB => lz4_flex::frame::BlockSize::Max256KB,
394        Lz4BlockSize::Max1MiB => lz4_flex::frame::BlockSize::Max1MB,
395        Lz4BlockSize::Max4MiB => lz4_flex::frame::BlockSize::Max4MB,
396    }
397}
398
399#[cfg(feature = "lz4")]
400fn compress_lz4(
401    input: &[u8],
402    output: &mut Vec<u8>,
403    context: &mut IpcWriteContext,
404) -> Result<(), ArrowError> {
405    context.lz4_compressor().compress_to_buffer(input, output)
406}
407
408#[cfg(not(feature = "lz4"))]
409fn compress_lz4(
410    _input: &[u8],
411    _output: &mut Vec<u8>,
412    _context: &mut IpcWriteContext,
413) -> Result<(), ArrowError> {
414    Err(ArrowError::InvalidArgumentError(
415        "lz4 IPC compression requires the lz4 feature".to_string(),
416    ))
417}
418
419#[cfg(feature = "lz4")]
420fn decompress_lz4(input: &[u8], decompressed_size: usize) -> Result<Vec<u8>, ArrowError> {
421    use std::io::Read;
422    let mut output = Vec::with_capacity(decompressed_size.min(crate::reader::MAX_PREALLOC_BYTES));
423    let mut decoder = lz4_flex::frame::FrameDecoder::new(input);
424    decoder
425        .by_ref()
426        .take(decompressed_size as u64)
427        .read_to_end(&mut output)?;
428
429    // Probe without growing `output` to reject data exceeding the advertised size.
430    if decoder.read(&mut [0])? != 0 {
431        return Err(ArrowError::IpcError(format!(
432            "LZ4 decompressed buffer exceeds advertised size of {decompressed_size}"
433        )));
434    }
435    Ok(output)
436}
437
438#[cfg(not(feature = "lz4"))]
439fn decompress_lz4(_input: &[u8], _decompressed_size: usize) -> Result<Vec<u8>, ArrowError> {
440    Err(ArrowError::InvalidArgumentError(
441        "lz4 IPC decompression requires the lz4 feature".to_string(),
442    ))
443}
444
445#[cfg(feature = "zstd")]
446fn compress_zstd(
447    input: &[u8],
448    output: &mut Vec<u8>,
449    context: &mut IpcWriteContext,
450    level: i32,
451) -> Result<(), ArrowError> {
452    let start = output.len();
453    output.reserve(zstd::zstd_safe::compress_bound(input.len()));
454
455    let mut cursor = std::io::Cursor::new(output);
456    cursor.set_position(start as u64);
457    context
458        .zstd_compressor(level)
459        .compress_to_buffer(input, &mut cursor)?;
460
461    Ok(())
462}
463
464#[cfg(not(feature = "zstd"))]
465fn compress_zstd(
466    _input: &[u8],
467    _output: &mut Vec<u8>,
468    _context: &mut IpcWriteContext,
469    _level: i32,
470) -> Result<(), ArrowError> {
471    Err(ArrowError::InvalidArgumentError(
472        "zstd IPC compression requires the zstd feature".to_string(),
473    ))
474}
475
476#[cfg(feature = "zstd")]
477fn decompress_zstd(
478    input: &[u8],
479    decompressed_size: usize,
480    context: &mut DecompressionContext,
481) -> Result<Vec<u8>, ArrowError> {
482    if decompressed_size > crate::reader::MAX_PREALLOC_BYTES {
483        // The bulk decompressor writes into a buffer reserved up front, so stream instead.
484        use std::io::Read;
485        let mut output =
486            Vec::with_capacity(decompressed_size.min(crate::reader::MAX_PREALLOC_BYTES));
487        let mut decoder = zstd::stream::read::Decoder::with_buffer(input)?;
488        decoder
489            .by_ref()
490            .take(decompressed_size as u64)
491            .read_to_end(&mut output)?;
492
493        // Probe without growing `output` to reject data exceeding the advertised size.
494        if decoder.read(&mut [0])? != 0 {
495            return Err(ArrowError::IpcError(format!(
496                "ZSTD decompressed buffer exceeds advertised size of {decompressed_size}"
497            )));
498        }
499        return Ok(output);
500    }
501    let output = context
502        .zstd_decompressor()
503        .decompress(input, decompressed_size)?;
504    Ok(output)
505}
506
507#[cfg(not(feature = "zstd"))]
508fn decompress_zstd(
509    _input: &[u8],
510    _decompressed_size: usize,
511    _context: &mut DecompressionContext,
512) -> Result<Vec<u8>, ArrowError> {
513    Err(ArrowError::InvalidArgumentError(
514        "zstd IPC decompression requires the zstd feature".to_string(),
515    ))
516}
517
518/// Get the uncompressed length
519/// Notes:
520///   LENGTH_NO_COMPRESSED_DATA: indicate that the data that follows is not compressed
521///    0: indicate that there is no data
522///   positive number: indicate the uncompressed length for the following data
523/// Returns an error if the input buffer is shorter than 8 bytes
524#[inline]
525fn read_uncompressed_size(buffer: &[u8]) -> Result<i64, ArrowError> {
526    let len_buffer = buffer.get(..LENGTH_OF_PREFIX_DATA as usize).ok_or_else(|| {
527        ArrowError::IpcError(format!(
528            "Compressed IPC buffer is too short: expected at least {LENGTH_OF_PREFIX_DATA} bytes, got {}",
529            buffer.len()
530        ))
531    })?;
532    Ok(i64::from_le_bytes(len_buffer.try_into().unwrap()))
533}
534
535#[cfg(test)]
536mod tests {
537    #[test]
538    #[cfg(feature = "lz4")]
539    fn test_lz4_compression() {
540        let input_bytes = b"hello lz4";
541        let codec = super::CompressionCodec::Lz4Frame;
542        let mut output_bytes: Vec<u8> = Vec::new();
543        codec
544            .compress(input_bytes, &mut output_bytes, &mut Default::default())
545            .unwrap();
546        let result = codec
547            .decompress(
548                output_bytes.as_slice(),
549                input_bytes.len(),
550                &mut Default::default(),
551            )
552            .unwrap();
553        assert_eq!(input_bytes, result.as_slice());
554    }
555
556    #[test]
557    #[cfg(feature = "lz4")]
558    fn test_lz4_decompression_rejects_output_exceeding_advertised_size() {
559        let input_bytes = b"hello lz4";
560        let codec = super::CompressionCodec::Lz4Frame;
561        let mut compressed = Vec::new();
562        codec
563            .compress(input_bytes, &mut compressed, &mut Default::default())
564            .unwrap();
565
566        let err = codec
567            .decompress(&compressed, input_bytes.len() - 1, &mut Default::default())
568            .expect_err("output larger than the advertised size should fail");
569
570        assert!(
571            err.to_string().contains("exceeds advertised size"),
572            "unexpected error: {err}"
573        );
574    }
575
576    #[test]
577    #[cfg(feature = "lz4")]
578    fn test_lz4_compression_multiple_frames() {
579        let codec = super::CompressionCodec::Lz4Frame;
580        let mut context = super::IpcWriteContext::default();
581        // Spans several 256KB blocks, followed by a smaller frame.
582        let large: Vec<u8> = (0..200_000u32)
583            .flat_map(|i| (i % 1000).to_le_bytes())
584            .collect();
585        let small = b"hello lz4".to_vec();
586        for input in [&large, &small, &large] {
587            let mut output = b"prefix".to_vec();
588            codec.compress(input, &mut output, &mut context).unwrap();
589            assert_eq!(&output[..6], b"prefix");
590            let result = codec
591                .decompress(&output[6..], input.len(), &mut Default::default())
592                .unwrap();
593            assert_eq!(input, &result);
594        }
595    }
596
597    #[test]
598    #[cfg(feature = "zstd")]
599    fn test_zstd_compression() {
600        let input_bytes = b"hello zstd";
601        let codec = super::CompressionCodec::Zstd(super::DEFAULT_ZSTD_COMPRESSION_LEVEL);
602        let mut output_bytes: Vec<u8> = Vec::new();
603        codec
604            .compress(input_bytes, &mut output_bytes, &mut Default::default())
605            .unwrap();
606        let result = codec
607            .decompress(
608                output_bytes.as_slice(),
609                input_bytes.len(),
610                &mut Default::default(),
611            )
612            .unwrap();
613        assert_eq!(input_bytes, result.as_slice());
614    }
615
616    /// A buffer larger than `MAX_PREALLOC_BYTES` round-trips, and a size its data does not back fails.
617    #[test]
618    #[cfg(any(feature = "lz4", feature = "zstd"))]
619    fn test_decompression_beyond_prealloc() {
620        let input = vec![7u8; crate::reader::MAX_PREALLOC_BYTES + 2];
621        for codec in [
622            #[cfg(feature = "lz4")]
623            super::CompressionCodec::Lz4Frame,
624            #[cfg(feature = "zstd")]
625            super::CompressionCodec::Zstd(super::DEFAULT_ZSTD_COMPRESSION_LEVEL),
626        ] {
627            let mut compressed = Vec::new();
628            codec
629                .compress(&input, &mut compressed, &mut Default::default())
630                .unwrap();
631            let decompress = |len| codec.decompress(&compressed, len, &mut Default::default());
632            assert_eq!(decompress(input.len()).unwrap(), input, "{codec:?}");
633            assert!(decompress(input.len() - 1).is_err(), "{codec:?}");
634            assert!(decompress(usize::MAX).is_err(), "{codec:?}");
635        }
636    }
637
638    #[test]
639    fn test_read_uncompressed_size_rejects_short_prefix() {
640        let err = super::read_uncompressed_size(&[1, 2, 3, 4, 5, 6, 7])
641            .expect_err("short compressed IPC prefix should return an error");
642
643        assert!(
644            err.to_string()
645                .contains("Compressed IPC buffer is too short"),
646            "unexpected error: {err}"
647        );
648    }
649
650    #[test]
651    #[cfg(feature = "lz4")]
652    fn test_compress_to_vec_writes_8_byte_length_prefix() {
653        // The length prefix must always be 8 bytes (i64),
654        // even on platforms where `usize` is narrower (e.g. wasm32).
655        let input_bytes = vec![42u8; 132];
656        let codec = super::CompressionCodec::Lz4Frame;
657        let mut output_bytes: Vec<u8> = Vec::new();
658        codec
659            .compress_to_vec(&input_bytes, &mut output_bytes, &mut Default::default())
660            .unwrap();
661
662        let prefix: [u8; 8] = output_bytes[..8].try_into().unwrap();
663        assert_eq!(i64::from_le_bytes(prefix), input_bytes.len() as i64);
664    }
665}