autozstd 0.2.0

Zstd envelope compression with automatic raw fallback and magicless frames
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
use std::cell::RefCell;
#[cfg(feature = "adaptive")]
use std::time::Instant;

use mzstd::{Compressor, EncoderConfig, FrameFormat, Level as ZLevel};

use crate::{Level, Type};

const CONFIG: EncoderConfig = EncoderConfig::new().with_format(FrameFormat::Magicless);

/// A non-empty magicless Zstd frame is at least 6 bytes (header + 3B block
/// header + 1B payload), so inputs under 7 bytes can never shrink.
pub(crate) const MIN_COMPRESS_LEN: usize = 7;

/// Sample size of one probe.
const PROBE_LEN: usize = 16 * 1024;
/// Inputs shorter than eight samples are compressed directly; probing would
/// cost more than the full pass.
const PROBE_MIN: usize = 8 * PROBE_LEN;
/// A probe sample must shrink below this percentage to count as compressible.
const PROBE_PCT: usize = 97;
/// Maximum compressed bytes allowed for one probe sample (`< 97%` of `PROBE_LEN`).
const PROBE_MAX: usize = (PROBE_LEN * PROBE_PCT).div_ceil(100) - 1;
/// Inputs below this size are not timed; clock noise dominates.
const MIN_OBSERVE: usize = 8 * 1024;
/// Extra tail room so frame/block header capacity checks never fail before raw
/// fallback is evaluated.
const SLACK: usize = 16;

thread_local! {
  static ENC: RefCell<EncState> = const {
    RefCell::new(EncState {
      compressor: None,
      probe: None,
    })
  };
}

struct EncState {
  compressor: Option<Compressor>,
  probe: Option<Probe>,
}

struct Probe {
  compressor: Compressor,
  buf: Box<[u8]>,
}

impl Probe {
  fn new() -> Self {
    let zlevel = ZLevel::try_from(Level::Fastest.get()).unwrap();
    Self {
      compressor: Compressor::new(CONFIG.with_level(zlevel)).unwrap(),
      buf: vec![0u8; PROBE_MAX + SLACK].into_boxed_slice(),
    }
  }

  /// Whether any sampled slice shrinks below `PROBE_PCT` of `PROBE_LEN`.
  ///
  /// The caller guarantees `data.len() >= PROBE_MIN`, so every offset fits a
  /// full sample before the end.
  fn can_compress(&mut self, data: &[u8]) -> bool {
    let tail = data.len() - PROBE_LEN;
    [0, tail / 2, tail].into_iter().any(|start| {
      let sample = &data[start..start + PROBE_LEN];
      matches!(
        self.compressor.compress_to_slice(sample, &mut self.buf),
        Ok(written) if written <= PROBE_MAX
      )
    })
  }
}

/// Returns `true` if `head` starts with a known compressed or container magic.
#[inline]
pub(crate) fn skip_magic(head: &[u8]) -> bool {
  let Some(&first) = head.first() else {
    return false;
  };
  match first {
    0x00 => {
      head.starts_with(b"\x00\x00\x00\x0cJXL \r\n\x87\n")
        || head.starts_with(b"\x00\x00\x00\x0cjP  \r\n\x87\n")
        || matches!(head, [0, 0, _, _, b'f', b't', b'y', b'p', _, _, _, _, ..])
    }
    0x04 => head.starts_with(b"\x04\x22\x4d\x18"),
    0x1a => head.starts_with(b"\x1aE\xdf\xa3"),
    0x1f => head.starts_with(b"\x1f\x8b\x08"),
    0x28 => head.starts_with(b"\x28\xb5\x2f\xfd"),
    b'7' => head.starts_with(b"7z\xbc\xaf\x27\x1c"),
    b'B' => matches!(head, [b'B', b'Z', b'h', b'1'..=b'9', ..]),
    b'G' => head.starts_with(b"GIF89a") || head.starts_with(b"GIF87a"),
    b'O' => head.starts_with(b"OggS"),
    b'P' => head.starts_with(b"PK\x03\x04"),
    b'R' => {
      head.starts_with(b"Rar!\x1a\x07")
        || matches!(
          head,
          [
            b'R',
            b'I',
            b'F',
            b'F',
            _,
            _,
            _,
            _,
            b'W',
            b'E',
            b'B',
            b'P',
            ..
          ]
        )
    }
    b'f' => head.starts_with(b"fLaC"),
    b'w' => head.starts_with(b"wOFF") || head.starts_with(b"wOF2"),
    0x89 => head.starts_with(b"\x89PNG\r\n\x1a\n"),
    0xfd => head.starts_with(b"\xfd7zXZ\x00"),
    0xff => {
      head.starts_with(b"\xff\xd8\xff")
        || head.starts_with(b"\xff\x0a")
        || head.starts_with(b"\xff\x4f\xff\x51")
    }
    _ => false,
  }
}

#[inline]
pub(crate) fn raw(data: &[u8]) -> Vec<u8> {
  let mut out = Vec::with_capacity(data.len() + 1);
  out.push(Type::Raw.into());
  out.extend_from_slice(data);
  out
}

/// Writes `[Raw tag][data]` into `out`, reusing its capacity.
#[inline]
pub(crate) fn raw_into(out: &mut Vec<u8>, data: &[u8]) {
  out.clear();
  out.reserve(data.len() + 1);
  out.push(Type::Raw.into());
  out.extend_from_slice(data);
}

/// Releases excess capacity after a fresh output buffer has been filled.
#[inline]
pub(crate) fn shrink(out: &mut Vec<u8>) {
  if out.len() * 2 < out.capacity() {
    out.shrink_to_fit();
  }
}

#[inline]
fn compressor_for(slot: &mut Option<Compressor>, level: Level) -> &mut Compressor {
  let zlevel = ZLevel::try_from(level.get()).unwrap();
  let compressor = slot.get_or_insert_with(|| Compressor::new(CONFIG.with_level(zlevel)).unwrap());
  if compressor.config().level() != zlevel {
    compressor.reconfigure(CONFIG.with_level(zlevel)).unwrap();
  }
  compressor
}

/// Attempts to write a compressed frame into `out`, reusing its capacity.
///
/// With `with_tag`, `out` becomes `[Zstd tag][frame]`; otherwise it becomes the
/// bare frame. Returns `false` and leaves `out` empty when the frame does not
/// shrink `data` or cannot be produced; the caller then decides whether to store
/// raw bytes.
fn compress_at(
  state: &mut EncState,
  data: &[u8],
  level: Level,
  out: &mut Vec<u8>,
  with_tag: bool,
) -> bool {
  out.clear();
  // Guard `limit + 1` against `isize::MAX` overflow on 32-bit targets.
  if data.len() > isize::MAX as usize - SLACK - 1 {
    return false;
  }
  let compressor = compressor_for(&mut state.compressor, level);
  let limit = data.len() + SLACK;
  let offset = usize::from(with_tag);

  if out.capacity() < limit + offset {
    out.reserve_exact(limit + offset);
  }
  if with_tag {
    out.push(Type::Zstd.into());
  }
  let Ok(written) = compressor.compress_to_uninit(data, &mut out.spare_capacity_mut()[..limit])
  else {
    out.clear();
    return false;
  };
  // Reject frames that do not shrink and anything beyond the destination slice.
  if written >= data.len() || written > limit {
    out.clear();
    return false;
  }
  // SAFETY: `compress_to_uninit` initialized `out[len..len + written]` on
  // `Ok(written)`, `written <= limit`, and the capacity covers
  // `offset + limit`.
  unsafe { out.set_len(offset + written) };
  true
}

/// Writes `[Zstd tag][frame]` into `out`.
#[inline]
fn compress_into(state: &mut EncState, data: &[u8], level: Level, out: &mut Vec<u8>) -> bool {
  compress_at(state, data, level, out, true)
}

/// Writes a bare frame into `out`, without the type tag.
#[inline]
fn compress_payload_into(
  state: &mut EncState,
  data: &[u8],
  level: Level,
  out: &mut Vec<u8>,
) -> bool {
  compress_at(state, data, level, out, false)
}

/// Compresses `data` into a fresh envelope, falling back to raw bytes.
fn encode_with(state: &mut EncState, data: &[u8], level: Level) -> Vec<u8> {
  let mut out = Vec::new();
  if !compress_into(state, data, level, &mut out) {
    raw_into(&mut out, data);
  }
  shrink(&mut out);
  out
}

/// Decision produced by [`plan`] before any payload bytes are written.
pub(crate) enum Plan {
  Raw,
  Zstd(Level),
}

/// Applies the length and magic checks, then asks `decide` and probes.
///
/// `decide` receives whether the call is observable (8 KiB or larger) and
/// returns `None` to store raw bytes. Inputs rejected by the head or probe check
/// never call it.
pub(crate) fn plan(data: &[u8], decide: impl FnOnce(bool) -> Option<Level>) -> Plan {
  if data.len() < MIN_COMPRESS_LEN || skip_magic(data) {
    return Plan::Raw;
  }
  // Decide before probing so a raw choice avoids the probe pass.
  let Some(level) = decide(data.len() >= MIN_OBSERVE) else {
    return Plan::Raw;
  };
  if data.len() >= PROBE_MIN {
    let compressible = ENC.with_borrow_mut(|state| {
      state
        .probe
        .get_or_insert_with(Probe::new)
        .can_compress(data)
    });
    if !compressible {
      return Plan::Raw;
    }
  }
  Plan::Zstd(level)
}

/// Compresses into `out` and times the pass when the input is observable.
#[cfg(feature = "adaptive")]
fn compress_timed(
  data: &[u8],
  level: Level,
  out: &mut Vec<u8>,
  with_tag: bool,
) -> (bool, Option<f64>) {
  let start = (data.len() >= MIN_OBSERVE).then(Instant::now);
  let compressed = ENC.with_borrow_mut(|state| compress_at(state, data, level, out, with_tag));
  (compressed, start.map(|t| t.elapsed().as_secs_f64()))
}

/// Compresses `[Zstd tag][frame]` into `out` and times the pass.
#[cfg(feature = "adaptive")]
#[inline]
pub(crate) fn compress_into_timed(
  data: &[u8],
  level: Level,
  out: &mut Vec<u8>,
) -> (bool, Option<f64>) {
  compress_timed(data, level, out, true)
}

/// Compresses a bare frame into `out` and times the pass.
#[cfg(feature = "adaptive")]
#[inline]
pub(crate) fn compress_payload_into_timed(
  data: &[u8],
  level: Level,
  out: &mut Vec<u8>,
) -> (bool, Option<f64>) {
  compress_timed(data, level, out, false)
}

/// Encoded payload with the type tag kept separate from the payload buffer.
///
/// Splitting the tag lets callers write the 1-byte tag and the payload as two
/// owned buffers, so raw payloads are never copied. Use [`Encoded::into_parts`]
/// to obtain both, or [`Encoded::payload`] to inspect the bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Encoded {
  kind: Type,
  payload: Vec<u8>,
}

impl Encoded {
  #[inline]
  pub(crate) fn raw(payload: Vec<u8>) -> Self {
    Self {
      kind: Type::Raw,
      payload,
    }
  }

  #[inline]
  pub(crate) fn zstd(payload: Vec<u8>) -> Self {
    Self {
      kind: Type::Zstd,
      payload,
    }
  }

  /// Returns the payload kind.
  #[must_use]
  #[inline]
  pub fn kind(&self) -> Type {
    self.kind
  }

  /// Returns the payload bytes without the tag.
  #[must_use]
  #[inline]
  pub fn payload(&self) -> &[u8] {
    &self.payload
  }

  /// Consumes the value into its kind and payload buffer.
  #[must_use]
  #[inline]
  pub fn into_parts(self) -> (Type, Vec<u8>) {
    (self.kind, self.payload)
  }
}

/// Encodes an owned buffer, keeping it unchanged when raw bytes are chosen.
///
/// Raw decisions include inputs under 7 bytes, known compressed formats, probe
/// rejections, and frames that do not shrink. The returned payload then reuses
/// the input allocation, so no payload bytes are copied; it also keeps the
/// input's spare capacity, since shrinking would allocate and copy. A compressed
/// payload is a freshly sized buffer without the tag byte.
#[must_use]
pub fn encode_owned(data: Vec<u8>, level: Level) -> Encoded {
  match plan(&data, |_| Some(level)) {
    Plan::Raw => Encoded::raw(data),
    Plan::Zstd(level) => {
      let mut out = Vec::new();
      let compressed =
        ENC.with_borrow_mut(|state| compress_payload_into(state, &data, level, &mut out));
      if compressed {
        shrink(&mut out);
        Encoded::zstd(out)
      } else {
        Encoded::raw(data)
      }
    }
  }
}

/// Encodes into `out`, reusing its capacity, and returns the payload kind.
///
/// `out` holds a complete envelope on return. Reusing one buffer across calls
/// avoids the per-call allocation of [`encode`] and writes compressed frames
/// directly into the destination. The buffer is never shrunk; it keeps its
/// capacity and grows to the largest envelope written.
pub fn encode_into(data: &[u8], level: Level, out: &mut Vec<u8>) -> Type {
  match plan(data, |_| Some(level)) {
    Plan::Raw => {
      raw_into(out, data);
      Type::Raw
    }
    Plan::Zstd(level) => {
      let compressed = ENC.with_borrow_mut(|state| compress_into(state, data, level, out));
      if compressed {
        Type::Zstd
      } else {
        raw_into(out, data);
        Type::Raw
      }
    }
  }
}

/// Compresses `data` into an envelope.
///
/// The result starts with a [`Type`] byte. Inputs under 7 bytes, known
/// compressed formats, and probes or frames that do not shrink below the input
/// size are stored as [`Type::Raw`].
#[must_use]
pub fn encode(data: &[u8], level: Level) -> Vec<u8> {
  match plan(data, |_| Some(level)) {
    Plan::Raw => raw(data),
    Plan::Zstd(level) => ENC.with_borrow_mut(|state| encode_with(state, data, level)),
  }
}