oxicode 0.2.5

A modern binary serialization library - successor to bincode
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Built-in compression support for oxicode.
//!
//! This module provides a small, explicit byte-level compression API. It is
//! **not** wired into [`crate::encode_to_vec`]/[`crate::decode_from_slice`],
//! [`crate::config::Configuration`], the streaming encoders, or the checksum
//! wrapper — there is no automatic or global compression. Callers opt in
//! explicitly by chaining the standalone functions, for example
//! `encode_to_vec(&value, config)` followed by [`compress`], and [`decompress`]
//! followed by `decode_from_slice(&bytes, config)` on the way back.
//!
//! ## Supported Codecs
//!
//! - **LZ4** (`compression-lz4` feature): Extremely fast compression/decompression.
//!   Good for real-time applications where speed matters more than ratio.
//!   Decompression speed: ~4 GB/s. Pure Rust via oxiarc-lz4.
//!
//! - **Zstd** (`compression-zstd` feature): Better compression ratio with still
//!   fast performance. Good for storage and network transmission.
//!   Pure Rust via oxiarc-zstd (full encode + decode, no C toolchain needed).
//!
//! ## Wire format
//!
//! [`compress`] prepends a fixed 5-byte header — `MAGIC` (`b"OXC"`), a version
//! byte, and a codec id — to the codec payload. [`decompress`] reads that header
//! to select the codec. The header is an oxicode framing convention and is
//! unrelated to the codec's own frame format.
//!
//! ## Example
//!
//! ```rust,ignore
//! use oxicode::compression::{Compression, compress, decompress};
//!
//! let data = b"Hello, World! This is some data to compress.";
//!
//! // Compress with LZ4 (default)
//! let compressed = compress(data, Compression::Lz4)?;
//!
//! // Decompress (256 MiB output cap by default; see `decompress_with_limit`)
//! let decompressed = decompress(&compressed)?;
//! assert_eq!(data.as_slice(), decompressed.as_slice());
//! ```
//!
//! ## Detection and its limits
//!
//! [`detect_compression`] and [`is_compressed`] inspect the 5-byte header to
//! recognise oxicode-compressed data. Detection is heuristic: arbitrary
//! serialized bytes can legitimately begin with the same 5 bytes, so a raw
//! payload may be mistaken for a compressed one (see [`decompress_or_passthrough`]).
//! For reliable round-trips, track whether a payload is compressed out of band
//! rather than relying on header sniffing.
//!
//! ## Decompression-bomb protection
//!
//! [`decompress`] caps the regenerated size at
//! [`DEFAULT_MAX_DECOMPRESSED_SIZE`] (256 MiB). Use [`decompress_with_limit`]
//! to pick a different bound when decompressing untrusted input.

#[cfg(feature = "alloc")]
extern crate alloc;

use crate::{Error, Result};

#[cfg(feature = "compression-lz4")]
mod lz4;

#[cfg(feature = "compression-zstd")]
mod zstd_impl;

/// Magic bytes for identifying compressed data.
/// Format: [0x4F, 0x58, 0x43, version, codec_id]
/// OXC = "OXiCode Compressed"
const MAGIC: [u8; 3] = [0x4F, 0x58, 0x43];
const VERSION: u8 = 1;
const HEADER_SIZE: usize = 5; // MAGIC (3) + VERSION (1) + CODEC (1)

/// Default cap on the regenerated (decompressed) size, in bytes (256 MiB).
///
/// [`decompress`] uses this bound to reject decompression bombs. Use
/// [`decompress_with_limit`] to override it for a specific call.
pub const DEFAULT_MAX_DECOMPRESSED_SIZE: usize = 256 * 1024 * 1024;

/// Compression algorithm selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Compression {
    /// No compression (passthrough)
    #[default]
    None,

    /// LZ4 compression - fastest, good for real-time
    #[cfg(feature = "compression-lz4")]
    Lz4,

    /// Zstd compression - better ratio, still fast
    #[cfg(feature = "compression-zstd")]
    Zstd,

    /// Zstd with specified compression level (1-22, default 3)
    #[cfg(feature = "compression-zstd")]
    ZstdLevel(u8),
}

impl Compression {
    /// Returns the codec ID for this compression type.
    const fn codec_id(self) -> u8 {
        match self {
            Compression::None => 0,
            #[cfg(feature = "compression-lz4")]
            Compression::Lz4 => 1,
            #[cfg(feature = "compression-zstd")]
            Compression::Zstd => 2,
            #[cfg(feature = "compression-zstd")]
            Compression::ZstdLevel(_) => 2,
        }
    }

    /// Returns the name of this compression type.
    pub const fn name(self) -> &'static str {
        match self {
            Compression::None => "none",
            #[cfg(feature = "compression-lz4")]
            Compression::Lz4 => "lz4",
            #[cfg(feature = "compression-zstd")]
            Compression::Zstd => "zstd",
            #[cfg(feature = "compression-zstd")]
            Compression::ZstdLevel(_) => "zstd",
        }
    }

    /// Returns true if this is no compression.
    pub const fn is_none(self) -> bool {
        matches!(self, Compression::None)
    }

    /// Parse codec from header byte.
    fn from_codec_id(id: u8) -> Option<Self> {
        match id {
            0 => Some(Compression::None),
            #[cfg(feature = "compression-lz4")]
            1 => Some(Compression::Lz4),
            #[cfg(feature = "compression-zstd")]
            2 => Some(Compression::Zstd),
            _ => None,
        }
    }
}

/// Compression statistics.
#[derive(Debug, Clone, Copy, Default)]
pub struct CompressionStats {
    /// Original (uncompressed) size in bytes.
    pub original_size: usize,
    /// Compressed size in bytes (including header).
    pub compressed_size: usize,
}

impl CompressionStats {
    /// Returns the compression ratio (original / compressed).
    /// A ratio > 1.0 means compression saved space.
    pub fn ratio(&self) -> f64 {
        if self.compressed_size == 0 {
            0.0
        } else {
            self.original_size as f64 / self.compressed_size as f64
        }
    }

    /// Returns the space saving as a percentage (0-100).
    pub fn savings_percent(&self) -> f64 {
        if self.original_size == 0 {
            0.0
        } else {
            100.0 * (1.0 - (self.compressed_size as f64 / self.original_size as f64))
        }
    }
}

/// Compress data using the specified compression algorithm.
///
/// Returns the compressed data with a header for automatic detection.
#[cfg(feature = "alloc")]
pub fn compress(data: &[u8], compression: Compression) -> Result<alloc::vec::Vec<u8>> {
    // Compute the codec payload first (or `None` for the passthrough case), then
    // write the 5-byte header and payload exactly once. Structuring it this way
    // keeps the wire format byte-identical to the previous implementation while
    // removing the unreachable!() panic path from the production code.
    let payload: Option<alloc::vec::Vec<u8>> = match compression {
        Compression::None => None,

        #[cfg(feature = "compression-lz4")]
        Compression::Lz4 => Some(lz4::compress(data)?),

        #[cfg(feature = "compression-zstd")]
        Compression::Zstd => Some(zstd_impl::compress(data, 3)?), // Default level

        #[cfg(feature = "compression-zstd")]
        Compression::ZstdLevel(level) => Some(zstd_impl::compress(data, level as i32)?),
    };

    let body: &[u8] = match payload.as_deref() {
        Some(compressed) => compressed,
        None => data,
    };

    let mut output = alloc::vec::Vec::with_capacity(HEADER_SIZE + body.len());
    output.extend_from_slice(&MAGIC);
    output.push(VERSION);
    output.push(compression.codec_id());
    output.extend_from_slice(body);
    Ok(output)
}

/// Compress data and return statistics.
#[cfg(feature = "alloc")]
pub fn compress_with_stats(
    data: &[u8],
    compression: Compression,
) -> Result<(alloc::vec::Vec<u8>, CompressionStats)> {
    let original_size = data.len();
    let compressed = compress(data, compression)?;
    let compressed_size = compressed.len();

    Ok((
        compressed,
        CompressionStats {
            original_size,
            compressed_size,
        },
    ))
}

/// Decompress data that was compressed with `compress`.
///
/// The compression format is selected from the 5-byte header. The regenerated
/// size is capped at [`DEFAULT_MAX_DECOMPRESSED_SIZE`] to guard against
/// decompression bombs; use [`decompress_with_limit`] to choose a different cap.
#[cfg(feature = "alloc")]
pub fn decompress(data: &[u8]) -> Result<alloc::vec::Vec<u8>> {
    decompress_with_limit(data, DEFAULT_MAX_DECOMPRESSED_SIZE)
}

/// Decompress data that was compressed with `compress`, capping the regenerated
/// size at `max_output` bytes.
///
/// The cap bounds worst-case memory use on untrusted input: a frame that would
/// regenerate more than `max_output` bytes is rejected with
/// [`Error::LimitExceeded`] instead of being expanded. If a payload's codec id
/// is recognised by the format but its feature is not compiled in, the error
/// states that explicitly rather than reporting an unknown codec.
#[cfg(feature = "alloc")]
pub fn decompress_with_limit(data: &[u8], max_output: usize) -> Result<alloc::vec::Vec<u8>> {
    if data.len() < HEADER_SIZE {
        return Err(Error::UnexpectedEnd {
            additional: HEADER_SIZE - data.len(),
        });
    }

    // Check magic
    if data[0..3] != MAGIC {
        return Err(Error::InvalidData {
            message: "invalid compression header magic",
        });
    }

    // Check version
    let version = data[3];
    if version != VERSION {
        return Err(Error::InvalidData {
            message: "unsupported compression version",
        });
    }

    let codec_id = data[4];
    let payload = &data[HEADER_SIZE..];

    // Dispatch on the raw codec id so that a codec known to the wire format but
    // not compiled in reports "feature not enabled" rather than "unknown codec".
    match codec_id {
        0 => Ok(payload.to_vec()),

        1 => {
            #[cfg(feature = "compression-lz4")]
            {
                lz4::decompress(payload, max_output)
            }
            #[cfg(not(feature = "compression-lz4"))]
            {
                let _ = max_output;
                Err(Error::InvalidData {
                    message:
                        "payload is LZ4-compressed but the compression-lz4 feature is not enabled",
                })
            }
        }

        2 => {
            #[cfg(feature = "compression-zstd")]
            {
                zstd_impl::decompress(payload, max_output)
            }
            #[cfg(not(feature = "compression-zstd"))]
            {
                let _ = max_output;
                Err(Error::InvalidData {
                    message:
                        "payload is Zstd-compressed but the compression-zstd feature is not enabled",
                })
            }
        }

        _ => Err(Error::InvalidData {
            message: "unknown compression codec",
        }),
    }
}

/// Try to decompress data, falling back to the original if it is not recognised
/// as compressed.
///
/// # Collision hazard
///
/// This function is a heuristic: it decompresses when [`is_compressed`] returns
/// `true` and otherwise returns the input unchanged. Detection looks only at the
/// 5-byte header, so an *uncompressed* payload that happens to begin with the
/// same bytes (`b"OXC"`, version `1`, and a valid codec id `0..=2`) is
/// misclassified as compressed. The probability is ~2^-40 for uniformly random
/// bytes but can be higher for structured data. When that happens:
///
/// * a colliding codec-`0` (passthrough) prefix has its 5-byte header stripped,
///   returning `Ok` with the first 5 bytes silently removed;
/// * a colliding codec-`1`/`2` prefix is fed to the LZ4/Zstd decoder, which
///   almost always fails and surfaces a decompression error.
///
/// Because a raw payload cannot be distinguished from a genuinely compressed one
/// by content alone, do **not** rely on this function for correctness on
/// arbitrary bytes. Track whether a payload is compressed out of band, or always
/// wrap payloads with [`compress`] so the header is guaranteed to be meaningful.
#[cfg(feature = "alloc")]
pub fn decompress_or_passthrough(data: &[u8]) -> Result<alloc::vec::Vec<u8>> {
    if is_compressed(data) {
        decompress(data)
    } else {
        Ok(data.to_vec())
    }
}

/// Check whether `data` looks like oxicode-compressed data.
///
/// Returns `true` when the 5-byte header is present: `MAGIC` (`b"OXC"`), the
/// expected version byte, and a codec id known to the wire format (`0..=2`).
///
/// This is a heuristic and can return a false positive: arbitrary serialized
/// bytes may legitimately start with the same 5-byte prefix. See
/// [`decompress_or_passthrough`] for the resulting collision hazard. Do not use
/// this as a correctness-critical test on untrusted or arbitrary input.
pub fn is_compressed(data: &[u8]) -> bool {
    data.len() >= HEADER_SIZE
        && data[0..3] == MAGIC
        && data[3] == VERSION
        && matches!(data[4], 0..=2)
}

/// Detect the compression type from compressed data.
pub fn detect_compression(data: &[u8]) -> Option<Compression> {
    if data.len() < HEADER_SIZE || data[0..3] != MAGIC || data[3] != VERSION {
        return None;
    }
    Compression::from_codec_id(data[4])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(all(feature = "alloc", feature = "compression-lz4"))]
    #[test]
    fn test_lz4_roundtrip() {
        let data = b"Hello, World! This is some test data for compression.";
        let compressed = compress(data, Compression::Lz4).expect("compress failed");
        let decompressed = decompress(&compressed).expect("decompress failed");
        assert_eq!(data.as_slice(), decompressed.as_slice());
    }

    #[cfg(all(feature = "alloc", feature = "compression-lz4"))]
    #[test]
    fn test_lz4_large_data() {
        // Create large repetitive data (compresses well)
        let data: alloc::vec::Vec<u8> = (0..100000).map(|i| (i % 256) as u8).collect();
        let compressed = compress(&data, Compression::Lz4).expect("compress failed");
        let decompressed = decompress(&compressed).expect("decompress failed");
        assert_eq!(data, decompressed);

        // Should have actually compressed
        assert!(compressed.len() < data.len());
    }

    #[cfg(all(feature = "alloc", feature = "compression-zstd"))]
    #[test]
    fn test_zstd_roundtrip() {
        let data = b"Hello, World! This is some test data for compression.";
        let compressed = compress(data, Compression::Zstd).expect("compress failed");
        let decompressed = decompress(&compressed).expect("decompress failed");
        assert_eq!(data.as_slice(), decompressed.as_slice());
    }

    #[cfg(all(feature = "alloc", feature = "compression-zstd"))]
    #[test]
    fn test_zstd_level() {
        let data = b"Hello, World! This is some test data for compression.";
        let compressed = compress(data, Compression::ZstdLevel(19)).expect("compress failed");
        let decompressed = decompress(&compressed).expect("decompress failed");
        assert_eq!(data.as_slice(), decompressed.as_slice());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_none_roundtrip() {
        let data = b"Hello, World!";
        let compressed = compress(data, Compression::None).expect("compress failed");
        let decompressed = decompress(&compressed).expect("decompress failed");
        assert_eq!(data.as_slice(), decompressed.as_slice());
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_is_compressed() {
        let data = b"Hello, World!";
        assert!(!is_compressed(data));

        let compressed = compress(data, Compression::None).expect("compress failed");
        assert!(is_compressed(&compressed));
    }

    #[cfg(all(feature = "alloc", feature = "compression-lz4"))]
    #[test]
    fn test_detect_compression() {
        let data = b"Hello, World!";
        let compressed = compress(data, Compression::Lz4).expect("compress failed");
        assert_eq!(detect_compression(&compressed), Some(Compression::Lz4));
    }

    #[cfg(all(feature = "alloc", feature = "compression-lz4"))]
    #[test]
    fn test_compression_stats() {
        let data: alloc::vec::Vec<u8> = (0..10000).map(|i| (i % 256) as u8).collect();
        let (compressed, stats) =
            compress_with_stats(&data, Compression::Lz4).expect("compress failed");

        assert_eq!(stats.original_size, data.len());
        assert_eq!(stats.compressed_size, compressed.len());
        assert!(stats.ratio() > 1.0); // Should have compressed
        assert!(stats.savings_percent() > 0.0);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_decompress_or_passthrough() {
        // Uncompressed data
        let raw = b"Hello, World!";
        let result = decompress_or_passthrough(raw).expect("failed");
        assert_eq!(raw.as_slice(), result.as_slice());

        // Compressed data
        let compressed = compress(raw, Compression::None).expect("compress failed");
        let result = decompress_or_passthrough(&compressed).expect("failed");
        assert_eq!(raw.as_slice(), result.as_slice());
    }

    #[test]
    fn test_compression_codec_id() {
        assert_eq!(Compression::None.codec_id(), 0);
        #[cfg(feature = "compression-lz4")]
        assert_eq!(Compression::Lz4.codec_id(), 1);
        #[cfg(feature = "compression-zstd")]
        assert_eq!(Compression::Zstd.codec_id(), 2);
    }

    #[test]
    fn test_compression_name() {
        assert_eq!(Compression::None.name(), "none");
        #[cfg(feature = "compression-lz4")]
        assert_eq!(Compression::Lz4.name(), "lz4");
        #[cfg(feature = "compression-zstd")]
        assert_eq!(Compression::Zstd.name(), "zstd");
    }
}