Skip to main content

utopia_compression/
snappy.rs

1//! Snappy, a port of Google's C++ snappy 1.2.1.
2
3use crate::sink::spare;
4use crate::{Algorithm, Compression, Error, Sink};
5
6/// Snappy raw format: the uncompressed length as a varint, then literals
7/// and copies.
8///
9/// The compressor is a port of C++ snappy 1.2.1's level 1 (the library
10/// PHP's ext-snappy links), with its portable hash: output is byte for byte
11/// `snappy_compress()`. The decompressor is as strict as snappy's: any
12/// malformed tag, out-of-range copy or length mismatch fails.
13///
14/// ```
15/// use utopia_compression::{Algorithm, Snappy};
16///
17/// let snappy = Snappy::new();
18/// let body = snappy.compress(b"This is a demo string")?;
19/// assert_eq!(body.len(), 23);
20/// assert_eq!(snappy.decompress(&body)?, b"This is a demo string");
21/// # Ok::<(), utopia_compression::Error>(())
22/// ```
23///
24/// ```php
25/// use Utopia\Compression\Algorithms\Snappy;
26///
27/// $snappy = new Snappy();
28/// $body = $snappy->compress('This is a demo string');
29/// echo strlen($body), "\n"; // 23
30/// echo $snappy->decompress($body), "\n"; // This is a demo string
31/// ```
32///
33/// Pure Rust, always available. PHP: `Utopia\Compression\Algorithms\Snappy`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub struct Snappy;
36
37impl Snappy {
38    /// Snappy.
39    ///
40    /// PHP: `new Snappy()`.
41    pub const fn new() -> Self {
42        Snappy
43    }
44
45    /// Always `true`: Snappy is pure Rust.
46    ///
47    /// PHP: `Snappy::isSupported()`, whether `snappy_compress()` exists.
48    pub const fn is_supported() -> bool {
49        true
50    }
51
52    /// [`Algorithm::compress`], appended to `out`: into room for snappy's
53    /// `MaxCompressedLength()`, as `snappy_compress()` allocates it.
54    pub fn compress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
55        let max = 32 + data.len() + data.len() / 6;
56        let start = out.len();
57        if !out.grow(start + max) {
58            return Err(Error::Codec("snappy_compress : memory error".into()));
59        }
60        let (at, _) = spare(out);
61        let mut writer = Writer { at, len: 0, capacity: max };
62        compress(data, &mut writer);
63        // SAFETY: the writer wrote `len` bytes, within the room made.
64        unsafe { out.set_len(start + writer.len) };
65        Ok(())
66    }
67
68    /// [`Algorithm::decompress`], appended to `out`: the length the input starts with is
69    /// allocated, as `snappy_uncompress()` allocates it, and the input must decode to exactly
70    /// that.
71    pub fn decompress_into<S: Sink + ?Sized>(&self, data: &[u8], out: &mut S) -> Result<(), Error> {
72        let Some((length, header)) = varint(data) else {
73            return Err(Error::Codec("snappy_uncompress : output length error".into()));
74        };
75        let length = length as usize;
76        let start = out.len();
77        if !out.grow(start + length) {
78            return Err(Error::Codec("snappy_uncompress : memory error".into()));
79        }
80        let (at, _) = spare(out);
81        // SAFETY: `at` has room for `length` bytes.
82        if !unsafe { decompress(&data[header..], at, length) } {
83            return Err(Error::Codec("snappy_uncompress : data error".into()));
84        }
85        // SAFETY: decompress wrote exactly `length` bytes.
86        unsafe { out.set_len(start + length) };
87        Ok(())
88    }
89}
90
91impl Algorithm for Snappy {
92    fn name(&self) -> &str {
93        Compression::SNAPPY
94    }
95
96    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
97        let mut out = Vec::new();
98        self.compress_into(data, &mut out)?;
99        Ok(out)
100    }
101
102    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, Error> {
103        let mut out = Vec::new();
104        self.decompress_into(data, &mut out)?;
105        Ok(out)
106    }
107
108    fn supported(&self) -> bool {
109        true
110    }
111}
112
113/// `kBlockSize`: input is compressed in independent 64 KiB fragments.
114const BLOCK_SIZE: usize = 1 << 16;
115/// `kMinHashTableBits` and `kMaxHashTableBits`.
116const MIN_TABLE_BITS: u32 = 8;
117const MAX_TABLE_BITS: u32 = 15;
118/// `kInputMarginBytes`: the main loop stops this close to the end.
119const INPUT_MARGIN: usize = 15;
120
121const LITERAL: u8 = 0;
122const COPY_1_BYTE_OFFSET: u32 = 1;
123const COPY_2_BYTE_OFFSET: u32 = 2;
124
125/// Where the compressor writes: room for snappy's `MaxCompressedLength()`, which its output
126/// never exceeds (a write past it panics rather than corrupting memory).
127struct Writer {
128    at: *mut u8,
129    len: usize,
130    capacity: usize,
131}
132
133impl Writer {
134    #[inline(always)]
135    fn push(&mut self, byte: u8) {
136        assert!(self.len < self.capacity, "snappy output past MaxCompressedLength");
137        // SAFETY: within the room checked above.
138        unsafe { self.at.add(self.len).write(byte) };
139        self.len += 1;
140    }
141
142    #[inline(always)]
143    fn extend(&mut self, bytes: &[u8]) {
144        assert!(bytes.len() <= self.capacity - self.len, "snappy output past MaxCompressedLength");
145        // SAFETY: within the room checked above; the input never overlaps the output.
146        unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.at.add(self.len), bytes.len()) };
147        self.len += bytes.len();
148    }
149}
150
151#[inline(always)]
152fn load32(s: &[u8], i: usize) -> u32 {
153    u32::from_le_bytes(s[i..i + 4].try_into().unwrap_or_default())
154}
155
156#[inline(always)]
157fn load64(s: &[u8], i: usize) -> u64 {
158    u64::from_le_bytes(s[i..i + 8].try_into().unwrap_or_default())
159}
160
161/// `CalculateTableSize()`: the next power of two, within 2^8..2^15.
162fn table_size(input: usize) -> usize {
163    input.clamp(1 << MIN_TABLE_BITS, 1 << MAX_TABLE_BITS).next_power_of_two()
164}
165
166/// `TableEntry()` with the portable multiplicative hash: the index of the
167/// 16-bit slot for the 4 bytes `bytes`.
168#[inline(always)]
169fn slot(bytes: u32, mask: u32) -> usize {
170    const MAGIC: u32 = 0x1e35_a7bd;
171    // The C++ table is addressed in bytes: `mask` is 2 * (size - 1).
172    (((MAGIC.wrapping_mul(bytes) >> (31 - MAX_TABLE_BITS)) & mask) >> 1) as usize
173}
174
175/// `RawCompress()`: the varint length, then each fragment.
176fn compress(input: &[u8], out: &mut Writer) {
177    let mut n = input.len() as u32;
178    while n >= 0x80 {
179        out.push(n as u8 | 0x80);
180        n >>= 7;
181    }
182    out.push(n as u8);
183    // The hash table, kept for the thread: only the part a fragment uses is cleared, so a small
184    // input does not pay for the 64 KiB a full one needs.
185    thread_local! {
186        static TABLE: std::cell::Cell<Option<Box<[u16; 1 << MAX_TABLE_BITS]>>> = const { std::cell::Cell::new(None) };
187    }
188    let mut table = TABLE.with(std::cell::Cell::take).unwrap_or_else(|| Box::new([0; 1 << MAX_TABLE_BITS]));
189    for fragment in input.chunks(BLOCK_SIZE) {
190        let size = table_size(fragment.len());
191        table[..size].fill(0);
192        compress_fragment(fragment, out, &mut table[..size]);
193    }
194    TABLE.with(|slot| slot.set(Some(table)));
195}
196
197/// `EmitLiteral()`.
198#[inline(always)]
199fn emit_literal(out: &mut Writer, literal: &[u8]) {
200    let n = literal.len() - 1;
201    if n < 60 {
202        out.push(LITERAL | ((n as u8) << 2));
203    } else {
204        let count = (n.ilog2() as usize >> 3) + 1;
205        out.push(LITERAL | (((59 + count) as u8) << 2));
206        out.extend(&(n as u32).to_le_bytes()[..count]);
207    }
208    out.extend(literal);
209}
210
211/// `EmitCopyAtMost64()`.
212#[inline(always)]
213fn emit_copy_at_most_64(out: &mut Writer, offset: usize, len: usize) {
214    let (offset, len) = (offset as u32, len as u32);
215    if len < 12 && offset < 2048 {
216        out.push((COPY_1_BYTE_OFFSET + ((len - 4) << 2) + ((offset >> 8) << 5)) as u8);
217        out.push(offset as u8);
218    } else {
219        out.push((COPY_2_BYTE_OFFSET + ((len - 1) << 2)) as u8);
220        out.extend(&(offset as u16).to_le_bytes());
221    }
222}
223
224/// `EmitCopy()`: 64-byte copies, keeping at least 4 bytes for the last one.
225#[inline(always)]
226fn emit_copy(out: &mut Writer, offset: usize, mut len: usize) {
227    if len < 12 {
228        return emit_copy_at_most_64(out, offset, len);
229    }
230    while len >= 68 {
231        emit_copy_at_most_64(out, offset, 64);
232        len -= 64;
233    }
234    if len > 64 {
235        emit_copy_at_most_64(out, offset, 60);
236        len -= 60;
237    }
238    emit_copy_at_most_64(out, offset, len);
239}
240
241/// `FindMatchLength()`: how many bytes from `a` and `b` agree, `b` bounded
242/// by `end` (`a < b`), eight at a time.
243#[inline(always)]
244fn match_length(s: &[u8], a: usize, b: usize, end: usize) -> usize {
245    let mut matched = 0;
246    while b + matched + 8 <= end {
247        let diff = load64(s, a + matched) ^ load64(s, b + matched);
248        if diff != 0 {
249            return matched + (diff.trailing_zeros() / 8) as usize;
250        }
251        matched += 8;
252    }
253    while b + matched < end && s[a + matched] == s[b + matched] {
254        matched += 1;
255    }
256    matched
257}
258
259/// `CompressFragment()`: greedy matching through a hash table of the last
260/// position of each 4-byte string, skipping faster through data without
261/// matches.
262fn compress_fragment(input: &[u8], out: &mut Writer, table: &mut [u16]) {
263    let mask = 2 * (table.len() as u32 - 1);
264    let end = input.len();
265    let mut ip = 0;
266    if end >= INPUT_MARGIN {
267        let limit = end - INPUT_MARGIN;
268        'outer: loop {
269            // Bytes in [next_emit, ip) are emitted as a literal before the
270            // next copy.
271            let next_emit = ip;
272            ip += 1;
273            let mut skip = 32u32;
274            let mut candidate;
275            // The unrolled first 16 probes: a match there takes a short
276            // literal straight away.
277            'scan: {
278                if limit >= ip + 16 {
279                    for i in 0..16 {
280                        let bytes = load32(input, ip + i);
281                        let entry = &mut table[slot(bytes, mask)];
282                        candidate = *entry as usize;
283                        *entry = (ip + i) as u16;
284                        if load32(input, candidate) == bytes {
285                            ip += i;
286                            break 'scan;
287                        }
288                    }
289                    ip += 16;
290                    skip += 16;
291                }
292                loop {
293                    let bytes = load32(input, ip);
294                    let index = slot(bytes, mask);
295                    let step = (skip >> 5) as usize;
296                    skip += step as u32;
297                    let next = ip + step;
298                    if next > limit {
299                        ip = next_emit;
300                        break 'outer;
301                    }
302                    candidate = table[index] as usize;
303                    table[index] = ip as u16;
304                    if load32(input, candidate) == bytes {
305                        break 'scan;
306                    }
307                    ip = next;
308                }
309            }
310            emit_literal(out, &input[next_emit..ip]);
311            // Copies, as long as the bytes after the last one match again.
312            loop {
313                let base = ip;
314                let matched = 4 + match_length(input, candidate + 4, ip + 4, end);
315                ip += matched;
316                emit_copy(out, base - candidate, matched);
317                if ip >= limit {
318                    break 'outer;
319                }
320                table[slot(load32(input, ip - 1), mask)] = (ip - 1) as u16;
321                let bytes = load32(input, ip);
322                let entry = &mut table[slot(bytes, mask)];
323                candidate = *entry as usize;
324                *entry = ip as u16;
325                if bytes != load32(input, candidate) {
326                    break;
327                }
328            }
329        }
330    }
331    if ip < end {
332        emit_literal(out, &input[ip..]);
333    }
334}
335
336/// `Varint::Parse32WithLimit()`: the uncompressed length and its size in
337/// bytes; at most 5 bytes, the last below 16.
338fn varint(data: &[u8]) -> Option<(u32, usize)> {
339    let mut result = 0u32;
340    for (i, &b) in data.iter().enumerate().take(5) {
341        if i == 4 {
342            return (b < 16).then(|| (result | (u32::from(b) << 28), 5));
343        }
344        result |= u32::from(b & 0x7f) << (7 * i);
345        if b < 0x80 {
346            return Some((result, i + 1));
347        }
348    }
349    None
350}
351
352/// `RawUncompress()`: decodes every tag into `out`; `false` unless the input ends on a tag
353/// boundary with exactly `length` bytes written.
354///
355/// # Safety
356///
357/// `out` has room for `length` bytes.
358unsafe fn decompress(mut input: &[u8], out: *mut u8, length: usize) -> bool {
359    let mut op = 0;
360    while let Some((&tag, rest)) = input.split_first() {
361        input = rest;
362        match tag & 3 {
363            0 => {
364                let mut len = (tag >> 2) as usize + 1;
365                if len > 60 {
366                    let count = len - 60;
367                    let Some((bytes, rest)) = input.split_at_checked(count) else { return false };
368                    input = rest;
369                    len = bytes.iter().rev().fold(0usize, |n, &b| (n << 8) | b as usize) + 1;
370                }
371                if len > length - op {
372                    return false;
373                }
374                let Some((literal, rest)) = input.split_at_checked(len) else { return false };
375                input = rest;
376                // SAFETY: `len` more bytes fit in `length`; the input never overlaps the output.
377                unsafe { std::ptr::copy_nonoverlapping(literal.as_ptr(), out.add(op), len) };
378                op += len;
379            }
380            kind => {
381                let (len, offset, extra) = match kind {
382                    1 => {
383                        let Some(&b) = input.first() else { return false };
384                        (((tag >> 2) & 7) as usize + 4, ((tag as usize >> 5) << 8) | b as usize, 1)
385                    }
386                    2 => {
387                        let Some(b) = input.first_chunk::<2>() else { return false };
388                        ((tag >> 2) as usize + 1, u16::from_le_bytes(*b) as usize, 2)
389                    }
390                    _ => {
391                        let Some(b) = input.first_chunk::<4>() else { return false };
392                        ((tag >> 2) as usize + 1, u32::from_le_bytes(*b) as usize, 4)
393                    }
394                };
395                input = &input[extra..];
396                if offset == 0 || offset > op || len > length - op {
397                    return false;
398                }
399                // SAFETY: the copy reads `offset` back from `op`, within what was written, and
400                // writes `len` bytes that fit in `length`. A copy longer than its offset repeats
401                // the bytes it writes, so it goes one offset's worth (or byte) at a time.
402                unsafe {
403                    let from = out.add(op - offset);
404                    let to = out.add(op);
405                    if offset >= len {
406                        std::ptr::copy_nonoverlapping(from, to, len);
407                    } else if offset >= 8 {
408                        let mut done = 0;
409                        while done < len {
410                            let step = offset.min(len - done);
411                            std::ptr::copy_nonoverlapping(from.add(done), to.add(done), step);
412                            done += step;
413                        }
414                    } else {
415                        for i in 0..len {
416                            *to.add(i) = *from.add(i);
417                        }
418                    }
419                }
420                op += len;
421            }
422        }
423    }
424    op == length
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn known_outputs() {
433        // snappy_compress() of PHP's ext-snappy.
434        assert_eq!(Snappy.compress(b"").unwrap(), b"\x00");
435        assert_eq!(Snappy.compress(b"a").unwrap(), b"\x01\x00a");
436        assert_eq!(Snappy.compress(b"This is a demo string").unwrap(), b"\x15\x50This is a demo string");
437    }
438
439    #[test]
440    fn round_trips() {
441        let mut data = Vec::new();
442        for i in 0..200_000u32 {
443            data.push((i.wrapping_mul(2_654_435_761) >> 29) as u8 + if i % 7 == 0 { b'a' } else { 0 });
444        }
445        for input in [&b"abcabcabcabcabcabcabcabc"[..], &data, &vec![0; 100_000], &b"0123456789".repeat(9000)] {
446            let compressed = Snappy.compress(input).unwrap();
447            assert_eq!(Snappy.decompress(&compressed).unwrap(), input);
448        }
449    }
450
451    #[test]
452    fn invalid_data() {
453        assert_eq!(Snappy.decompress(b""), Err(Error::Codec("snappy_uncompress : output length error".into())));
454        assert_eq!(Snappy.decompress(b"garbage"), Err(Error::Codec("snappy_uncompress : data error".into())));
455        assert_eq!(Snappy.decompress(b"\x01\x05\x01"), Err(Error::Codec("snappy_uncompress : data error".into())));
456    }
457}