pub const SNIFF_PREFIX_LEN: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContentHint {
#[default]
Unknown,
AlreadyCompressed,
Compressible,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SkipPolicy {
hint: ContentHint,
}
impl SkipPolicy {
pub const fn resolve() -> Self {
Self {
hint: ContentHint::Unknown,
}
}
pub const fn already_compressed() -> Self {
Self {
hint: ContentHint::AlreadyCompressed,
}
}
pub const fn compress_everything() -> Self {
Self {
hint: ContentHint::Compressible,
}
}
pub const fn from_hint(hint: ContentHint) -> Self {
Self { hint }
}
pub const fn hint(&self) -> ContentHint {
self.hint
}
#[inline]
pub fn skip(&self, src: &[u8]) -> bool {
match self.hint {
ContentHint::AlreadyCompressed => true,
ContentHint::Compressible => false,
ContentHint::Unknown => looks_compressed(src),
}
}
}
type Magic = (&'static [u8], &'static str);
const MAGICS: &[Magic] = &[
(b"PACK", "git packfile"),
(b"\xfftOc", "git pack index v2"),
(b"MIDX", "git multi-pack-index"),
(b"BITM", "git pack bitmap (EWAH)"),
(b"\x1f\x8b", "gzip"),
(b"\x28\xb5\x2f\xfd", "zstd frame"),
(b"\xfd7zXZ\x00", "xz"),
(b"\x04\x22\x4d\x18", "lz4 frame"),
(b"7z\xbc\xaf\x27\x1c", "7z"),
(b"Rar!\x1a\x07", "rar"),
(b"PK\x03\x04", "zip"),
(b"PK\x05\x06", "zip (empty archive)"),
(b"PK\x07\x08", "zip (spanned)"),
(b"\x89PNG\r\n\x1a\n", "png"),
(b"\xff\xd8\xff", "jpeg"),
(b"GIF87a", "gif"),
(b"GIF89a", "gif"),
];
pub fn looks_compressed(prefix: &[u8]) -> bool {
let head = &prefix[..prefix.len().min(SNIFF_PREFIX_LEN)];
if MAGICS.iter().any(|(pat, _)| head.starts_with(pat)) {
return true;
}
if head.len() >= 4 && head.starts_with(b"BZh") && head[3].is_ascii_digit() && head[3] != b'0' {
return true;
}
if head.len() >= 12 && head.starts_with(b"RIFF") && &head[8..12] == b"WEBP" {
return true;
}
is_zlib_stream(head)
}
pub fn is_zlib_stream(prefix: &[u8]) -> bool {
let [cmf, flg, ..] = prefix else { return false };
let (cmf, flg) = (*cmf, *flg);
cmf & 0x0f == 8
&& cmf >> 4 <= 7
&& flg & 0x20 == 0
&& (u16::from(cmf) << 8 | u16::from(flg)) % 31 == 0
}
const STORED_MAX: usize = u16::MAX as usize;
pub fn stored_deflate(src: &[u8], is_last: bool) -> Vec<u8> {
let blocks = src.len().div_ceil(STORED_MAX).max(1);
let mut out = Vec::with_capacity(src.len() + 5 * blocks + 5);
let mut chunks = src.chunks(STORED_MAX).peekable();
if chunks.peek().is_none() {
push_stored_block(&mut out, &[], is_last);
return out;
}
while let Some(chunk) = chunks.next() {
let last_block = is_last && chunks.peek().is_none();
push_stored_block(&mut out, chunk, last_block);
}
out
}
#[inline]
fn push_stored_block(out: &mut Vec<u8>, chunk: &[u8], is_last: bool) {
debug_assert!(chunk.len() <= STORED_MAX);
out.push(if is_last { 1 } else { 0 });
let len = chunk.len() as u16;
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(&(!len).to_le_bytes());
out.extend_from_slice(chunk);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_magic_in_the_table_is_recognised_at_its_own_length() {
for (pat, label) in MAGICS {
assert!(
looks_compressed(pat),
"{label}: not recognised from its own {} magic bytes",
pat.len()
);
}
}
#[test]
fn the_special_cased_probes_fire_only_on_their_real_shape() {
assert!(looks_compressed(b"BZh9\x31\x41\x59\x26"));
assert!(looks_compressed(b"BZh1"));
assert!(
!looks_compressed(b"BZh0"),
"'0' is not a valid bzip2 block size"
);
assert!(
!looks_compressed(b"BZhx"),
"a non-digit is not a block size"
);
assert!(
!looks_compressed(b"BZh"),
"three bytes cannot carry the digit"
);
assert!(looks_compressed(b"RIFF\x00\x00\x00\x00WEBPVP8 "));
assert!(
!looks_compressed(b"RIFF\x00\x00\x00\x00WAVEfmt "),
"a RIFF WAVE is not compressed"
);
assert!(
!looks_compressed(b"RIFF\x00\x00\x00\x00WEB"),
"truncated form type"
);
}
#[test]
fn the_zlib_probe_accepts_real_headers_and_rejects_text() {
for h in [[0x78u8, 0x01], [0x78, 0x9c], [0x78, 0xda]] {
assert!(is_zlib_stream(&h), "{h:02x?} is a real zlib header");
assert!(looks_compressed(&h));
}
assert!(!is_zlib_stream(&[0x77, 0x9c]), "CM != 8");
assert!(!is_zlib_stream(&[0x88, 0x9c]), "CINFO > 7");
assert!(!is_zlib_stream(&[0x78, 0xbb]), "FDICT set");
assert!(!is_zlib_stream(&[0x78, 0x9d]), "check bits fail");
assert!(!is_zlib_stream(&[0x78]), "one byte is not a header");
assert!(!is_zlib_stream(&[]), "empty is not a header");
for text in [
&b"fn main() { println!(\"hi\"); }"[..],
b"the quick brown fox jumps over the lazy dog",
b"{\"key\": \"value\", \"n\": 1}",
b"<?xml version=\"1.0\"?><osm/>",
b"# heading\n\nsome prose\n",
b"\0\0\0\0\0\0\0\0",
] {
assert!(
!looks_compressed(text),
"false positive on {:?}",
&text[..text.len().min(12)]
);
}
}
#[test]
fn the_probe_reads_only_the_head() {
let mut v = vec![b'a'; 4 << 20];
v.extend_from_slice(b"\x89PNG\r\n\x1a\n");
assert!(!looks_compressed(&v), "a magic in the tail is not a magic");
assert!(
looks_compressed(b"\x89PNG\r\n\x1a\nrest"),
"but one at the head is"
);
}
#[test]
fn a_hint_beats_the_bytes_in_both_directions() {
let png = b"\x89PNG\r\n\x1a\n....";
let text = b"plain text, very compressible indeed";
assert!(SkipPolicy::resolve().skip(png));
assert!(!SkipPolicy::resolve().skip(text));
assert!(
SkipPolicy::already_compressed().skip(text),
"hint must override the probe"
);
assert!(
!SkipPolicy::compress_everything().skip(png),
"a Compressible hint is never vetoed by a probe"
);
assert_eq!(
SkipPolicy::default(),
SkipPolicy::resolve(),
"the probe is the default"
);
}
#[test]
fn a_stored_block_is_framed_exactly_as_rfc1951_says() {
let out = stored_deflate(b"abc", true);
assert_eq!(out, vec![0x01, 0x03, 0x00, 0xfc, 0xff, b'a', b'b', b'c']);
let non_final = stored_deflate(b"abc", false);
assert_eq!(
non_final[0], 0x00,
"BFINAL must be clear on a non-final block"
);
assert_eq!(&non_final[1..5], &[0x03, 0x00, 0xfc, 0xff]);
}
#[test]
fn an_empty_input_still_emits_one_block() {
assert_eq!(
stored_deflate(b"", true),
vec![0x01, 0x00, 0x00, 0xff, 0xff]
);
}
#[test]
fn a_payload_past_the_block_limit_splits_and_only_the_last_is_final() {
let src = vec![0xABu8; STORED_MAX + 1];
let out = stored_deflate(&src, true);
assert_eq!(
out.len(),
src.len() + 10,
"two blocks, five framing bytes each"
);
assert_eq!(out[0], 0x00, "the first of two blocks is not final");
assert_eq!(
&out[1..5],
&[0xff, 0xff, 0x00, 0x00],
"LEN = 65535, ~LEN = 0"
);
let second = STORED_MAX + 5;
assert_eq!(out[second], 0x01, "the last block is final");
assert_eq!(
&out[second + 1..second + 5],
&[0x01, 0x00, 0xfe, 0xff],
"LEN = 1"
);
}
#[test]
fn stored_output_inflates_back_to_the_input() {
for len in [
0usize,
1,
255,
STORED_MAX - 1,
STORED_MAX,
STORED_MAX + 1,
3 * STORED_MAX + 7,
] {
let src: Vec<u8> = (0..len).map(|i| (i * 31 + 7) as u8).collect();
let body = stored_deflate(&src, true);
let mut out = vec![0u8; len + linflate::OVERWRITE_HEADROOM];
let n = linflate::inflate_segment(&body, &mut out)
.unwrap_or_else(|e| panic!("len {len}: stored output did not inflate: {e:?}"));
assert_eq!(n, len, "len {len}: wrong output length");
assert_eq!(
&out[..n],
&src[..],
"len {len}: stored output did not round-trip"
);
}
}
#[test]
fn this_crates_own_zlib_output_is_recognised() {
let payload = b"the quick brown fox jumps over the lazy dog. ".repeat(40);
let refs = [payload.as_slice()];
let mut seen_flg = std::collections::BTreeSet::new();
for level in [0u32, 1, 5, 6, 9] {
let cfg = crate::Config {
level,
container: crate::Container::Zlib,
..crate::Config::default()
}
.compress_everything();
let out = crate::compress_objects(&refs, &cfg).expect("compress");
let z = &out[0];
assert!(
is_zlib_stream(z),
"level {level}: own output header {:02x?} not recognised",
&z[..2]
);
assert!(
looks_compressed(z),
"level {level}: own output must be stored on re-compress"
);
seen_flg.insert(z[1]);
}
assert!(
seen_flg.len() > 1,
"the levels must actually differ in FLG, else this proves nothing: {seen_flg:02x?}"
);
}
#[test]
fn a_real_loose_object_is_recognised_and_its_canonical_form_is_not() {
for kind in ["blob", "tree", "commit", "tag"] {
let body = b"fn main() { println!(\"hello\"); }\n".repeat(8);
let mut canonical = format!("{kind} {}\0", body.len()).into_bytes();
canonical.extend_from_slice(&body);
assert!(
!looks_compressed(&canonical),
"canonical {kind} bytes are inflated and must be compressed"
);
let cfg = crate::Config {
container: crate::Container::Zlib,
..crate::Config::default()
}
.compress_everything();
let refs = [canonical.as_slice()];
let loose = crate::compress_objects(&refs, &cfg).expect("compress");
assert!(
is_zlib_stream(&loose[0]),
"{kind}: the zlib header itself must be recognised"
);
assert!(
looks_compressed(&loose[0]),
"a git loose object must be stored raw"
);
}
}
#[test]
fn text_that_starts_like_a_zlib_header_is_still_compressed() {
for (bytes, why) in [
(b"x = 1;\n".as_slice(), "FLG 0x20 sets FDICT"),
(b"x is a variable".as_slice(), "FLG 0x20 sets FDICT"),
(b"x?y".as_slice(), "FLG 0x3f sets FDICT"),
(b"x}".as_slice(), "FLG 0x7d sets FDICT"),
(b"xyzzy".as_slice(), "FLG 0x79 fails the mod-31 check"),
(b"xx".as_slice(), "FLG 0x78 fails the mod-31 check"),
(b"\x78".as_slice(), "a lone CMF is not a header"),
(
b"\x18\x9c".as_slice(),
"CM and FDICT are fine, but 0x189c fails the mod-31 check",
),
] {
assert!(!is_zlib_stream(bytes), "{bytes:?} is not zlib: {why}");
assert!(
!looks_compressed(bytes),
"{bytes:?} must still be compressed"
);
}
}
#[test]
fn compressible_content_and_truncated_magics_are_left_alone() {
for (bytes, what) in [
(
b"SELECT * FROM njord WHERE id = 42;\n".as_slice(),
"plain SQL",
),
(
b"{\"lake\": \"njord\", \"tables\": [1, 2, 3]}\n".as_slice(),
"json",
),
(
b"pub fn main() -> Result<()> { Ok(()) }\n".as_slice(),
"rust source",
),
(b"<?xml version=\"1.0\"?><project/>\n".as_slice(), "xml"),
(b"\x7fELF\x02\x01\x01\x00".as_slice(), "an ELF binary"),
(b"".as_slice(), "nothing at all"),
(b"P".as_slice(), "one byte of a would-be PACK"),
(b"PAC".as_slice(), "three bytes of a would-be PACK"),
] {
assert!(!looks_compressed(bytes), "{what} must still be compressed");
}
}
}