minlz 1.1.0

S2 compression format - compatible with klauspost/compress/s2
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// Copyright 2024 Karpeles Lab Inc.
// Based on the S2 compression format by Klaus Post
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

use crate::constants::*;
use crate::dict::{Dict, MAX_DICT_SRC_OFFSET};
use crate::error::{Error, Result};
use crate::varint::decode_varint;

/// Decoder for S2 and Snappy compression
pub struct Decoder {
    /// Whether to allow Snappy format (no repeat offsets)
    #[allow(dead_code)]
    allow_snappy: bool,
}

impl Decoder {
    /// Create a new decoder that accepts both S2 and Snappy formats
    pub fn new() -> Self {
        Decoder { allow_snappy: true }
    }

    /// Create a decoder that only accepts S2 format
    pub fn new_s2_only() -> Self {
        Decoder {
            allow_snappy: false,
        }
    }
}

impl Default for Decoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Decode returns the decoded form of src. The returned slice may be a sub-slice
/// of dst if dst was large enough to hold the entire decoded block.
/// Otherwise, a newly allocated Vec will be returned.
///
/// This function accepts both S2 and Snappy format.
/// The dst and src must not overlap. It is valid to pass an empty dst.
pub fn decode(src: &[u8]) -> Result<Vec<u8>> {
    let (dlen, header_len) = decode_len(src)?;
    let mut dst = alloc_uninit_dst(dlen)?;
    s2_decode(&mut dst, &src[header_len..])?;
    Ok(dst)
}

/// Decode Snappy format data
/// This is an alias for decode() since S2 decoder handles Snappy format
pub fn decode_snappy(src: &[u8]) -> Result<Vec<u8>> {
    decode(src)
}

/// Decode with dictionary
///
/// Decodes S2 data that was compressed with a dictionary.
/// Early copy operations may reference the dictionary instead of already-decoded output.
pub fn decode_with_dict(src: &[u8], dict: &Dict) -> Result<Vec<u8>> {
    let (dlen, header_len) = decode_len(src)?;
    let mut dst = alloc_uninit_dst(dlen)?;
    s2_decode_dict(&mut dst, &src[header_len..], dict)?;
    Ok(dst)
}

/// Hard cap on the decoded length the block-format decoder will accept.
///
/// The S2 wire format encodes the decoded length as a varint that can
/// represent up to 2^32 − 1 bytes (≈ 4 GiB). Accepting that at face
/// value lets a 5-byte adversarial input force a multi-gigabyte
/// allocation; on Linux the `malloc` returns virtual address space
/// without committing physical memory, so even `try_reserve_exact`
/// cannot detect the problem reliably (it succeeds, then later writes
/// page-fault). libFuzzer's malloc interceptor then aborts the
/// process when the request crosses its rss limit.
///
/// 256 MiB is well past any realistic single-block use (the stream
/// format already caps individual blocks at `MAX_BLOCK_SIZE` = 4 MiB)
/// and far below libFuzzer's 2 GiB default. Callers who need to
/// decode arbitrarily large payloads should use the stream
/// [`Reader`](crate::Reader) API instead, which processes one capped
/// block at a time.
pub const MAX_DECODE_DST_SIZE: usize = 256 * 1024 * 1024;

/// Allocate a `Vec<u8>` of length `n` whose bytes are *uninitialized*.
///
/// The S2 decoder writes every byte of the destination from 0..len before
/// returning Ok and only ever reads from positions it has already written.
/// We therefore skip the calloc-style zero-fill that `vec![0u8; n]` would
/// otherwise perform — that memset is the single largest cost on the
/// decode path for small/medium blocks (≈ 80 % of cycles).
///
/// Two layers protect against adversarial length headers:
///   1. A hard cap at [`MAX_DECODE_DST_SIZE`] rejects obviously
///      malicious requests up front.
///   2. `try_reserve_exact` covers the rest, returning
///      [`Error::TooLarge`] when the allocator itself can't satisfy
///      the request.
///
/// If the decoder returns Err, the partially-uninitialized Vec is dropped;
/// that is safe because `u8` has no Drop and no code path reads from the
/// uninit prefix.
#[inline]
fn alloc_uninit_dst(n: usize) -> Result<Vec<u8>> {
    if n > MAX_DECODE_DST_SIZE {
        return Err(Error::TooLarge);
    }
    let mut v: Vec<u8> = Vec::new();
    v.try_reserve_exact(n).map_err(|_| Error::TooLarge)?;
    // SAFETY: capacity is now ≥ `n`. The decoder fully initializes
    // 0..n before any read (see contract above); writes via
    // copy_from_slice / copy_within over an uninit `&mut [u8]` are
    // sound — no read of uninit bytes ever occurs.
    #[allow(clippy::uninit_vec)]
    unsafe {
        v.set_len(n);
    }
    Ok(v)
}

/// Decode into a pre-allocated destination buffer.
///
/// `dst` must be at least `decode_len(src)?.0` bytes; otherwise
/// returns [`Error::BufferTooSmall`]. The returned `usize` is the
/// number of bytes written into `dst`.
///
/// Useful for hot loops that decode into a reusable buffer without
/// allocating a fresh `Vec` per call.
pub fn decode_into(dst: &mut [u8], src: &[u8]) -> Result<usize> {
    let (dlen, header_len) = decode_len(src)?;

    if dst.len() < dlen {
        return Err(Error::BufferTooSmall);
    }

    s2_decode(&mut dst[..dlen], &src[header_len..])?;

    Ok(dlen)
}

/// Returns the length of the decoded block and the number of bytes
/// that the length header occupied.
pub fn decode_len(src: &[u8]) -> Result<(usize, usize)> {
    let (v, n) = decode_varint(src)?;

    if v > 0xffffffff {
        return Err(Error::Corrupt);
    }

    // Check for 32-bit overflow on 32-bit systems
    #[cfg(target_pointer_width = "32")]
    {
        if v > 0x7fffffff {
            return Err(Error::TooLarge);
        }
    }

    Ok((v as usize, n))
}

/// Core S2 decoding function
fn s2_decode(dst: &mut [u8], src: &[u8]) -> Result<()> {
    let mut d = 0; // destination index
    let mut s = 0; // source index
    let mut offset = 0; // last copy offset

    // Fast path: process as long as we can read at least 5 bytes
    while s < src.len().saturating_sub(5) {
        let tag = src[s] & 0x03;

        match tag {
            TAG_LITERAL => {
                let (length, bytes_consumed) = decode_literal_length(&src[s..])?;
                s += bytes_consumed;

                // Bounds check
                if length > dst.len() - d || length > src.len() - s {
                    return Err(Error::Corrupt);
                }

                // Copy literal bytes
                dst[d..d + length].copy_from_slice(&src[s..s + length]);
                d += length;
                s += length;
            }
            TAG_COPY1 => {
                let (new_offset, length, bytes_consumed) = decode_copy1(&src[s..], offset)?;
                s += bytes_consumed;
                offset = new_offset;

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            TAG_COPY2 => {
                if s + 3 > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u16::from_le_bytes(src[s + 1..s + 3].try_into().unwrap()) as usize;
                let length = 1 + ((src[s] >> 2) as usize);
                s += 3;

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            TAG_COPY4 => {
                if s + 5 > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u32::from_le_bytes(src[s + 1..s + 5].try_into().unwrap()) as usize;
                let length = 1 + ((src[s] >> 2) as usize);
                s += 5;

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            _ => unreachable!(),
        }
    }

    // Slow path: process remaining bytes with extra bounds checking
    while s < src.len() {
        let tag = src[s] & 0x03;

        match tag {
            TAG_LITERAL => {
                let (length, bytes_consumed) = decode_literal_length(&src[s..])?;
                s += bytes_consumed;

                // Bounds check
                if s > src.len() || length > dst.len() - d || length > src.len() - s {
                    return Err(Error::Corrupt);
                }

                // Copy literal bytes
                dst[d..d + length].copy_from_slice(&src[s..s + length]);
                d += length;
                s += length;
            }
            TAG_COPY1 => {
                let (new_offset, length, bytes_consumed) = decode_copy1(&src[s..], offset)?;
                s += bytes_consumed;

                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = new_offset;

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            TAG_COPY2 => {
                s += 3;
                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u16::from_le_bytes(src[s - 2..s].try_into().unwrap()) as usize;
                let length = 1 + ((src[s - 3] >> 2) as usize);

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            TAG_COPY4 => {
                s += 5;
                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u32::from_le_bytes(src[s - 4..s].try_into().unwrap()) as usize;
                let length = 1 + ((src[s - 5] >> 2) as usize);

                // Bounds check
                if offset == 0 || d < offset || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from earlier in dst
                copy_within(dst, d, offset, length);
                d += length;
            }
            _ => unreachable!(),
        }
    }

    // Verify we decoded exactly the right amount
    if d != dst.len() {
        return Err(Error::Corrupt);
    }

    Ok(())
}

/// Core S2 decoding function with dictionary support
fn s2_decode_dict(dst: &mut [u8], src: &[u8], dict: &Dict) -> Result<()> {
    let mut d = 0; // destination index
    let mut s = 0; // source index
    let mut offset = dict.data().len() - dict.repeat(); // Initialize with dictionary repeat offset

    // Fast path: process as long as we can read at least 5 bytes
    while s < src.len().saturating_sub(5) {
        let tag = src[s] & 0x03;

        match tag {
            TAG_LITERAL => {
                let (length, bytes_consumed) = decode_literal_length(&src[s..])?;
                s += bytes_consumed;

                // Bounds check
                if length > dst.len() - d || length > src.len() - s {
                    return Err(Error::Corrupt);
                }

                // Copy literal bytes
                dst[d..d + length].copy_from_slice(&src[s..s + length]);
                d += length;
                s += length;
            }
            TAG_COPY1 => {
                let (new_offset, length, bytes_consumed) = decode_copy1(&src[s..], offset)?;
                s += bytes_consumed;
                offset = new_offset;

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    // Copying from dictionary
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    // Copy from earlier in dst
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            TAG_COPY2 => {
                if s + 3 > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u16::from_le_bytes(src[s + 1..s + 3].try_into().unwrap()) as usize;
                let length = 1 + ((src[s] >> 2) as usize);
                s += 3;

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            TAG_COPY4 => {
                if s + 5 > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u32::from_le_bytes(src[s + 1..s + 5].try_into().unwrap()) as usize;
                let length = 1 + ((src[s] >> 2) as usize);
                s += 5;

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            _ => unreachable!(),
        }
    }

    // Slow path: process remaining bytes with extra bounds checking
    while s < src.len() {
        let tag = src[s] & 0x03;

        match tag {
            TAG_LITERAL => {
                let (length, bytes_consumed) = decode_literal_length(&src[s..])?;
                s += bytes_consumed;

                // Bounds check
                if s > src.len() || length > dst.len() - d || length > src.len() - s {
                    return Err(Error::Corrupt);
                }

                // Copy literal bytes
                dst[d..d + length].copy_from_slice(&src[s..s + length]);
                d += length;
                s += length;
            }
            TAG_COPY1 => {
                let (new_offset, length, bytes_consumed) = decode_copy1(&src[s..], offset)?;
                s += bytes_consumed;

                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = new_offset;

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            TAG_COPY2 => {
                s += 3;
                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u16::from_le_bytes(src[s - 2..s].try_into().unwrap()) as usize;
                let length = 1 + ((src[s - 3] >> 2) as usize);

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            TAG_COPY4 => {
                s += 5;
                if s > src.len() {
                    return Err(Error::Corrupt);
                }

                offset = u32::from_le_bytes(src[s - 4..s].try_into().unwrap()) as usize;
                let length = 1 + ((src[s - 5] >> 2) as usize);

                // Bounds check
                if offset == 0 || length > dst.len() - d {
                    return Err(Error::Corrupt);
                }

                // Copy from dictionary if needed
                if d < offset {
                    if d > MAX_DICT_SRC_OFFSET {
                        return Err(Error::Corrupt);
                    }

                    let dict_start = dict.data().len() - offset + d;
                    if dict_start + length > dict.data().len() {
                        return Err(Error::Corrupt);
                    }

                    dst[d..d + length]
                        .copy_from_slice(&dict.data()[dict_start..dict_start + length]);
                } else {
                    copy_within(dst, d, offset, length);
                }
                d += length;
            }
            _ => unreachable!(),
        }
    }

    // Verify we decoded exactly the right amount
    if d != dst.len() {
        return Err(Error::Corrupt);
    }

    Ok(())
}

/// Decode the length of a literal chunk
/// Returns (length, bytes_consumed)
fn decode_literal_length(src: &[u8]) -> Result<(usize, usize)> {
    let x = (src[0] >> 2) as u32;

    match x {
        0..=59 => Ok((x as usize + 1, 1)),
        60 => {
            if src.len() < 2 {
                return Err(Error::Corrupt);
            }
            Ok((src[1] as usize + 1, 2))
        }
        61 => {
            if src.len() < 3 {
                return Err(Error::Corrupt);
            }
            let len = u16::from_le_bytes(src[1..3].try_into().unwrap()) as usize;
            Ok((len + 1, 3))
        }
        62 => {
            if src.len() < 4 {
                return Err(Error::Corrupt);
            }
            // Read 4 bytes starting at src[0] and shift out the tag byte
            // — this turns 3 indexed reads into one unaligned word load.
            let len = (u32::from_le_bytes(src[0..4].try_into().unwrap()) >> 8) as usize;
            Ok((len + 1, 4))
        }
        63 => {
            if src.len() < 5 {
                return Err(Error::Corrupt);
            }
            let len = u32::from_le_bytes(src[1..5].try_into().unwrap()) as usize;
            Ok((len + 1, 5))
        }
        _ => Err(Error::Corrupt),
    }
}

/// Decode a COPY1 tag
/// Returns (offset, length, bytes_consumed)
fn decode_copy1(src: &[u8], last_offset: usize) -> Result<(usize, usize, usize)> {
    if src.len() < 2 {
        return Err(Error::Corrupt);
    }

    let toffset = ((src[0] as usize & 0xe0) << 3) | (src[1] as usize);
    let mut length = ((src[0] >> 2) & 0x7) as usize;

    if toffset == 0 {
        // Repeat offset - special encoding for length
        match length {
            5 => {
                if src.len() < 3 {
                    return Err(Error::Corrupt);
                }
                length = src[2] as usize + 4;
                Ok((last_offset, length + 4, 3))
            }
            6 => {
                if src.len() < 4 {
                    return Err(Error::Corrupt);
                }
                length = u16::from_le_bytes(src[2..4].try_into().unwrap()) as usize + (1 << 8);
                Ok((last_offset, length + 4, 4))
            }
            7 => {
                if src.len() < 5 {
                    return Err(Error::Corrupt);
                }
                // Read 4 bytes starting at src[1] and shift out the count byte.
                length =
                    (u32::from_le_bytes(src[1..5].try_into().unwrap()) >> 8) as usize + (1 << 16);
                Ok((last_offset, length + 4, 5))
            }
            _ => {
                // 0-4: use as-is
                Ok((last_offset, length + 4, 2))
            }
        }
    } else {
        Ok((toffset, length + 4, 2))
    }
}

/// Copy data within the same buffer, handling overlapping regions correctly.
/// This mimics the behavior of the Go implementation where overlapping copies
/// repeat the pattern (RLE-style).
#[inline]
fn copy_within(dst: &mut [u8], d: usize, offset: usize, length: usize) {
    let src_start = d - offset;

    // Non-overlapping: one memmove.
    if offset >= length {
        dst.copy_within(src_start..src_start + length, d);
        return;
    }

    // RLE case: offset == 1 is just a byte fill.
    if offset == 1 {
        let b = dst[src_start];
        dst[d..d + length].fill(b);
        return;
    }

    // Overlapping pattern fill (offset < length, offset > 1).
    // After each round we have at least `2 * available` valid bytes, so this
    // runs in O(log length) calls to copy_within — each of which can use the
    // built-in memmove and SIMD.
    let mut written = 0;
    while written < length {
        let available = offset + written;
        let chunk = (length - written).min(available);
        dst.copy_within(src_start..src_start + chunk, d + written);
        written += chunk;
    }
}