ferrosys 0.8.0

Pure-Rust filesystem formatter and reader: ext4, ext3, ext2, FAT32, FAT16, FAT12, exFAT, btrfs, and APFS — rootless, in userspace, byte-reproducible
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Undoing the six encodings a filesystem stores a run of bytes in fewer of them.
//!
//! A format that compresses records, per run of bytes, which algorithm produced them and how
//! many bytes they expand to. Everything above this module knows that much and no more: it
//! hands over the bytes on the volume and a buffer the size the record declared, and what
//! comes back is the file's own bytes or a refusal naming what could not be undone.
//!
//! This module is pure — bytes in, bytes out, no I/O — and it is at the crate root rather than
//! inside a family for the reason [`crc32c`](crate::crc32c()) is: an encoding is a property of a
//! run of bytes rather than of the format around it, and the same algorithms appear in more than
//! one filesystem. What is *not* here is how a format frames them — how many streams
//! one extent is cut into, and where each begins — which is the format's own and belongs to
//! it.
//!
//! # One signature, six algorithms, and a bound that is the caller's
//!
//! Each decoder fills a caller-supplied slice and reports how much of it was filled. That
//! shape is deliberate: the expected length is a number the *image* supplied, so the only
//! place it can be judged is above this module, where what the format allows is known. A
//! decoder here never allocates on the strength of it, and so cannot be asked for a gibibyte
//! by a record claiming one.
//!
//! Producing fewer bytes than the buffer holds is not an error here, and may be one to the
//! caller: what it means is that the stream ended early, and whether that is a fault depends
//! on what the caller asked for. So the comparison, and the name for what it found, are the
//! caller's.
//!
//! # Each algorithm is a feature, and a build without one says so
//!
//! [`Algorithm`] names all six whatever a build carries, because *recognizing* an encoding
//! and *undoing* it are different questions and a reader has to answer the first either way: a
//! file this build cannot decode is reported as one it cannot decode, naming the algorithm,
//! rather than as a file whose bytes are what the volume holds.
//!
//! LZO's and LZBITMAP's decoders are this crate's own, DEFLATE's and Zstandard's are
//! `miniz_oxide`'s and `ruzstd`'s, and LZVN's and LZFSE's are `ferrosys-lzfse`'s, derived from
//! Apple's lzfse project and under its BSD-3-Clause license. [`decompress`] gives every answer
//! in this module's terms, so a caller meets one [`Error`] whichever crate decoded the stream.

/// Which encoding a run of bytes on a volume is in.
///
/// Every variant exists in every build. What a feature decides is whether
/// [`decompress`] can undo it, which [`Algorithm::available`] answers.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Algorithm {
    // Each is constructed by the family that stores runs in it, so a build without that
    // family names it and never meets it.
    /// DEFLATE, as `zlib` frames it.
    #[cfg_attr(not(feature = "btrfs"), allow(dead_code))]
    Zlib,
    /// LZO1X.
    #[cfg_attr(not(feature = "btrfs"), allow(dead_code))]
    Lzo,
    /// Zstandard.
    #[cfg_attr(not(feature = "btrfs"), allow(dead_code))]
    Zstd,
    /// LZVN, an encoding an APFS compressed file stores its content in.
    #[cfg_attr(not(feature = "apfs"), allow(dead_code))]
    Lzvn,
    /// LZFSE, another.
    #[cfg_attr(not(feature = "apfs"), allow(dead_code))]
    Lzfse,
    /// LZBITMAP, a third.
    #[cfg_attr(not(feature = "apfs"), allow(dead_code))]
    Lzbitmap,
}

impl Algorithm {
    /// The name this algorithm is known by, which is the word a refusal names it with.
    pub(crate) const fn name(self) -> &'static str {
        match self {
            Algorithm::Zlib => "zlib",
            Algorithm::Lzo => "lzo",
            Algorithm::Zstd => "zstd",
            Algorithm::Lzvn => "lzvn",
            Algorithm::Lzfse => "lzfse",
            Algorithm::Lzbitmap => "lzbitmap",
        }
    }

    /// Whether this build can undo this encoding.
    ///
    /// A caller asks before it reaches for bytes it would have to refuse: a filesystem whose
    /// *feature word* says some extent is LZO-compressed is one a build without that decoder
    /// should decline as a whole, rather than open and fail partway through a walk.
    pub(crate) const fn available(self) -> bool {
        match self {
            Algorithm::Zlib => cfg!(feature = "zlib"),
            Algorithm::Lzo => cfg!(feature = "lzo"),
            Algorithm::Zstd => cfg!(feature = "zstd"),
            Algorithm::Lzvn => cfg!(feature = "lzvn"),
            Algorithm::Lzfse => cfg!(feature = "lzfse"),
            Algorithm::Lzbitmap => cfg!(feature = "lzbitmap"),
        }
    }
}

/// The clause a refusal ends with when a read stops for want of a decoder: which Cargo feature
/// compiles it. Each decoder's feature is named for its algorithm.
///
/// Every refusal of a compressed file ends with this one — the shared decoder's, and each
/// family's own, which names the inode as well — so a build left without a decoder says how to
/// get it in the same words wherever a read stops. It writes nothing for `None`, which is an
/// encoding no feature decodes: a value the format leaves undefined.
pub(crate) struct CompiledBy(pub(crate) Option<Algorithm>);

impl std::fmt::Display for CompiledBy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            Some(algorithm) => write!(
                f,
                "; the `{}` feature compiles its decoder",
                algorithm.name()
            ),
            None => Ok(()),
        }
    }
}

/// Why a run of compressed bytes could not be turned back into the bytes it stands for.
///
/// The three are kept apart because they mean different things about the image: a stream this
/// build has no decoder for is a filesystem that is *fine* and beyond this build, and a stream
/// that does not decode, or that decodes to more than the record framing it declared, is
/// damage.
///
/// A stream that decodes to *fewer* bytes than the record declared is not here, and that is
/// deliberate: what a caller asked for decides whether a short run is a fault, so it is the
/// caller that compares the two and names it in its own terms.
// A build carrying no decoder constructs only `Unavailable` — which is the honest state of
// such a build rather than an oversight, so the other two are allowed to go unbuilt there.
#[cfg_attr(
    not(any(
        feature = "zlib",
        feature = "lzo",
        feature = "zstd",
        feature = "lzvn",
        feature = "lzbitmap"
    )),
    allow(dead_code)
)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub(crate) enum Error {
    /// This build carries no decoder for the algorithm.
    #[error(
        "{} is an algorithm this build does not decode{}",
        .0.name(),
        CompiledBy(Some(*.0))
    )]
    Unavailable(Algorithm),
    /// The stream is not a well-formed one of its kind.
    #[error("the {} stream does not decode: {fault}", .algorithm.name())]
    #[non_exhaustive]
    Malformed {
        /// Which encoding it claimed to be.
        algorithm: Algorithm,
        /// What was wrong with it.
        fault: &'static str,
    },
    /// The stream expands past the buffer it was given, so the record's declared length is
    /// not the length of what it holds.
    #[error(
        "the {} stream expands past the {expected} bytes the record declares",
        .algorithm.name()
    )]
    #[non_exhaustive]
    Overrun {
        /// Which encoding it was.
        algorithm: Algorithm,
        /// The buffer's length, which is what the record said the run expands to.
        expected: usize,
    },
}

/// Undo one stream into `out`, returning how many bytes it produced.
///
/// `out` is sized by the caller from what the format recorded, and it bounds the work: a
/// stream that would expand past it is [`Error::Overrun`] rather than an allocation.
///
/// # Errors
///
/// [`Error::Unavailable`] where this build carries no decoder for `algorithm`, and otherwise
/// whatever the stream turns out to be wrong about.
// A build carrying none of the decoders reaches only the last arm, which needs neither the bytes
// nor the room. The names stay, because they are the signature every build offers.
#[cfg_attr(
    not(any(
        feature = "zlib",
        feature = "lzo",
        feature = "zstd",
        feature = "lzvn",
        feature = "lzbitmap"
    )),
    allow(unused_variables)
)]
pub(crate) fn decompress(
    algorithm: Algorithm,
    input: &[u8],
    out: &mut [u8],
) -> Result<usize, Error> {
    match algorithm {
        #[cfg(feature = "zlib")]
        Algorithm::Zlib => zlib::decompress(input, out),
        #[cfg(feature = "lzo")]
        Algorithm::Lzo => lzo::decompress(input, out),
        #[cfg(feature = "zstd")]
        Algorithm::Zstd => zstd::decompress(input, out),
        #[cfg(feature = "lzvn")]
        Algorithm::Lzvn => lifted(Algorithm::Lzvn, ferrosys_lzfse::decompress_lzvn(input, out)),
        #[cfg(feature = "lzfse")]
        Algorithm::Lzfse => lifted(
            Algorithm::Lzfse,
            ferrosys_lzfse::decompress_lzfse(input, out),
        ),
        #[cfg(feature = "lzbitmap")]
        Algorithm::Lzbitmap => lzbitmap::decompress(input, out),
        // Whichever of the algorithms this build did not take. Reached only through a caller that
        // did not ask `available` first, which is a caller reporting a file it cannot read
        // rather than one refusing a filesystem it cannot open.
        #[allow(unreachable_patterns)]
        other => Err(Error::Unavailable(other)),
    }
}

#[cfg(feature = "zlib")]
mod zlib {
    use super::{Algorithm, Error};

    /// Undo one zlib-framed DEFLATE stream into `out`.
    ///
    /// The whole stream at once rather than in pieces: a compressed run is bounded by what
    /// the format allows an extent to expand to, which is measured in kibibytes.
    pub(super) fn decompress(input: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        use miniz_oxide::inflate::TINFLStatus;

        // `zlib_header = true` because the format stores the two-byte wrapper, and the
        // trailing Adler-32 is checked rather than ignored: it costs nothing here and it is a
        // second opinion on bytes a filesystem's own checksum has already covered.
        miniz_oxide::inflate::decompress_slice_iter_to_slice(
            out,
            core::iter::once(input),
            true,
            false,
        )
        .map_err(|status| match status {
            // The decoder stops with this exactly where the output buffer filled, which for
            // this caller means the record's declared length is short of what the stream
            // expands to.
            TINFLStatus::HasMoreOutput => Error::Overrun {
                algorithm: Algorithm::Zlib,
                expected: out.len(),
            },
            TINFLStatus::NeedsMoreInput | TINFLStatus::FailedCannotMakeProgress => {
                Error::Malformed {
                    algorithm: Algorithm::Zlib,
                    fault: "the stream ends mid-symbol",
                }
            }
            TINFLStatus::BadParam => Error::Malformed {
                algorithm: Algorithm::Zlib,
                fault: "the stream's own parameters are not ones the format defines",
            },
            TINFLStatus::Adler32Mismatch => Error::Malformed {
                algorithm: Algorithm::Zlib,
                fault: "the stream's own checksum does not cover what it decoded to",
            },
            _ => Error::Malformed {
                algorithm: Algorithm::Zlib,
                fault: "the stream is not well-formed",
            },
        })
    }
}

#[cfg(feature = "zstd")]
mod zstd {
    use std::io::Read as _;

    use super::{Algorithm, Error};

    /// The smallest window the Zstandard format defines, which floors the clamp below.
    const MIN_WINDOW: u64 = 1 << 10;

    /// Undo one Zstandard frame into `out`.
    ///
    /// Read into the buffer rather than to the end of the stream, and one byte past it: what
    /// distinguishes a frame that fills the record exactly from one that expands past it is
    /// whether anything follows, and a decoder asked only for `out.len()` bytes cannot say.
    pub(super) fn decompress(input: &[u8], out: &mut [u8]) -> Result<usize, Error> {
        let malformed = |fault| Error::Malformed {
            algorithm: Algorithm::Zstd,
            fault,
        };
        // A frame declares its own window, and the decoder allocates that declaration before
        // producing a byte — the one number in the stream that could otherwise buy an
        // allocation this module's contract says no image-supplied number buys. It is clamped
        // to the caller's buffer: a stream never needs a window past what it decodes to, and
        // an encoder that knows its input sizes the window down to the input's next power of
        // two, so no frame a real writer produces is refused. The format's own floor is kept
        // for the smallest buffers. The decoder holds each block's output to that window, as
        // the format bounds a block, so the clamp bounds what a whole decode holds and not only
        // its history.
        let window_cap = (out.len() as u64).next_power_of_two().max(MIN_WINDOW);
        let mut decoder =
            ruzstd::decoding::StreamingDecoder::new_with_max_window_size(input, window_cap)
                .map_err(|error| match error {
                    ruzstd::decoding::errors::FrameDecoderError::WindowSizeTooBig { .. } => {
                        malformed("the frame declares a window larger than what it decodes into")
                    }
                    _ => malformed("the frame header is not one the format defines"),
                })?;

        let mut filled = 0;
        while filled < out.len() {
            match decoder.read(&mut out[filled..]) {
                Ok(0) => return Ok(filled),
                Ok(n) => filled += n,
                Err(_) => return Err(malformed("the frame does not decode")),
            }
        }
        // One more byte, into a buffer of its own. Anything at all here is a frame longer
        // than the record says it is.
        let mut past = [0u8; 1];
        match decoder.read(&mut past) {
            Ok(0) => Ok(filled),
            Ok(_) => Err(Error::Overrun {
                algorithm: Algorithm::Zstd,
                expected: out.len(),
            }),
            Err(_) => Err(malformed("the frame does not decode")),
        }
    }
}

/// What `ferrosys-lzfse` answered for a stream of `algorithm`, in this module's terms: the two
/// faults it reports are the two this module's [`Error`] carries for every decoder, named here
/// with the algorithm the stream was.
#[cfg(feature = "lzvn")]
fn lifted(
    algorithm: Algorithm,
    answer: Result<usize, ferrosys_lzfse::Error>,
) -> Result<usize, Error> {
    answer.map_err(|error| match error {
        ferrosys_lzfse::Error::Malformed { fault, .. } => Error::Malformed { algorithm, fault },
        ferrosys_lzfse::Error::Overrun { expected, .. } => Error::Overrun {
            algorithm,
            expected,
        },
        // The decoder crate is released with this one and required at exactly its version,
        // so a refusal it adds is named here in the same release. Until it is, a stream the
        // decoder refuses is one that does not decode.
        _ => Error::Malformed {
            algorithm,
            fault: "the decoder refuses the stream",
        },
    })
}

/// Write the `count` bytes from `distance` back at `at` of `out`, a byte at a time: a copy may
/// reach into the run it is producing, so a distance of one and a count of ten is ten copies of
/// one byte, and a block move would read bytes not yet written. `false`, copying nothing, where
/// the distance is zero or reaches before the output's start. The caller holds `at + count` to
/// the output's length.
#[cfg(feature = "lzo")]
fn copy_back(out: &mut [u8], at: usize, distance: usize, count: usize) -> bool {
    if distance == 0 || distance > at {
        return false;
    }
    for i in at..at + count {
        out[i] = out[i - distance];
    }
    true
}

#[cfg(feature = "lzo")]
pub(crate) mod lzo;

#[cfg(feature = "lzbitmap")]
mod lzbitmap;

#[cfg(all(test, feature = "lzvn", feature = "lzfse", feature = "lzbitmap"))]
mod reference;

/// Drive `decode` over every one-byte change of `stream`, a stream it decodes whole, and every
/// cut of it, into `room` bytes, and hold it to the property [`sweep_arbitrary_bytes`] holds
/// it to.
///
/// Arbitrary bytes seldom get past a format's first length field, so a sweep of them reaches
/// the header and little after it. A stream the decoder reads whole, changed one byte at a
/// time, reaches every field after the header: a table, a count, a distance, the last block.
#[cfg(all(
    test,
    any(
        feature = "lzo",
        feature = "zlib",
        feature = "zstd",
        feature = "lzbitmap"
    )
))]
pub(crate) fn sweep_changes_of<E>(
    stream: &[u8],
    room: usize,
    mut decode: impl FnMut(&[u8], &mut [u8]) -> Result<usize, E>,
) {
    const GUARD: u8 = 0xee;
    let mut held = |bytes: &[u8], what: &dyn Fn() -> String| {
        let mut out = vec![GUARD; room + 64];
        if let Ok(produced) = decode(bytes, &mut out[..room]) {
            assert!(produced <= room, "{} reported {produced} of {room}", what());
        }
        assert!(
            out[room..].iter().all(|&b| b == GUARD),
            "{} wrote past the buffer it was given",
            what()
        );
    };
    let mut changed = stream.to_vec();
    for at in 0..stream.len() {
        for value in [
            stream[at] ^ 0x01,
            stream[at] ^ 0x80,
            !stream[at],
            0x00,
            0x7F,
            0xFF,
        ] {
            changed[at] = value;
            held(&changed, &|| format!("byte {at} as {value:#04x}"));
        }
        changed[at] = stream[at];
    }
    for len in 0..stream.len() {
        held(&stream[..len], &|| format!("the first {len} bytes"));
    }
}

/// Drive `decode` over arbitrary bytes and hold it to the one property every layer of this
/// has: whatever it is handed, it either produces bytes inside the buffer it was given or
/// refuses.
///
/// Shared because there is more than one layer to hold to it — a stream, and the framing that
/// cuts an extent into streams — and each reads lengths out of the image that a decoder must
/// check rather than trust. `salt` moves the generator, so two callers sweep different inputs
/// rather than the same ones twice.
///
/// Deterministic and cheap, so it runs on every `cargo test` rather than only under a fuzzer.
/// The buffer is longer than the room offered and the tail is a fixed byte, which is what
/// turns "wrote past the end" from a memory fault into an assertion.
///
/// Compiled with any algorithm whose decoder sweeps: each stream decoder runs it over
/// its own decode, and the LZO framing runs it a second time over the segmenting around the
/// stream.
#[cfg(all(
    test,
    any(
        feature = "lzo",
        feature = "zlib",
        feature = "zstd",
        feature = "lzvn",
        feature = "lzbitmap"
    )
))]
pub(crate) fn sweep_arbitrary_bytes<E>(
    salt: u32,
    mut decode: impl FnMut(&[u8], &mut [u8]) -> Result<usize, E>,
) {
    const GUARD: u8 = 0xee;
    for seed in 0..2048u32 {
        let mut bytes = Vec::new();
        let mut x = seed.wrapping_mul(2_654_435_761).wrapping_add(salt);
        for _ in 0..(seed as usize % 160) + 1 {
            x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
            bytes.push((x >> 16) as u8);
        }
        let mut out = [GUARD; 512];
        let room = out.len() - 64;
        if let Ok(produced) = decode(&bytes, &mut out[..room]) {
            assert!(
                produced <= room,
                "seed {seed} reported {produced} of {room}"
            );
        }
        assert!(
            out[room..].iter().all(|&b| b == GUARD),
            "seed {seed} wrote past the buffer it was given"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_algorithm_is_named_whether_or_not_this_build_decodes_it() {
        // Recognizing an encoding and undoing it are different questions, and a build that
        // answers only the second cannot tell a caller what it is declining.
        for (algorithm, name) in [
            (Algorithm::Zlib, "zlib"),
            (Algorithm::Lzo, "lzo"),
            (Algorithm::Zstd, "zstd"),
            (Algorithm::Lzvn, "lzvn"),
            (Algorithm::Lzfse, "lzfse"),
            (Algorithm::Lzbitmap, "lzbitmap"),
        ] {
            assert_eq!(algorithm.name(), name);
            // And the refusal a build without the decoder gives names it too, with the
            // feature that compiles the decoder.
            assert_eq!(
                Error::Unavailable(algorithm).to_string(),
                format!(
                    "{name} is an algorithm this build does not decode; the `{name}` feature \
                     compiles its decoder"
                )
            );
        }
    }

    #[test]
    fn the_feature_a_refusal_names_is_one_the_manifest_declares() {
        // A refusal tells a caller which feature to turn on, so the word it names has to be a
        // feature someone can turn on — not merely the algorithm's name.
        let manifest = include_str!("../Cargo.toml");
        let features = manifest
            .split("\n[features]\n")
            .nth(1)
            .and_then(|rest| rest.split("\n[").next())
            .expect("the manifest has a [features] table");
        let declared: Vec<&str> = features
            .lines()
            .filter_map(|line| line.split_once(" = ").map(|(name, _)| name.trim()))
            .filter(|name| !name.starts_with('#'))
            .collect();
        for algorithm in [
            Algorithm::Zlib,
            Algorithm::Lzo,
            Algorithm::Zstd,
            Algorithm::Lzvn,
            Algorithm::Lzfse,
            Algorithm::Lzbitmap,
        ] {
            assert!(
                declared.contains(&algorithm.name()),
                "`{}` is not a feature in {declared:?}",
                algorithm.name()
            );
        }
        // An encoding no feature decodes adds nothing.
        assert_eq!(CompiledBy(None).to_string(), "");
    }

    #[test]
    fn an_algorithm_this_build_does_not_carry_is_refused_rather_than_attempted() {
        // The one property this dispatch has in every configuration: what it will not do is
        // decode a stream with the wrong decoder. Whichever of them is absent here reports
        // itself absent, and whichever are present do not.
        for algorithm in [
            Algorithm::Zlib,
            Algorithm::Lzo,
            Algorithm::Zstd,
            Algorithm::Lzvn,
            Algorithm::Lzfse,
            Algorithm::Lzbitmap,
        ] {
            let mut out = [0u8; 8];
            let refused = decompress(algorithm, b"", &mut out);
            assert_eq!(
                matches!(refused, Err(Error::Unavailable(_))),
                !algorithm.available(),
                "{algorithm:?} reported itself {} and answered {refused:?}",
                if algorithm.available() {
                    "available"
                } else {
                    "unavailable"
                }
            );
        }
    }

    #[cfg(feature = "zlib")]
    #[test]
    fn a_zlib_stream_decodes_to_what_it_stands_for() {
        // A stream produced outside this crate: the bytes below are what `python3 -c
        // "import zlib; zlib.compress(b'ferrosys' * 8, 9)"` emits, recorded here so the
        // decoder is held against an encoder it shares no code with.
        const STREAM: &[u8] = &[
            0x78, 0xda, 0x4b, 0x4b, 0x2d, 0x2a, 0xca, 0x2f, 0xae, 0x2c, 0x4e, 0x23, 0x93, 0x06,
            0x00, 0x88, 0x65, 0x1b, 0xe9,
        ];
        let want = b"ferrosys".repeat(8);
        let mut out = vec![0u8; want.len()];
        assert_eq!(
            decompress(Algorithm::Zlib, STREAM, &mut out),
            Ok(want.len())
        );
        assert_eq!(out, want);

        // A buffer one byte short of what the stream expands to: the record's declared
        // length disagreeing with its contents is a refusal, never a short read reported as
        // a whole one.
        let mut small = vec![0u8; want.len() - 1];
        assert!(matches!(
            decompress(Algorithm::Zlib, STREAM, &mut small),
            Err(Error::Overrun { .. })
        ));

        // And bytes that are not a stream at all.
        let mut out = vec![0u8; 64];
        assert!(matches!(
            decompress(Algorithm::Zlib, b"not a stream", &mut out),
            Err(Error::Malformed { .. })
        ));
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn a_zstd_frame_declaring_a_giant_window_is_refused_at_the_header() {
        // Six bytes: the magic, a descriptor saying a window descriptor follows, and that
        // descriptor naming a 64-mebibyte window. The record it would decode into holds four
        // kibibytes, and a stream never needs a window past what it decodes to — so the
        // declaration is refused at the header, before the decoder allocates what it names.
        // The fault names the window specifically: reaching the generic header refusal here
        // would mean the frame was *accepted* at the header and sixty-four mebibytes were
        // bought by six bytes of input.
        const FRAME: &[u8] = &[0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x80];
        let mut out = vec![0u8; 4096];
        assert_eq!(
            decompress(Algorithm::Zstd, FRAME, &mut out),
            Err(Error::Malformed {
                algorithm: Algorithm::Zstd,
                fault: "the frame declares a window larger than what it decodes into",
            })
        );
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn a_zstd_block_expanding_past_its_window_is_refused_rather_than_produced() {
        // Laid out by hand from RFC 8878: a frame whose window descriptor follows, one raw
        // block of the byte `A`, and a last compressed block holding no literals and one
        // sequence — the three codes each in RLE mode, a copy of 65,539 bytes at offset 1 —
        // whose bitstream is the marker bit over eighteen zero bits. The format bounds what one
        // block expands to by the frame's window, and the window clamp above bounds memory
        // only because the decoder holds a block to it: a frame of a few kilobytes made of such
        // sequences otherwise expands to gigabytes inside the decoder, before the record's
        // declared size is ever compared. So the same block is refused under a four-kibibyte
        // window as a frame that does not decode, which is the decoder's refusal, rather than
        // as one that expands past the record, which is this module's after the block was
        // produced; and it decodes under a window that holds it, which makes the frame well
        // formed in everything else.
        const fn frame(window: u8) -> [u8; 22] {
            [
                0x28, 0xb5, 0x2f, 0xfd, 0x00, window, 0x08, 0x00, 0x00, b'A', 0x4d, 0x00, 0x00,
                0x00, 0x01, 0x54, 0x00, 0x02, 0x34, 0x00, 0x00, 0x04,
            ]
        }
        let mut out = vec![0u8; 4096];
        assert_eq!(
            decompress(Algorithm::Zstd, &frame(0x10), &mut out),
            Err(Error::Malformed {
                algorithm: Algorithm::Zstd,
                fault: "the frame does not decode",
            })
        );

        let mut out = vec![0u8; 1 + 65_539];
        assert_eq!(
            decompress(Algorithm::Zstd, &frame(0x38), &mut out),
            Ok(out.len())
        );
        assert!(out.iter().all(|&byte| byte == b'A'));
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn a_zstd_frame_decodes_to_what_it_stands_for() {
        // As above, produced outside this crate: `zstd -19` over the same bytes.
        const FRAME: &[u8] = &[
            0x28, 0xb5, 0x2f, 0xfd, 0x24, 0x40, 0x7d, 0x00, 0x00, 0x48, 0x66, 0x65, 0x72, 0x72,
            0x6f, 0x73, 0x79, 0x73, 0x66, 0x01, 0x00, 0x7c, 0xde, 0x23, 0x80, 0xc5, 0xf4, 0x04,
        ];
        let want = b"ferrosys".repeat(8);
        let mut out = vec![0u8; want.len()];
        assert_eq!(decompress(Algorithm::Zstd, FRAME, &mut out), Ok(want.len()));
        assert_eq!(out, want);

        let mut small = vec![0u8; want.len() - 1];
        assert!(matches!(
            decompress(Algorithm::Zstd, FRAME, &mut small),
            Err(Error::Overrun { .. })
        ));

        let mut out = vec![0u8; 64];
        assert!(matches!(
            decompress(Algorithm::Zstd, b"not a frame at all", &mut out),
            Err(Error::Malformed { .. })
        ));
    }

    // The deterministic never-panic sweeps, one per decoder this build carries: arbitrary
    // bytes either refuse or fit the buffer offered, and nothing is written past it. The
    // hand vectors above pin what a correct stream decodes to; these pin what every other
    // input does. The salts keep them from sweeping the same bytes.

    #[cfg(feature = "zlib")]
    #[test]
    fn arbitrary_bytes_are_a_zlib_stream_that_refuses_or_fits() {
        sweep_arbitrary_bytes(2, |bytes, out| decompress(Algorithm::Zlib, bytes, out));
    }

    #[cfg(feature = "zstd")]
    #[test]
    fn arbitrary_bytes_are_a_zstd_frame_that_refuses_or_fits() {
        sweep_arbitrary_bytes(3, |bytes, out| decompress(Algorithm::Zstd, bytes, out));
    }

    #[cfg(feature = "lzvn")]
    #[test]
    fn arbitrary_bytes_are_an_lzvn_stream_that_refuses_or_fits() {
        sweep_arbitrary_bytes(4, |bytes, out| decompress(Algorithm::Lzvn, bytes, out));
    }

    #[cfg(feature = "zlib")]
    #[test]
    fn a_zlib_stream_changed_a_byte_at_a_time_refuses_or_fits() {
        // The stream `a_zlib_stream_decodes_to_what_it_stands_for` holds the decoder to.
        const STREAM: &[u8] = &[
            0x78, 0xda, 0x4b, 0x4b, 0x2d, 0x2a, 0xca, 0x2f, 0xae, 0x2c, 0x4e, 0x23, 0x93, 0x06,
            0x00, 0x88, 0x65, 0x1b, 0xe9,
        ];
        sweep_changes_of(STREAM, 64 + 16, |bytes, out| {
            decompress(Algorithm::Zlib, bytes, out)
        });
    }

    #[cfg(feature = "lzfse")]
    #[test]
    fn arbitrary_bytes_are_an_lzfse_stream_that_refuses_or_fits() {
        // Arbitrary bytes seldom open with a block's magic, so each is given one of the four
        // kinds to open with and is swept as that kind's body.
        for (i, magic) in [b"bvx-", b"bvxn", b"bvx2", b"bvx$"].into_iter().enumerate() {
            sweep_arbitrary_bytes(5 + i as u32, |bytes, out| {
                let stream = [&magic[..], bytes].concat();
                decompress(Algorithm::Lzfse, &stream, out)
            });
        }
    }
}