ldeflate/precompressed.rs
1//! **Never compress what is already compressed** — an exact probe, and the
2//! stored-DEFLATE emitter that makes acting on it free.
3//!
4//! Level-6 DEFLATE over already-compressed content measures a ratio of **1.000
5//! while running 42x slower than a hash over the same bytes**
6//! (`.nornir/ldeflate-design.md`, the incompressible finding). Every format this
7//! crate writes hits that case constantly: a git object store full of packfiles,
8//! a JAR full of PNGs, a `.tar.gz` of `.jpg`s. Paying an entropy coder to
9//! produce its input back is the single largest avoidable cost on the write
10//! side.
11//!
12//! `zip.rs` already stored an entry when deflate failed to help — but *after*
13//! deflating it, so the CPU was already spent and only the bytes were saved.
14//! This module moves the decision in front of the encoder, for all three
15//! containers at once.
16//!
17//! # Why there is no entropy estimate
18//!
19//! Inherited verbatim from the reference implementation, and worth restating
20//! because it is the first thing anyone reaches for: an entropy estimate is a
21//! heuristic with a tunable threshold, it costs a scan proportional to the data,
22//! and it misjudges in both directions. Every probe here is **exact** — a fixed
23//! byte pattern at a fixed offset, at most [`SNIFF_PREFIX_LEN`] byte compares,
24//! no threshold, no sample size, no allocation.
25//!
26//! # Provenance, and why this module is the one writer (LAW 5)
27//!
28//! The probe is the owner's, from `znippy-common/src/precompressed.rs`, and for
29//! one commit it existed twice. It lives **here** now, and `znippy-common`'s
30//! module is a re-export of this one — `znippy_common::precompressed::{
31//! looks_compressed, is_zlib_stream, ContentHint, SNIFF_PREFIX_LEN}` are these
32//! items, not copies of them.
33//!
34//! The direction is forced. `znippy-common` already depends on `znippy-zoomies`
35//! (`znippy-common/Cargo.toml:95`, plus `ljar`/`lbzip2`/`lgz`), so an
36//! `ldeflate -> znippy-common` edge would close a cycle; and `znippy-common`
37//! drags `arrow`, `blake3` and an `openzl-sys` whose `build.rs` fetches a tarball
38//! over the network — for 88 lines of `std`-only pattern matching. The
39//! dependency arrow already pointed here, and this crate is the *compressor*,
40//! the only thing that ever needs to ask the question.
41//!
42//! The extension half of the reference chain (`skip_by_path`, backed by
43//! `znippy_common::index::is_probably_compressed`) is deliberately **not**
44//! lifted, and is the one part `znippy-common` still owns: this crate is handed
45//! `&[u8]`, never a `Path`. A caller who has a path resolves it to a
46//! [`ContentHint`] and passes that. `znippy_common::precompressed::SkipPolicy`
47//! is therefore a thin wrapper over [`SkipPolicy`] that adds the path leg and
48//! delegates the byte leg to [`SkipPolicy::skip`] — the hint-to-verdict mapping
49//! for bytes exists once, here.
50
51/// Bytes of prefix the probe reads. Sized by WebP, whose form type sits at
52/// offset 8..12 — the longest anchored pattern here.
53pub const SNIFF_PREFIX_LEN: usize = 16;
54
55/// What a caller already knows about its content, if anything.
56///
57/// The hint is honoured **in both directions**: `Compressible` is never vetoed
58/// by a probe, so a caller who knows better than the magic bytes wins.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum ContentHint {
61 /// Nothing known — probe the bytes.
62 #[default]
63 Unknown,
64 /// Caller asserts this is already compressed. Store it, do not probe.
65 AlreadyCompressed,
66 /// Caller asserts this is worth compressing. Compress it, do not probe.
67 Compressible,
68}
69
70/// Whether, and how, the compressor is allowed to skip the entropy coder.
71///
72/// [`Default`] is [`resolve`](Self::resolve) — the probe is **on**. An
73/// optimisation that a caller must opt into is one that nobody gets; and unlike
74/// a cap, being wrong here costs a few percent of ratio on a file that lied
75/// about its own magic bytes, not a correctness bug. Every output remains a
76/// valid stream of its container either way.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
78pub struct SkipPolicy {
79 hint: ContentHint,
80}
81
82impl SkipPolicy {
83 /// Probe the bytes (the default).
84 pub const fn resolve() -> Self {
85 Self {
86 hint: ContentHint::Unknown,
87 }
88 }
89 /// Store everything: the caller knows the whole batch is compressed.
90 pub const fn already_compressed() -> Self {
91 Self {
92 hint: ContentHint::AlreadyCompressed,
93 }
94 }
95 /// Compress everything, probe nothing — the pre-probe behaviour, by name.
96 pub const fn compress_everything() -> Self {
97 Self {
98 hint: ContentHint::Compressible,
99 }
100 }
101 /// From a caller's hint.
102 pub const fn from_hint(hint: ContentHint) -> Self {
103 Self { hint }
104 }
105 /// The hint this policy carries.
106 pub const fn hint(&self) -> ContentHint {
107 self.hint
108 }
109
110 /// Should `src` be stored rather than deflated?
111 ///
112 /// Reads at most [`SNIFF_PREFIX_LEN`] bytes regardless of how long `src` is,
113 /// so this is O(1) in the object size — the property that makes it sound to
114 /// call on every object on the hot path.
115 #[inline]
116 pub fn skip(&self, src: &[u8]) -> bool {
117 match self.hint {
118 ContentHint::AlreadyCompressed => true,
119 ContentHint::Compressible => false,
120 ContentHint::Unknown => looks_compressed(src),
121 }
122 }
123}
124
125/// One magic-byte pattern that must match at offset 0.
126type Magic = (&'static [u8], &'static str);
127
128/// Exact patterns, all anchored at offset 0. Each is a format whose payload is
129/// compressed or otherwise incompressible; none has a threshold.
130const MAGICS: &[Magic] = &[
131 // ── git ─────────────────────────────────────────────────────────────────
132 (b"PACK", "git packfile"),
133 (b"\xfftOc", "git pack index v2"),
134 (b"MIDX", "git multi-pack-index"),
135 (b"BITM", "git pack bitmap (EWAH)"),
136 // ── general-purpose compressors ─────────────────────────────────────────
137 (b"\x1f\x8b", "gzip"),
138 (b"\x28\xb5\x2f\xfd", "zstd frame"),
139 (b"\xfd7zXZ\x00", "xz"),
140 (b"\x04\x22\x4d\x18", "lz4 frame"),
141 (b"7z\xbc\xaf\x27\x1c", "7z"),
142 (b"Rar!\x1a\x07", "rar"),
143 (b"PK\x03\x04", "zip"),
144 (b"PK\x05\x06", "zip (empty archive)"),
145 (b"PK\x07\x08", "zip (spanned)"),
146 // ── already-compressed media ────────────────────────────────────────────
147 (b"\x89PNG\r\n\x1a\n", "png"),
148 (b"\xff\xd8\xff", "jpeg"),
149 (b"GIF87a", "gif"),
150 (b"GIF89a", "gif"),
151];
152
153/// Does this buffer begin with data that is already compressed?
154///
155/// At most [`SNIFF_PREFIX_LEN`] byte compares, no allocation, safe on a short or
156/// empty slice.
157pub fn looks_compressed(prefix: &[u8]) -> bool {
158 let head = &prefix[..prefix.len().min(SNIFF_PREFIX_LEN)];
159
160 if MAGICS.iter().any(|(pat, _)| head.starts_with(pat)) {
161 return true;
162 }
163 // bzip2: "BZh" then the block-size digit '1'..='9'.
164 if head.len() >= 4 && head.starts_with(b"BZh") && head[3].is_ascii_digit() && head[3] != b'0' {
165 return true;
166 }
167 // WebP is a RIFF container with a WEBP form type at offset 8; the four
168 // length bytes between them are not part of the magic.
169 if head.len() >= 12 && head.starts_with(b"RIFF") && &head[8..12] == b"WEBP" {
170 return true;
171 }
172 is_zlib_stream(head)
173}
174
175/// Does this buffer begin with a raw zlib stream (RFC 1950)?
176///
177/// This is what a git **loose object** is, and the one case an extension table
178/// can never reach — the file's name is an oid with no extension at all. It is
179/// also what *this crate writes*, so it is what keeps a re-compress pass over
180/// `ldeflate`'s own output from paying twice.
181///
182/// * `CM` = `CMF & 0x0f` must be `8` — deflate is the only defined method;
183/// * `CINFO` = `CMF >> 4` must be `<= 7` — a window over 32 KiB is not defined;
184/// * `FDICT` = `FLG & 0x20` must be clear;
185/// * `(CMF << 8 | FLG) % 31 == 0` — the header's own check bits.
186///
187/// The `FDICT` clause is what keeps ordinary text out. `CMF = 0x78` is ASCII
188/// `x`, and of the nine `FLG` values satisfying the mod-31 rule, every printable
189/// one — `' '`, `'?'`, `'}'` — sets `FDICT` and is rejected. `x^` is the sole
190/// printable two-byte sequence that survives.
191pub fn is_zlib_stream(prefix: &[u8]) -> bool {
192 let [cmf, flg, ..] = prefix else { return false };
193 let (cmf, flg) = (*cmf, *flg);
194
195 cmf & 0x0f == 8
196 && cmf >> 4 <= 7
197 && flg & 0x20 == 0
198 && (u16::from(cmf) << 8 | u16::from(flg)) % 31 == 0
199}
200
201// ── Stored DEFLATE ───────────────────────────────────────────────────────────
202
203/// Largest payload one DEFLATE stored block can carry: `LEN` is a `u16`.
204const STORED_MAX: usize = u16::MAX as usize;
205
206/// Emit `src` as **stored** DEFLATE blocks (RFC 1951 §3.2.4) — a memcpy plus
207/// five bytes of framing per 65 535 bytes.
208///
209/// This is what makes the probe worth having. Asking `flate2` for level 0 would
210/// also produce stored blocks, but it still constructs a `Compress`, still runs
211/// the deflate state machine, and still copies through its internal window; this
212/// is a length-prefixed `extend_from_slice`. The output is ordinary DEFLATE that
213/// every inflater reads — including this workspace's own `linflate`.
214///
215/// `is_last` controls the final block's `BFINAL` bit:
216///
217/// * `true` — the stream ends here. An empty input still emits one empty final
218/// block, because a DEFLATE stream with no blocks is malformed.
219/// * `false` — the caller will append more, and the emitted bytes end at a block
220/// boundary. That is the same seam `Z_FULL_FLUSH` leaves and what
221/// `linflate::deflate_scan` looks for, so a stored segment concatenates with a
222/// deflated one.
223pub fn stored_deflate(src: &[u8], is_last: bool) -> Vec<u8> {
224 // 5 bytes of framing per block, plus one extra block's worth for the empty
225 // terminator an exact multiple needs.
226 let blocks = src.len().div_ceil(STORED_MAX).max(1);
227 let mut out = Vec::with_capacity(src.len() + 5 * blocks + 5);
228
229 let mut chunks = src.chunks(STORED_MAX).peekable();
230 if chunks.peek().is_none() {
231 push_stored_block(&mut out, &[], is_last);
232 return out;
233 }
234 while let Some(chunk) = chunks.next() {
235 let last_block = is_last && chunks.peek().is_none();
236 push_stored_block(&mut out, chunk, last_block);
237 }
238 out
239}
240
241/// One stored block: a byte-aligned 3-bit header (`BFINAL`, `BTYPE = 00`, then
242/// five bits of padding to the byte boundary), `LEN`, `~LEN`, then the bytes
243/// verbatim.
244#[inline]
245fn push_stored_block(out: &mut Vec<u8>, chunk: &[u8], is_last: bool) {
246 debug_assert!(chunk.len() <= STORED_MAX);
247 out.push(if is_last { 1 } else { 0 });
248 let len = chunk.len() as u16;
249 out.extend_from_slice(&len.to_le_bytes());
250 out.extend_from_slice(&(!len).to_le_bytes());
251 out.extend_from_slice(chunk);
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 /// Every magic in the table must fire, and each must fire on the *shortest*
259 /// buffer that carries it — a probe that needs 16 bytes to recognise a
260 /// 2-byte magic would miss every tiny object.
261 #[test]
262 fn every_magic_in_the_table_is_recognised_at_its_own_length() {
263 for (pat, label) in MAGICS {
264 assert!(
265 looks_compressed(pat),
266 "{label}: not recognised from its own {} magic bytes",
267 pat.len()
268 );
269 }
270 }
271
272 /// The three probes that are not a plain prefix compare, each from both
273 /// sides — a check that only ever says yes is as useless as one that only
274 /// ever says no.
275 #[test]
276 fn the_special_cased_probes_fire_only_on_their_real_shape() {
277 // bzip2 needs the block-size digit, and '0' is not one.
278 assert!(looks_compressed(b"BZh9\x31\x41\x59\x26"));
279 assert!(looks_compressed(b"BZh1"));
280 assert!(
281 !looks_compressed(b"BZh0"),
282 "'0' is not a valid bzip2 block size"
283 );
284 assert!(
285 !looks_compressed(b"BZhx"),
286 "a non-digit is not a block size"
287 );
288 assert!(
289 !looks_compressed(b"BZh"),
290 "three bytes cannot carry the digit"
291 );
292
293 // WebP needs BOTH the RIFF magic and the WEBP form type at 8..12.
294 assert!(looks_compressed(b"RIFF\x00\x00\x00\x00WEBPVP8 "));
295 assert!(
296 !looks_compressed(b"RIFF\x00\x00\x00\x00WAVEfmt "),
297 "a RIFF WAVE is not compressed"
298 );
299 assert!(
300 !looks_compressed(b"RIFF\x00\x00\x00\x00WEB"),
301 "truncated form type"
302 );
303 }
304
305 /// The zlib header check, exactly — this is the one that decides whether a
306 /// git loose object gets re-deflated, and the one most at risk of matching
307 /// ordinary text.
308 #[test]
309 fn the_zlib_probe_accepts_real_headers_and_rejects_text() {
310 // The three levels zlib actually emits at a 32 KiB window.
311 for h in [[0x78u8, 0x01], [0x78, 0x9c], [0x78, 0xda]] {
312 assert!(is_zlib_stream(&h), "{h:02x?} is a real zlib header");
313 assert!(looks_compressed(&h));
314 }
315 // Wrong method, oversized window, FDICT set, bad check bits.
316 assert!(!is_zlib_stream(&[0x77, 0x9c]), "CM != 8");
317 assert!(!is_zlib_stream(&[0x88, 0x9c]), "CINFO > 7");
318 assert!(!is_zlib_stream(&[0x78, 0xbb]), "FDICT set");
319 assert!(!is_zlib_stream(&[0x78, 0x9d]), "check bits fail");
320 assert!(!is_zlib_stream(&[0x78]), "one byte is not a header");
321 assert!(!is_zlib_stream(&[]), "empty is not a header");
322
323 // Ordinary content must not be mistaken for a stream.
324 for text in [
325 &b"fn main() { println!(\"hi\"); }"[..],
326 b"the quick brown fox jumps over the lazy dog",
327 b"{\"key\": \"value\", \"n\": 1}",
328 b"<?xml version=\"1.0\"?><osm/>",
329 b"# heading\n\nsome prose\n",
330 b"\0\0\0\0\0\0\0\0",
331 ] {
332 assert!(
333 !looks_compressed(text),
334 "false positive on {:?}",
335 &text[..text.len().min(12)]
336 );
337 }
338 }
339
340 /// The probe must be O(1) in the object size: a huge compressible buffer
341 /// whose head is plain must not be read past the prefix. Asserted by
342 /// behaviour — a 4 MiB buffer whose only compressed-looking bytes are at the
343 /// end must not fire.
344 #[test]
345 fn the_probe_reads_only_the_head() {
346 let mut v = vec![b'a'; 4 << 20];
347 v.extend_from_slice(b"\x89PNG\r\n\x1a\n");
348 assert!(!looks_compressed(&v), "a magic in the tail is not a magic");
349 assert!(
350 looks_compressed(b"\x89PNG\r\n\x1a\nrest"),
351 "but one at the head is"
352 );
353 }
354
355 /// The policy honours a hint in both directions, overriding the bytes.
356 #[test]
357 fn a_hint_beats_the_bytes_in_both_directions() {
358 let png = b"\x89PNG\r\n\x1a\n....";
359 let text = b"plain text, very compressible indeed";
360
361 assert!(SkipPolicy::resolve().skip(png));
362 assert!(!SkipPolicy::resolve().skip(text));
363
364 assert!(
365 SkipPolicy::already_compressed().skip(text),
366 "hint must override the probe"
367 );
368 assert!(
369 !SkipPolicy::compress_everything().skip(png),
370 "a Compressible hint is never vetoed by a probe"
371 );
372
373 assert_eq!(
374 SkipPolicy::default(),
375 SkipPolicy::resolve(),
376 "the probe is the default"
377 );
378 }
379
380 /// The stored emitter's framing, byte for byte. `LEN`/`~LEN` is the field
381 /// most likely to be got wrong and the one an inflater checks.
382 #[test]
383 fn a_stored_block_is_framed_exactly_as_rfc1951_says() {
384 let out = stored_deflate(b"abc", true);
385 assert_eq!(out, vec![0x01, 0x03, 0x00, 0xfc, 0xff, b'a', b'b', b'c']);
386
387 let non_final = stored_deflate(b"abc", false);
388 assert_eq!(
389 non_final[0], 0x00,
390 "BFINAL must be clear on a non-final block"
391 );
392 assert_eq!(&non_final[1..5], &[0x03, 0x00, 0xfc, 0xff]);
393 }
394
395 /// An empty input is still one (empty) final block — a DEFLATE stream with
396 /// no blocks at all is malformed, and an empty git object is real.
397 #[test]
398 fn an_empty_input_still_emits_one_block() {
399 assert_eq!(
400 stored_deflate(b"", true),
401 vec![0x01, 0x00, 0x00, 0xff, 0xff]
402 );
403 }
404
405 /// Payloads past 65 535 bytes must split into several blocks, with BFINAL
406 /// set on the last one only.
407 #[test]
408 fn a_payload_past_the_block_limit_splits_and_only_the_last_is_final() {
409 let src = vec![0xABu8; STORED_MAX + 1];
410 let out = stored_deflate(&src, true);
411 assert_eq!(
412 out.len(),
413 src.len() + 10,
414 "two blocks, five framing bytes each"
415 );
416 assert_eq!(out[0], 0x00, "the first of two blocks is not final");
417 assert_eq!(
418 &out[1..5],
419 &[0xff, 0xff, 0x00, 0x00],
420 "LEN = 65535, ~LEN = 0"
421 );
422 let second = STORED_MAX + 5;
423 assert_eq!(out[second], 0x01, "the last block is final");
424 assert_eq!(
425 &out[second + 1..second + 5],
426 &[0x01, 0x00, 0xfe, 0xff],
427 "LEN = 1"
428 );
429 }
430
431 /// The whole point, asserted against the real inflater: stored output must
432 /// round-trip through `linflate` to the exact input, at every size class
433 /// around the block boundary.
434 #[test]
435 fn stored_output_inflates_back_to_the_input() {
436 for len in [
437 0usize,
438 1,
439 255,
440 STORED_MAX - 1,
441 STORED_MAX,
442 STORED_MAX + 1,
443 3 * STORED_MAX + 7,
444 ] {
445 let src: Vec<u8> = (0..len).map(|i| (i * 31 + 7) as u8).collect();
446 let body = stored_deflate(&src, true);
447 let mut out = vec![0u8; len + linflate::OVERWRITE_HEADROOM];
448 let n = linflate::inflate_segment(&body, &mut out)
449 .unwrap_or_else(|e| panic!("len {len}: stored output did not inflate: {e:?}"));
450 assert_eq!(n, len, "len {len}: wrong output length");
451 assert_eq!(
452 &out[..n],
453 &src[..],
454 "len {len}: stored output did not round-trip"
455 );
456 }
457 }
458
459 // ── the zlib probe against a REAL encoder ────────────────────────────────
460 //
461 // The cases above hand-type the two header bytes, which proves only that the
462 // test and the probe agree with each other. These three come from
463 // `compress_objects` — this crate's own encoder — and from the canonical git
464 // bytes a real object store holds. They moved here from
465 // `znippy-common/src/precompressed.rs` when that module became a re-export of
466 // this one; the assertions are the reference implementation's, unchanged.
467
468 /// A real zlib stream out of this crate's own encoder. The module doc claims
469 /// the probe keeps a re-compress pass over `ldeflate`'s own output from
470 /// paying twice — this is that claim, asserted rather than stated.
471 ///
472 /// `compress_everything()` produces the fixtures so the probe cannot be used
473 /// to manufacture its own evidence, and the `FLG` values must genuinely
474 /// differ across the level range, else a single accidental constant would
475 /// prove nothing.
476 #[test]
477 fn this_crates_own_zlib_output_is_recognised() {
478 let payload = b"the quick brown fox jumps over the lazy dog. ".repeat(40);
479 let refs = [payload.as_slice()];
480 let mut seen_flg = std::collections::BTreeSet::new();
481
482 for level in [0u32, 1, 5, 6, 9] {
483 let cfg = crate::Config {
484 level,
485 container: crate::Container::Zlib,
486 ..crate::Config::default()
487 }
488 .compress_everything();
489 let out = crate::compress_objects(&refs, &cfg).expect("compress");
490 let z = &out[0];
491 assert!(
492 is_zlib_stream(z),
493 "level {level}: own output header {:02x?} not recognised",
494 &z[..2]
495 );
496 assert!(
497 looks_compressed(z),
498 "level {level}: own output must be stored on re-compress"
499 );
500 seen_flg.insert(z[1]);
501 }
502 assert!(
503 seen_flg.len() > 1,
504 "the levels must actually differ in FLG, else this proves nothing: {seen_flg:02x?}"
505 );
506 }
507
508 /// The git case, both halves, and they need opposite answers:
509 ///
510 /// * a **loose object file** is the canonical form zlib-deflated — an oid for
511 /// a name, no extension, and it must be stored raw;
512 /// * the **canonical form itself** (`"<type> <size>\0<content>"`) is what a
513 /// `znippy-plugin-git` entry holds. It is inflated bytes, compresses well,
514 /// and must reach the coder.
515 ///
516 /// A rule of the shape "an oid-keyed entry is already compressed" gets the
517 /// second one backwards and silently stores compressible data raw.
518 #[test]
519 fn a_real_loose_object_is_recognised_and_its_canonical_form_is_not() {
520 for kind in ["blob", "tree", "commit", "tag"] {
521 let body = b"fn main() { println!(\"hello\"); }\n".repeat(8);
522 let mut canonical = format!("{kind} {}\0", body.len()).into_bytes();
523 canonical.extend_from_slice(&body);
524
525 assert!(
526 !looks_compressed(&canonical),
527 "canonical {kind} bytes are inflated and must be compressed"
528 );
529
530 let cfg = crate::Config {
531 container: crate::Container::Zlib,
532 ..crate::Config::default()
533 }
534 .compress_everything();
535 let refs = [canonical.as_slice()];
536 let loose = crate::compress_objects(&refs, &cfg).expect("compress");
537 assert!(
538 is_zlib_stream(&loose[0]),
539 "{kind}: the zlib header itself must be recognised"
540 );
541 assert!(
542 looks_compressed(&loose[0]),
543 "a git loose object must be stored raw"
544 );
545 }
546 }
547
548 /// A plausible first byte is not a zlib stream. `x` is `0x78`, the CMF of
549 /// every stream git emits, so text starting with `x` is the exact trap the
550 /// `FDICT` clause exists for.
551 #[test]
552 fn text_that_starts_like_a_zlib_header_is_still_compressed() {
553 for (bytes, why) in [
554 (b"x = 1;\n".as_slice(), "FLG 0x20 sets FDICT"),
555 (b"x is a variable".as_slice(), "FLG 0x20 sets FDICT"),
556 (b"x?y".as_slice(), "FLG 0x3f sets FDICT"),
557 (b"x}".as_slice(), "FLG 0x7d sets FDICT"),
558 (b"xyzzy".as_slice(), "FLG 0x79 fails the mod-31 check"),
559 (b"xx".as_slice(), "FLG 0x78 fails the mod-31 check"),
560 (b"\x78".as_slice(), "a lone CMF is not a header"),
561 (
562 b"\x18\x9c".as_slice(),
563 "CM and FDICT are fine, but 0x189c fails the mod-31 check",
564 ),
565 ] {
566 assert!(!is_zlib_stream(bytes), "{bytes:?} is not zlib: {why}");
567 assert!(
568 !looks_compressed(bytes),
569 "{bytes:?} must still be compressed"
570 );
571 }
572 }
573
574 /// The negatives the reference implementation kept, which this file's own
575 /// text cases do not cover: a would-be magic truncated below its own length,
576 /// and an ELF header (a binary that compresses well and must not be mistaken
577 /// for a container).
578 #[test]
579 fn compressible_content_and_truncated_magics_are_left_alone() {
580 for (bytes, what) in [
581 (
582 b"SELECT * FROM njord WHERE id = 42;\n".as_slice(),
583 "plain SQL",
584 ),
585 (
586 b"{\"lake\": \"njord\", \"tables\": [1, 2, 3]}\n".as_slice(),
587 "json",
588 ),
589 (
590 b"pub fn main() -> Result<()> { Ok(()) }\n".as_slice(),
591 "rust source",
592 ),
593 (b"<?xml version=\"1.0\"?><project/>\n".as_slice(), "xml"),
594 (b"\x7fELF\x02\x01\x01\x00".as_slice(), "an ELF binary"),
595 (b"".as_slice(), "nothing at all"),
596 (b"P".as_slice(), "one byte of a would-be PACK"),
597 (b"PAC".as_slice(), "three bytes of a would-be PACK"),
598 ] {
599 assert!(!looks_compressed(bytes), "{what} must still be compressed");
600 }
601 }
602}