Skip to main content

stuffr_cli/bench/
measure.rs

1//! The timing harness for `stuffr bench`: one format at one level, run over
2//! the user's input, compressed and decompressed, with only codec work
3//! inside a timed region, except the temp file's writes when the output is
4//! too large to keep in memory (below).
5//!
6//! Compression's timed regions hold encoder creation, `write_all` of the
7//! input and `Sink::finish` (which consumes the sink, so its teardown is
8//! inside too). Decompression's hold decoder creation and reading the
9//! decoder to its end into a buffer whose bytes are only counted. Building
10//! the destination, opening files, reading streamed input, the temp file's
11//! creation and removal, and dropping the decoder are all outside.
12//!
13//! Each phase is the sum of several timed pieces, each one pair of clock
14//! reads. Compression: encoder creation, then one piece per 64 KiB
15//! `write_all` of the input, then `finish`. Decompression: one piece per
16//! 64 KiB the decoder fills, the decoder's creation in the first, its own
17//! reads of the compressed bytes being part of decoding. In memory and
18//! streamed alike; streamed, the input's reads fall between the pieces.
19//! Otherwise nothing runs between them but the progress report, so the
20//! pieces cost every format the same: one pair of clock reads per 64 KiB.
21//!
22//! Each codec gets the destination its own worst case allows, decided
23//! before any timing: memory whenever that worst case (input + 1/8 +
24//! 1 KiB, or 2 x input + 1 KiB for `compress`, LZW) fits under the memory
25//! left for it, half of `--memory-limit` when the input is held in memory,
26//! all of it when the input is streamed. Only past that does its output go
27//! to one temp file, and then its writes (to the page cache, through the
28//! 64 KiB buffer) fall inside its compression regions, so a row that went
29//! to disk is marked ([`Measured::on_disk`]; the table's `*`, the `output`
30//! field of JSON and CSV). With `--per-file` each file's stream is decided
31//! by its own size. Both destinations have the same shape: a 64 KiB
32//! `BufWriter` over a pre-reserved `Vec`, or over the temp file, so a codec
33//! that writes in small pieces pays the same either way. Decoding reads the
34//! same shape back: the `Vec` as a seekable, sized
35//! source, or the temp file through a 64 KiB `BufReader`, so a decoder that
36//! reads a byte at a time (LZW's) costs a memory copy per byte, not a
37//! system call.
38//!
39//! Each file's length is taken once, when the input is loaded; every later
40//! read stops there, so a file still being written is benched as it was.
41//!
42//! bench ignores STUFFR_THREADS; threads come only from --threads.
43//!
44//! With `--threads` above 1, a multi-threaded encoder's workers keep running
45//! in the untimed gaps between pieces, so its compression time can be
46//! under-reported against a single-threaded one. Streamed, the gaps hold
47//! the input's reads; in memory, only the progress report (a clock read,
48//! and a redraw at most every 100 ms).
49
50use std::fs::{self, File};
51use std::io::{self, BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write};
52use std::path::{Path, PathBuf};
53use std::sync::atomic::{AtomicU32, Ordering};
54use std::sync::{Arc, Mutex};
55use std::time::Instant;
56
57use stuffr::ops::{CompressOpts, resolved_budget};
58use stuffr::source::{GuardedSeek, SeekRead, Source, SourceCaps};
59use stuffr::{Codec, DecodeOpts, EncodeOpts, Error, FormatKind, Governor};
60
61use super::score::{Measured, Outcome};
62use crate::compat::{CleanupGuard, create_armed};
63
64/// The copy buffer, as `ops` uses.
65const CHUNK: usize = 64 * 1024;
66
67/// A monotonic clock in nanoseconds; injected so tests can count its reads.
68pub trait Clock {
69    fn now(&mut self) -> u64;
70}
71
72/// The real clock: nanoseconds since it was made.
73pub struct RealClock(Instant);
74
75impl RealClock {
76    pub fn new() -> Self {
77        Self(Instant::now())
78    }
79}
80
81impl Default for RealClock {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl Clock for RealClock {
88    fn now(&mut self) -> u64 {
89        u64::try_from(self.0.elapsed().as_nanos()).unwrap_or(u64::MAX)
90    }
91}
92
93/// The input, in operand order: held in memory (one buffer per file) or
94/// streamed from the files.
95#[derive(Debug)]
96pub enum Input {
97    Memory(Vec<Vec<u8>>),
98    Files(Vec<Snapshot>),
99}
100
101/// A streamed file and its length when the input was loaded: every read of
102/// it stops at `len`, so bytes appended later are never benched.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Snapshot {
105    pub path: PathBuf,
106    pub len: u64,
107}
108
109impl Snapshot {
110    /// The file, opened and limited to its loaded length.
111    fn open(&self) -> io::Result<io::Take<File>> {
112        Ok(File::open(&self.path)?.take(self.len))
113    }
114
115    /// [`Snapshot::open`] while the input is loaded: a file that cannot be
116    /// opened is the user's to fix, so a usage error naming it.
117    fn open_input(&self) -> stuffr::Result<io::Take<File>> {
118        self.open().map_err(|e| super::unreadable(&self.path, &e))
119    }
120}
121
122/// One stream of the files concatenated, or one stream per file.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum Mode {
125    OneStream,
126    PerFile,
127}
128
129/// The conditions every row runs under.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct Plan {
132    pub mode: Mode,
133    /// Runs per row; the reported times are the medians. 0 counts as 1.
134    pub repeat: u32,
135    /// As `pack --threads`.
136    pub threads: Option<usize>,
137    pub memory_limit: u64,
138}
139
140/// Loads `paths` into memory when their total size is at most half of
141/// `memory_limit`, leaving room for the compressed copy; otherwise the input
142/// is streamed from the files.
143///
144/// Also returns the input's size, measured here once: the bytes read into
145/// memory, or the files' sizes when streamed. It is the ratio's denominator,
146/// and each file's length is snapshotted with it (reads stop there), so a
147/// file still growing while the rows run changes neither.
148///
149/// A file whose size cannot be read, or that cannot be opened, is a usage
150/// error naming it (exit 2); only a failing read is an i/o error.
151pub fn load_input(paths: &[PathBuf], memory_limit: u64) -> stuffr::Result<(Input, u64)> {
152    let mut total = 0u64;
153    let mut snaps = Vec::with_capacity(paths.len());
154    for p in paths {
155        let len = fs::metadata(p).map_err(|e| super::unreadable(p, &e))?.len();
156        total = total.saturating_add(len);
157        snaps.push(Snapshot {
158            path: p.clone(),
159            len,
160        });
161    }
162    if total > memory_limit / 2 {
163        return Ok((Input::Files(snaps), total));
164    }
165    let mut parts = Vec::with_capacity(snaps.len());
166    for s in &snaps {
167        let mut buf = Vec::with_capacity(usize::try_from(s.len).unwrap_or(0));
168        s.open_input()?.read_to_end(&mut buf)?;
169        parts.push(buf);
170    }
171    let read = parts.iter().map(|b| b.len() as u64).sum();
172    Ok((Input::Memory(parts), read))
173}
174
175/// One untimed read of every file, so the first timed run does not pay for
176/// a cold cache. Nothing to do for input already in memory. A file that
177/// cannot be opened is a usage error naming it, as in [`load_input`].
178pub fn warm(input: &Input) -> stuffr::Result<()> {
179    if let Input::Files(files) = input {
180        let mut buf = vec![0u8; CHUNK];
181        for s in files {
182            let mut f = s.open_input()?;
183            while read_some(&mut f, &mut buf)? > 0 {}
184        }
185    }
186    Ok(())
187}
188
189/// Which half of a row's round trip a progress report is about.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum Phase {
192    Compress,
193    Decompress,
194}
195
196/// Compresses and decompresses `input` with `codec` at `level` (`None`: the
197/// encoder's own default) under `plan`. Every error, a rejected level
198/// included, is a failed row; nothing panics.
199///
200/// `progress` is called only between timed pieces, never inside one, with
201/// `(phase, done, total)`; `total` is the input's size. Each repeat opens
202/// with exactly one `(Compress, 0, total)`; after it, `Compress` reports
203/// the input bytes the encoder has taken, rising strictly, and `Decompress`
204/// the bytes the decoder has given back, never falling; both end at
205/// `total` and never pass it. With `Mode::PerFile` the two phases take
206/// turns, file by file, each counting on across the files.
207pub fn measure(
208    codec: &str,
209    level: Option<i32>,
210    input: &Input,
211    plan: &Plan,
212    clock: &mut dyn Clock,
213    progress: &mut dyn FnMut(Phase, u64, u64),
214) -> Outcome {
215    match run(codec, level, input, plan, clock, progress) {
216        Ok(m) => Outcome::Ok(m),
217        Err(e) => Outcome::Failed(e.to_string()),
218    }
219}
220
221/// One file's input as the harness reads it.
222#[derive(Clone, Copy)]
223enum Part<'a> {
224    Memory(&'a [u8]),
225    File(&'a Snapshot),
226}
227
228impl Part<'_> {
229    /// The length the input was loaded at, never re-read from the file.
230    fn len(&self) -> u64 {
231        match self {
232            Part::Memory(b) => b.len() as u64,
233            Part::File(s) => s.len,
234        }
235    }
236}
237
238/// A part as compression takes it: its bytes, or its file opened.
239enum Feed<'a> {
240    Memory(&'a [u8]),
241    File(&'a Snapshot, io::Take<File>),
242}
243
244/// Where one stream's compressed output goes. Decided per codec, from its
245/// own worst case, before any timing (see [`destination`]), and the same
246/// for all of that codec's repeats. A row with any stream on the temp
247/// file is marked as such ([`Measured::on_disk`]).
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249enum Dest {
250    Memory,
251    TempFile,
252}
253
254/// Memory whenever `codec`'s worst-case output for `input_len` bytes (see
255/// [`output_room`]) fits in the memory left for it: half of `memory_limit`
256/// beside input held in memory, all of it when the input is `streamed` (it
257/// holds no copy of the input). The temp file only past that, so the
258/// reservation never exceeds the budget. Each codec gets the destination
259/// its own worst case allows; the row reports which it got.
260fn destination(codec: &str, input_len: u64, memory_limit: u64, streamed: bool) -> Dest {
261    // Small test inputs always fit; this is how the tests reach the temp
262    // file with a memory limit the decoders can still work under.
263    #[cfg(test)]
264    if tests::FORCE_DISK.with(std::cell::Cell::get) {
265        return Dest::TempFile;
266    }
267    let budget = if streamed {
268        memory_limit
269    } else {
270        memory_limit / 2
271    };
272    match output_room(codec, input_len) {
273        Some(w) if w <= budget => Dest::Memory,
274        _ => Dest::TempFile,
275    }
276}
277
278/// The capacity reserved for `codec`'s output in memory, large enough that
279/// the `Vec` never reallocates inside a timed region. LZW (`compress`)
280/// writes no code wider than 16 bits and every code stands for at least one
281/// input byte, so it never writes more than two bytes per input byte (plus
282/// its 3-byte header and the padding at each code-width step); every other
283/// codec stays within 1/8 + 1 KiB, which
284/// `the_reserved_room_holds_incompressible_output` measures. Reserved pages
285/// a codec never writes are never touched. `None`: past `u64`, so it fits
286/// nowhere.
287fn output_room(codec: &str, input_len: u64) -> Option<u64> {
288    match codec {
289        "compress" => input_len.checked_mul(2),
290        _ => input_len.checked_add(input_len / 8),
291    }
292    .and_then(|n| n.checked_add(1024))
293}
294
295fn run(
296    name: &str,
297    level: Option<i32>,
298    input: &Input,
299    plan: &Plan,
300    clock: &mut dyn Clock,
301    report: &mut dyn FnMut(Phase, u64, u64),
302) -> stuffr::Result<Measured> {
303    let reg = stuffr::registry();
304    let id = reg
305        .matrix()
306        .into_iter()
307        .find(|r| r.kind == FormatKind::Codec && r.id.as_str() == name)
308        .map(|r| r.id)
309        .ok_or_else(|| Error::Usage(format!("`{name}` is not a codec in this build")))?;
310    let codec = reg.require_encoder(id)?;
311    reg.require_decoder(id)?;
312
313    let encode = EncodeOpts {
314        level,
315        governor: governor_for(plan),
316        ..Default::default()
317    };
318    codec.check_encode_opts(&encode)?;
319    let decode = DecodeOpts {
320        memory_limit: Some(plan.memory_limit),
321        ..Default::default()
322    };
323
324    let parts: Vec<Part<'_>> = match input {
325        Input::Memory(bufs) => bufs.iter().map(|b| Part::Memory(b)).collect(),
326        Input::Files(files) => files.iter().map(Part::File).collect(),
327    };
328    let groups: Vec<&[Part<'_>]> = match plan.mode {
329        Mode::OneStream => vec![&parts[..]],
330        Mode::PerFile => parts.chunks(1).collect(),
331    };
332    let group_len = |g: &[Part<'_>]| g.iter().map(Part::len).sum::<u64>();
333    let streamed = matches!(input, Input::Files(_));
334    let dest = |g: &[Part<'_>]| destination(name, group_len(g), plan.memory_limit, streamed);
335    let temp = if groups.iter().any(|g| dest(g) == Dest::TempFile) {
336        Some(TempOut::create()?.0)
337    } else {
338        None
339    };
340
341    let mut buf = vec![0u8; CHUNK];
342    let mut bytes_out = None;
343    let mut on_disk = false;
344    let mut compress = Vec::new();
345    let mut decompress = Vec::new();
346    let mut progress = Progress::new(report, parts.iter().map(Part::len).sum());
347    for _ in 0..plan.repeat.max(1) {
348        progress.start();
349        let (mut out, mut c_ns, mut d_ns) = (0u64, 0u64, 0u64);
350        for group in &groups {
351            let expected = group_len(group);
352            let job = Job {
353                name: id.as_str(),
354                codec: codec.as_ref(),
355                dest: dest(group),
356                encode: &encode,
357                decode: &decode,
358                temp: temp.as_ref(),
359                buf: &mut buf,
360            };
361            let row = job.run(group, expected, clock, &mut progress)?;
362            out += row.bytes_out;
363            c_ns += row.compress_ns;
364            d_ns += row.decompress_ns;
365            on_disk |= row.on_disk;
366        }
367        bytes_out.get_or_insert(out);
368        compress.push(c_ns);
369        decompress.push(d_ns);
370    }
371    Ok(Measured {
372        bytes_out: bytes_out.unwrap_or(0),
373        compress_ns: median(compress),
374        decompress_ns: median(decompress),
375        on_disk,
376    })
377}
378
379/// The encode governor for `plan`: `pack --threads`'s mapping, except that
380/// no `--threads` means single-threaded whatever `STUFFR_THREADS` says
381/// (`resolved_budget` would read it). With a CLI value the variable is
382/// already ignored: `resolve_workers` takes the CLI value first.
383pub fn governor_for(plan: &Plan) -> Option<Arc<Governor>> {
384    let t = plan.threads?;
385    resolved_budget(&CompressOpts {
386        threads: Some(t),
387        memory_limit: Some(plan.memory_limit),
388        ..Default::default()
389    })
390}
391
392/// The middle value; the lower of the two middles for an even count.
393fn median(mut v: Vec<u64>) -> u64 {
394    v.sort_unstable();
395    v.get(v.len().saturating_sub(1) / 2).copied().unwrap_or(0)
396}
397
398/// The progress reports of one row, made between timed pieces only (see
399/// [`measure`] for what they promise).
400struct Progress<'a> {
401    report: &'a mut dyn FnMut(Phase, u64, u64),
402    total: u64,
403    fed: u64,
404    decoded: u64,
405}
406
407impl<'a> Progress<'a> {
408    fn new(report: &'a mut dyn FnMut(Phase, u64, u64), total: u64) -> Self {
409        Self {
410            report,
411            total,
412            fed: 0,
413            decoded: 0,
414        }
415    }
416
417    /// A repeat begins: its one `(Compress, 0, total)`.
418    fn start(&mut self) {
419        self.fed = 0;
420        self.decoded = 0;
421        (self.report)(Phase::Compress, 0, self.total);
422    }
423
424    /// The encoder took `n` more input bytes.
425    fn fed(&mut self, n: usize) {
426        let fed = self.fed.saturating_add(n as u64).min(self.total);
427        // Never a second `(Compress, 0, _)`: that opens a repeat.
428        if fed > self.fed {
429            self.fed = fed;
430            (self.report)(Phase::Compress, fed, self.total);
431        }
432    }
433
434    /// The decoder gave back `n` more bytes.
435    fn decoded(&mut self, n: usize) {
436        self.decoded = self.decoded.saturating_add(n as u64).min(self.total);
437        (self.report)(Phase::Decompress, self.decoded, self.total);
438    }
439}
440
441/// One timed piece: `f` between two clock reads, and nothing else.
442fn timed<T>(clock: &mut dyn Clock, f: impl FnOnce() -> T) -> (T, u64) {
443    let t0 = clock.now();
444    let r = f();
445    let t1 = clock.now();
446    (r, t1.saturating_sub(t0))
447}
448
449/// Everything one stream's round trip needs.
450struct Job<'a> {
451    name: &'a str,
452    codec: &'a dyn Codec,
453    dest: Dest,
454    encode: &'a EncodeOpts,
455    decode: &'a DecodeOpts,
456    temp: Option<&'a TempOut>,
457    buf: &'a mut [u8],
458}
459
460impl Job<'_> {
461    /// Compresses `group` as one stream, then decompresses it, checking the
462    /// round trip gives back `expected` bytes.
463    fn run(
464        mut self,
465        group: &[Part<'_>],
466        expected: u64,
467        clock: &mut dyn Clock,
468        progress: &mut Progress<'_>,
469    ) -> stuffr::Result<Measured> {
470        let on_disk = matches!((self.dest, self.temp), (Dest::TempFile, Some(_)));
471        let (bytes_out, compress_ns, src) = match (self.dest, self.temp) {
472            (Dest::Memory, _) | (Dest::TempFile, None) => {
473                // Room for incompressible output, so the outer Vec does not
474                // reallocate inside the region. (`TempFile` always comes
475                // with a temp file; `run` creates one whenever any group
476                // needs it.)
477                let room = output_room(self.name, expected).unwrap_or(0);
478                let shared = SharedVec::with_capacity(usize::try_from(room).unwrap_or(0));
479                let dst = BufWriter::with_capacity(CHUNK, shared.clone());
480                let ns = self.compress(group, Box::new(dst), clock, progress)?;
481                let bytes = shared.take();
482                let len = bytes.len() as u64;
483                (len, ns, Box::new(MemSource::new(bytes)) as Box<dyn Source>)
484            }
485            (Dest::TempFile, Some(temp)) => {
486                let file = File::options()
487                    .write(true)
488                    .truncate(true)
489                    .open(temp.path())?;
490                let dst = BufWriter::with_capacity(CHUNK, file);
491                let ns = self.compress(group, Box::new(dst), clock, progress)?;
492                let file = File::open(temp.path())?;
493                let len = file.metadata()?.len();
494                let src = temp_source(GuardedSeek::new(counted(file)), len);
495                (len, ns, Box::new(src) as Box<dyn Source>)
496            }
497        };
498        let (decoded, decompress_ns) =
499            decode(self.codec, self.decode, src, self.buf, clock, progress)?;
500        if decoded != expected {
501            return Err(Error::Corrupt(format!(
502                "the round trip gave back {decoded} bytes of {expected}"
503            )));
504        }
505        Ok(Measured {
506            bytes_out,
507            compress_ns,
508            decompress_ns,
509            on_disk,
510        })
511    }
512
513    /// The compression pieces' total: encoder creation, one `write_all`
514    /// per 64 KiB of input, `finish`. Streamed, each chunk is read between
515    /// two pieces.
516    fn compress(
517        &mut self,
518        group: &[Part<'_>],
519        dst: Box<dyn Write + Send>,
520        clock: &mut dyn Clock,
521        progress: &mut Progress<'_>,
522    ) -> stuffr::Result<u64> {
523        // Files are opened before any timing.
524        let mut feeds = Vec::with_capacity(group.len());
525        for p in group {
526            feeds.push(match p {
527                Part::Memory(b) => Feed::Memory(b),
528                Part::File(snap) => Feed::File(snap, snap.open()?),
529            });
530        }
531        let (sink, mut ns) = timed(clock, || self.codec.encoder(dst, self.encode));
532        let mut sink = sink?;
533        for feed in &mut feeds {
534            match feed {
535                Feed::Memory(b) => {
536                    for chunk in b.chunks(CHUNK) {
537                        let (r, t) = timed(clock, || sink.write_all(chunk));
538                        r?;
539                        ns += t;
540                        progress.fed(chunk.len());
541                    }
542                }
543                Feed::File(snap, f) => {
544                    let mut read = 0u64;
545                    loop {
546                        let n = read_some(f, self.buf)?;
547                        if n == 0 {
548                            if read < snap.len {
549                                return Err(Error::Io(io::Error::new(
550                                    io::ErrorKind::UnexpectedEof,
551                                    format!(
552                                        "{} shrank to {read} bytes from {} while bench ran",
553                                        snap.path.display(),
554                                        snap.len
555                                    ),
556                                )));
557                            }
558                            break;
559                        }
560                        read += n as u64;
561                        let chunk = &self.buf[..n];
562                        let (r, t) = timed(clock, || sink.write_all(chunk));
563                        r?;
564                        ns += t;
565                        progress.fed(n);
566                    }
567                }
568            }
569        }
570        let (r, t) = timed(clock, || sink.finish());
571        r?;
572        Ok(ns + t)
573    }
574}
575
576/// Decompression: one piece per 64 KiB the decoder fills (`buf` is
577/// [`CHUNK`] long), the decoder made in the first, until a fill comes back
578/// short at the end; the bytes are only counted. Returns the count and the
579/// pieces' total. The decoder is dropped outside them.
580fn decode(
581    codec: &dyn Codec,
582    opts: &DecodeOpts,
583    src: Box<dyn Source>,
584    buf: &mut [u8],
585    clock: &mut dyn Clock,
586    progress: &mut Progress<'_>,
587) -> stuffr::Result<(u64, u64)> {
588    let (first, mut ns) = timed(clock, || {
589        let mut decoder = codec.decoder(src, opts)?;
590        let n = fill(&mut decoder, buf).map_err(Error::from_decode_io)?;
591        Ok::<_, Error>((decoder, n))
592    });
593    let (mut decoder, mut n) = first?;
594    let mut total = 0u64;
595    loop {
596        total += n as u64;
597        progress.decoded(n);
598        if n < buf.len() {
599            break;
600        }
601        let (r, t) = timed(clock, || fill(&mut decoder, buf));
602        ns += t;
603        n = r.map_err(Error::from_decode_io)?;
604    }
605    drop(decoder);
606    Ok((total, ns))
607}
608
609/// Reads into `buf` until it is full or the reader ends, retrying
610/// `Interrupted`. Short only at the end.
611fn fill(r: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
612    let mut filled = 0;
613    while filled < buf.len() {
614        match r.read(&mut buf[filled..]) {
615            Ok(0) => break,
616            Ok(n) => filled += n,
617            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
618            Err(e) => return Err(e),
619        }
620    }
621    Ok(filled)
622}
623
624/// `read`, retried on `Interrupted`.
625fn read_some(r: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
626    loop {
627        match r.read(buf) {
628            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
629            other => return other,
630        }
631    }
632}
633
634/// The in-memory destination: the encoder owns one handle, the harness
635/// keeps the other to take the bytes back after `finish`.
636#[derive(Clone)]
637struct SharedVec(Arc<Mutex<Vec<u8>>>);
638
639impl SharedVec {
640    fn with_capacity(n: usize) -> Self {
641        Self(Arc::new(Mutex::new(Vec::with_capacity(n))))
642    }
643
644    #[cfg(test)]
645    fn capacity(&self) -> usize {
646        self.0.lock().unwrap_or_else(|e| e.into_inner()).capacity()
647    }
648
649    fn take(&self) -> Vec<u8> {
650        std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()))
651    }
652}
653
654impl Write for SharedVec {
655    fn write(&mut self, b: &[u8]) -> io::Result<usize> {
656        self.0
657            .lock()
658            .unwrap_or_else(|e| e.into_inner())
659            .extend_from_slice(b);
660        Ok(b.len())
661    }
662
663    fn flush(&mut self) -> io::Result<()> {
664        Ok(())
665    }
666}
667
668/// Compressed bytes in memory, as seekable and sized as the [`BufSource`]
669/// over the temp file, so a decoder sees the same capabilities either way.
670struct MemSource {
671    cursor: Cursor<Vec<u8>>,
672    len: u64,
673}
674
675impl MemSource {
676    fn new(bytes: Vec<u8>) -> Self {
677        let len = bytes.len() as u64;
678        Self {
679            cursor: Cursor::new(bytes),
680            len,
681        }
682    }
683}
684
685impl Read for MemSource {
686    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
687        self.cursor.read(buf)
688    }
689}
690
691impl Seek for MemSource {
692    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
693        self.cursor.seek(pos)
694    }
695}
696
697impl Source for MemSource {
698    fn caps(&self) -> SourceCaps {
699        SourceCaps {
700            seekable: true,
701            len: Some(self.len),
702        }
703    }
704
705    fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
706        Some(self)
707    }
708}
709
710/// The temp file's compressed bytes as the decoder reads them: through a
711/// 64 KiB buffer, so a decoder reading a byte at a time pays a memory copy
712/// per byte, as it does from [`MemSource`], not a system call. Seekable and
713/// sized like `MemSource`.
714fn temp_source<R: Read + Seek + Send>(inner: R, len: u64) -> BufSource<R> {
715    BufSource {
716        inner: BufReader::with_capacity(CHUNK, inner),
717        len,
718    }
719}
720
721struct BufSource<R> {
722    inner: BufReader<R>,
723    len: u64,
724}
725
726impl<R: Read> Read for BufSource<R> {
727    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
728        self.inner.read(buf)
729    }
730}
731
732impl<R: Seek> Seek for BufSource<R> {
733    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
734        self.inner.seek(pos)
735    }
736}
737
738impl<R: Read + Seek + Send> Source for BufSource<R> {
739    fn caps(&self) -> SourceCaps {
740        SourceCaps {
741            seekable: true,
742            len: Some(self.len),
743        }
744    }
745
746    fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
747        Some(self)
748    }
749}
750
751/// The temp file as `temp_source` reads it. Production: the file itself.
752#[cfg(not(test))]
753fn counted(file: File) -> File {
754    file
755}
756
757/// Under test, a file whose reads are counted per thread, so a test sees
758/// how many reach it through the path `measure` takes.
759#[cfg(test)]
760fn counted(file: File) -> tests::CountedFile {
761    tests::CountedFile(file)
762}
763
764/// The next temp file's `<n>`; also how the tests see whether a run made one.
765static TEMP_SEQ: AtomicU32 = AtomicU32::new(0);
766
767/// The streamed run's compressed output, `stuffr-bench-<pid>-<n>` in the
768/// temp directory: armed for removal on SIGINT, SIGTERM and SIGHUP while it
769/// lives, removed when it drops (a panic included).
770struct TempOut {
771    path: PathBuf,
772    /// Dropped after `drop` has removed the file, so there is no moment the
773    /// file exists unarmed.
774    _armed: CleanupGuard,
775}
776
777impl TempOut {
778    fn create() -> io::Result<(Self, File)> {
779        let dir = std::env::temp_dir();
780        let mut tries = 0;
781        loop {
782            let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
783            let path = dir.join(format!("stuffr-bench-{}-{n}", std::process::id()));
784            match create_armed(&path) {
785                Ok((file, armed)) => {
786                    return Ok((
787                        Self {
788                            path,
789                            _armed: armed,
790                        },
791                        file,
792                    ));
793                }
794                Err(e) if e.kind() == io::ErrorKind::AlreadyExists && tries < 1000 => tries += 1,
795                Err(e) => return Err(e),
796            }
797        }
798    }
799
800    fn path(&self) -> &Path {
801        &self.path
802    }
803}
804
805impl Drop for TempOut {
806    fn drop(&mut self) {
807        let _ = fs::remove_file(&self.path);
808    }
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814    use std::fs;
815    use std::path::PathBuf;
816    use std::sync::atomic::{AtomicU32, Ordering};
817
818    /// 0, 10, 20, …: every region it times lasts exactly 10.
819    struct FakeClock(u64);
820
821    impl Clock for FakeClock {
822        fn now(&mut self) -> u64 {
823            let t = self.0;
824            self.0 += 10;
825            t
826        }
827    }
828
829    /// Times region `i` (reads `2i` and `2i + 1`) as `durations[i]`.
830    struct ScriptClock {
831        durations: Vec<u64>,
832        reads: usize,
833        t: u64,
834    }
835
836    impl Clock for ScriptClock {
837        fn now(&mut self) -> u64 {
838            if self.reads % 2 == 1 {
839                self.t += self.durations[self.reads / 2];
840            } else {
841                self.t += 1_000;
842            }
843            self.reads += 1;
844            self.t
845        }
846    }
847
848    /// A scratch directory `stuffr-benchtest-<pid>-<n>`, removed on drop.
849    struct Scratch(PathBuf);
850
851    impl Scratch {
852        fn new() -> Self {
853            static N: AtomicU32 = AtomicU32::new(0);
854            let n = N.fetch_add(1, Ordering::Relaxed);
855            let dir =
856                std::env::temp_dir().join(format!("stuffr-benchtest-{}-{n}", std::process::id()));
857            fs::create_dir_all(&dir).unwrap();
858            Scratch(dir)
859        }
860
861        fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
862            let p = self.0.join(name);
863            fs::write(&p, bytes).unwrap();
864            p
865        }
866    }
867
868    impl Drop for Scratch {
869        fn drop(&mut self) {
870            let _ = fs::remove_dir_all(&self.0);
871        }
872    }
873
874    /// Serialises the tests that arm the process-wide signal cleanup.
875    fn armed_lock() -> std::sync::MutexGuard<'static, ()> {
876        crate::compat::ARM_TEST_LOCK
877            .lock()
878            .unwrap_or_else(|e| e.into_inner())
879    }
880
881    fn text(len: usize, seed: u8) -> Vec<u8> {
882        b"the quick brown fox jumps over the lazy dog, "
883            .iter()
884            .cycle()
885            .enumerate()
886            .map(|(i, &b)| b.wrapping_add(seed).wrapping_add((i / 997) as u8))
887            .take(len)
888            .collect()
889    }
890
891    fn plan(mode: Mode, repeat: u32) -> Plan {
892        Plan {
893            mode,
894            repeat,
895            threads: None,
896            memory_limit: 1 << 30,
897        }
898    }
899
900    thread_local! {
901        /// Set by `on_disk`: every output goes to the temp file.
902        pub(super) static FORCE_DISK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
903    }
904
905    /// Runs `f` with every compressed output sent to the temp file.
906    fn on_disk<T>(f: impl FnOnce() -> T) -> T {
907        FORCE_DISK.with(|d| d.set(true));
908        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
909        FORCE_DISK.with(|d| d.set(false));
910        r.unwrap_or_else(|e| std::panic::resume_unwind(e))
911    }
912
913    thread_local! {
914        /// Reads that reached a temp file on this thread (see `counted`).
915        static FILE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
916    }
917
918    /// The temp file under test: counts each read that reaches it.
919    pub(super) struct CountedFile(pub(super) File);
920
921    impl Read for CountedFile {
922        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
923            FILE_READS.with(|r| r.set(r.get() + 1));
924            self.0.read(buf)
925        }
926    }
927
928    impl Seek for CountedFile {
929        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
930            self.0.seek(pos)
931        }
932    }
933
934    /// The temp files created while `f` ran. Hold `armed_lock`: every test
935    /// that can create one does.
936    fn temps_made(f: impl FnOnce()) -> u32 {
937        let before = TEMP_SEQ.load(Ordering::Relaxed);
938        f();
939        TEMP_SEQ.load(Ordering::Relaxed) - before
940    }
941
942    /// Deterministic noise no codec can shrink.
943    fn noise(len: usize) -> Vec<u8> {
944        let mut x = 0x9e37_79b9_7f4a_7c15u64;
945        (0..len)
946            .map(|_| {
947                x ^= x << 13;
948                x ^= x >> 7;
949                x ^= x << 17;
950                (x >> 24) as u8
951            })
952            .collect()
953    }
954
955    fn ok(o: Outcome) -> Measured {
956        match o {
957            Outcome::Ok(m) => m,
958            Outcome::Failed(e) => panic!("failed: {e}"),
959        }
960    }
961
962    fn run(codec: &str, input: &Input, plan: &Plan) -> Measured {
963        ok(measure(
964            codec,
965            None,
966            input,
967            plan,
968            &mut FakeClock(0),
969            &mut |_, _, _| {},
970        ))
971    }
972
973    fn bench_temps() -> Vec<String> {
974        let prefix = format!("stuffr-bench-{}-", std::process::id());
975        fs::read_dir(std::env::temp_dir())
976            .unwrap()
977            .filter_map(|e| e.ok()?.file_name().into_string().ok())
978            .filter(|n| n.starts_with(&prefix))
979            .collect()
980    }
981
982    #[test]
983    fn one_stream_compresses_the_concatenation() {
984        let (a, b) = (text(20_000, 0), text(30_000, 7));
985        let both = [a.clone(), b.clone()].concat();
986        let p = plan(Mode::OneStream, 1);
987        for codec in ["gzip", "zstd", "bzip2"] {
988            let parts = run(codec, &Input::Memory(vec![a.clone(), b.clone()]), &p);
989            let whole = run(codec, &Input::Memory(vec![both.clone()]), &p);
990            assert_eq!(parts.bytes_out, whole.bytes_out, "{codec}");
991        }
992    }
993
994    #[test]
995    fn per_file_sums_each_file() {
996        let (a, b) = (text(20_000, 0), text(30_000, 7));
997        let p = plan(Mode::PerFile, 1);
998        let both = run("gzip", &Input::Memory(vec![a.clone(), b.clone()]), &p);
999        let one = run("gzip", &Input::Memory(vec![a]), &p);
1000        let two = run("gzip", &Input::Memory(vec![b]), &p);
1001        assert_eq!(both.bytes_out, one.bytes_out + two.bytes_out);
1002        let stream = run(
1003            "gzip",
1004            &Input::Memory(vec![text(20_000, 0), text(30_000, 7)]),
1005            &plan(Mode::OneStream, 1),
1006        );
1007        assert_ne!(
1008            both.bytes_out, stream.bytes_out,
1009            "per-file is not one stream"
1010        );
1011        // Per file: encoder creation, one write (each file is under 64 KiB)
1012        // and `finish` to compress, one fill to decompress; summed.
1013        assert_eq!(both.compress_ns, 2 * 30);
1014        assert_eq!(both.decompress_ns, 2 * 10);
1015    }
1016
1017    /// Streamed: compression is encoder creation, one region per input
1018    /// chunk's `write_all` (each 64 KiB read falls between them) and
1019    /// `finish`; decompression one region per 64 KiB filled, the decoder
1020    /// made in the first.
1021    #[test]
1022    fn a_streamed_run_times_each_write_and_not_the_reads() {
1023        let _lock = armed_lock();
1024        let s = Scratch::new();
1025        // Two chunks: 64 KiB, then 36 KiB.
1026        let paths = vec![s.file("a", &text(100 * 1024, 6))];
1027        let files = load_input(&paths, 0).unwrap().0;
1028        let mut clock = FakeClock(0);
1029        let m = ok(measure(
1030            "gzip",
1031            None,
1032            &files,
1033            &plan(Mode::OneStream, 1),
1034            &mut clock,
1035            &mut |_, _, _| {},
1036        ));
1037        let regions = 1 + 2 + 1;
1038        // 64 KiB, then 36 KiB: the short fill is the end.
1039        let fills = 2;
1040        assert_eq!(m.compress_ns, 10 * regions);
1041        assert_eq!(m.decompress_ns, 10 * fills);
1042        assert_eq!(clock.0, 10 * 2 * (regions + fills), "no other clock reads");
1043    }
1044
1045    #[test]
1046    fn no_threads_means_no_governor() {
1047        // Pinned structurally rather than by exporting STUFFR_THREADS: the
1048        // lib tests share one environment (edition 2024 `set_var` is
1049        // unsafe for exactly that reason), and `governor_for` returns
1050        // before `resolved_budget`, the only reader of the variable, is
1051        // called.
1052        assert!(governor_for(&plan(Mode::OneStream, 1)).is_none());
1053        let two = Plan {
1054            threads: Some(2),
1055            ..plan(Mode::OneStream, 1)
1056        };
1057        assert!(governor_for(&two).is_some());
1058    }
1059
1060    /// In memory, as streamed: encoder creation, one piece per 64 KiB
1061    /// `write_all` and `finish`; then one piece per 64 KiB the decoder
1062    /// fills, the decoder made in the first. Each piece is exactly two
1063    /// clock reads, and there are no others.
1064    #[test]
1065    fn the_fake_clock_still_times_only_codec_work() {
1066        // Three chunks: 64, 64 and 32 KiB.
1067        let input = Input::Memory(vec![text(160 * 1024, 3)]);
1068        let mut clock = FakeClock(0);
1069        let m = ok(measure(
1070            "gzip",
1071            None,
1072            &input,
1073            &plan(Mode::OneStream, 1),
1074            &mut clock,
1075            &mut |_, _, _| {},
1076        ));
1077        let compress_pieces = 1 + 3 + 1;
1078        // 64, 64, then 32 KiB: the short fill is the end.
1079        let decompress_pieces = 3;
1080        assert_eq!(m.compress_ns, 10 * compress_pieces);
1081        assert_eq!(m.decompress_ns, 10 * decompress_pieces);
1082        assert_eq!(
1083            clock.0,
1084            10 * 2 * (compress_pieces + decompress_pieces),
1085            "two reads per piece, nothing else"
1086        );
1087    }
1088
1089    /// A clock whose reads a progress callback can see: the callback runs
1090    /// inside a timed region exactly when the count is odd.
1091    struct SeenClock(std::rc::Rc<std::cell::Cell<u64>>);
1092
1093    impl Clock for SeenClock {
1094        fn now(&mut self) -> u64 {
1095            let n = self.0.get();
1096            self.0.set(n + 1);
1097            10 * n
1098        }
1099    }
1100
1101    /// Splits `seen` into repeats at each `(Compress, 0, _)`, the one report
1102    /// that opens a repeat, and checks each: both phases rise to `total`,
1103    /// compression strictly after the opening report.
1104    fn check_reports(seen: &[(Phase, u64, u64)], total: u64, repeats: usize, what: &str) {
1105        let opens: Vec<usize> = (0..seen.len())
1106            .filter(|&i| matches!(seen[i], (Phase::Compress, 0, _)))
1107            .collect();
1108        assert_eq!(opens.len(), repeats, "{what}: {seen:?}");
1109        assert_eq!(opens[0], 0, "{what}: the first report opens a repeat");
1110        for (i, &start) in opens.iter().enumerate() {
1111            let end = opens.get(i + 1).copied().unwrap_or(seen.len());
1112            let one = &seen[start..end];
1113            assert!(one.iter().all(|r| r.2 == total), "{what}: {one:?}");
1114            let fed: Vec<u64> = one
1115                .iter()
1116                .filter(|r| r.0 == Phase::Compress)
1117                .map(|r| r.1)
1118                .collect();
1119            let decoded: Vec<u64> = one
1120                .iter()
1121                .filter(|r| r.0 == Phase::Decompress)
1122                .map(|r| r.1)
1123                .collect();
1124            assert!(fed.windows(2).all(|w| w[0] < w[1]), "{what}: {fed:?}");
1125            assert!(
1126                decoded.windows(2).all(|w| w[0] <= w[1]),
1127                "{what}: {decoded:?}"
1128            );
1129            assert_eq!(fed.last(), Some(&total), "{what}: compression");
1130            assert_eq!(decoded.last(), Some(&total), "{what}: decompression");
1131            assert!(fed.len() > 2 && decoded.len() > 1, "{what}: {one:?}");
1132        }
1133    }
1134
1135    #[test]
1136    fn progress_is_reported_between_pieces_only() {
1137        use std::{cell::Cell, rc::Rc};
1138        let _lock = armed_lock();
1139        let s = Scratch::new();
1140        let data = text(160 * 1024, 5);
1141        let paths = vec![
1142            s.file("a", &data[..100 * 1024]),
1143            s.file("b", &data[100 * 1024..]),
1144        ];
1145        let memory = load_input(&paths, 1 << 30).unwrap().0;
1146        let files = load_input(&paths, 0).unwrap().0;
1147        for (input, disk, name) in [
1148            (&memory, false, "memory"),
1149            (&memory, true, "memory, temp file"),
1150            (&files, false, "streamed"),
1151            (&files, true, "streamed, temp file"),
1152        ] {
1153            for mode in [Mode::OneStream, Mode::PerFile] {
1154                let reads = Rc::new(Cell::new(0));
1155                let mut clock = SeenClock(reads.clone());
1156                let mut seen = Vec::new();
1157                let mut report = |phase, done, total| {
1158                    assert_eq!(reads.get() % 2, 0, "a report inside a timed region");
1159                    seen.push((phase, done, total));
1160                };
1161                let p = plan(mode, 2);
1162                let mut go = || measure("gzip", None, input, &p, &mut clock, &mut report);
1163                let o = if disk { on_disk(go) } else { go() };
1164                ok(o);
1165                check_reports(&seen, data.len() as u64, 2, &format!("{name} {mode:?}"));
1166            }
1167        }
1168    }
1169
1170    #[test]
1171    fn repeat_reports_the_median() {
1172        let input = Input::Memory(vec![text(4096, 1)]);
1173        // Per run: encoder creation, one write, `finish`, then one fill.
1174        // Compression 30, 10, 20; decompression 7, 5, 9.
1175        let mut clock = ScriptClock {
1176            durations: vec![10, 10, 10, 7, 2, 3, 5, 5, 5, 5, 10, 9],
1177            reads: 0,
1178            t: 0,
1179        };
1180        let m = ok(measure(
1181            "gzip",
1182            None,
1183            &input,
1184            &plan(Mode::OneStream, 3),
1185            &mut clock,
1186            &mut |_, _, _| {},
1187        ));
1188        assert_eq!(m.compress_ns, 20);
1189        assert_eq!(m.decompress_ns, 7);
1190        assert_eq!(clock.reads, 24, "two reads per piece, nothing else");
1191    }
1192
1193    #[test]
1194    fn an_even_repeat_reports_the_lower_median() {
1195        let input = Input::Memory(vec![text(4096, 1)]);
1196        let mut clock = ScriptClock {
1197            // Compression 40, 10, 30, 20; decompression 1, 2, 3, 4.
1198            durations: vec![20, 10, 10, 1, 4, 3, 3, 2, 10, 10, 10, 3, 5, 5, 10, 4],
1199            reads: 0,
1200            t: 0,
1201        };
1202        let m = ok(measure(
1203            "gzip",
1204            None,
1205            &input,
1206            &plan(Mode::OneStream, 4),
1207            &mut clock,
1208            &mut |_, _, _| {},
1209        ));
1210        assert_eq!(m.compress_ns, 20);
1211        assert_eq!(m.decompress_ns, 2);
1212    }
1213
1214    #[test]
1215    fn a_rejected_level_is_a_failed_row() {
1216        let input = Input::Memory(vec![text(1024, 0)]);
1217        let mut clock = FakeClock(0);
1218        match measure(
1219            "gzip",
1220            Some(99),
1221            &input,
1222            &plan(Mode::OneStream, 1),
1223            &mut clock,
1224            &mut |_, _, _| {},
1225        ) {
1226            Outcome::Failed(msg) => assert!(msg.contains("99"), "{msg}"),
1227            Outcome::Ok(m) => panic!("level 99 accepted: {m:?}"),
1228        }
1229        assert_eq!(clock.0, 0, "nothing was timed");
1230    }
1231
1232    #[test]
1233    fn an_unknown_format_is_a_failed_row() {
1234        let input = Input::Memory(vec![text(1024, 0)]);
1235        let o = measure(
1236            "nope",
1237            None,
1238            &input,
1239            &plan(Mode::OneStream, 1),
1240            &mut FakeClock(0),
1241            &mut |_, _, _| {},
1242        );
1243        assert!(matches!(o, Outcome::Failed(_)), "{o:?}");
1244    }
1245
1246    #[test]
1247    fn streamed_input_matches_memory_input() {
1248        let _lock = armed_lock();
1249        let s = Scratch::new();
1250        let (a, b) = (text(32 * 1024, 2), text(32 * 1024, 9));
1251        let paths = vec![s.file("a", &a), s.file("b", &b)];
1252        let files = load_input(&paths, 0).unwrap().0;
1253        assert!(matches!(files, Input::Files(_)));
1254        warm(&files).unwrap();
1255        let memory = load_input(&paths, 1 << 30).unwrap().0;
1256        assert!(matches!(memory, Input::Memory(_)));
1257        for mode in [Mode::OneStream, Mode::PerFile] {
1258            let p = plan(mode, 1);
1259            for codec in ["gzip", "xz", "lz4"] {
1260                let want = run(codec, &memory, &p).bytes_out;
1261                assert_eq!(run(codec, &files, &p).bytes_out, want, "{codec}");
1262                let disk = on_disk(|| run(codec, &files, &p)).bytes_out;
1263                assert_eq!(disk, want, "{codec} via the temp file");
1264            }
1265        }
1266    }
1267
1268    #[test]
1269    fn the_output_temp_file_is_removed() {
1270        let _lock = armed_lock();
1271        let s = Scratch::new();
1272        let paths = vec![s.file("a", &text(16 * 1024, 4))];
1273        let files = load_input(&paths, 0).unwrap().0;
1274        let made = temps_made(|| {
1275            on_disk(|| run("gzip", &files, &plan(Mode::OneStream, 2)));
1276        });
1277        assert_eq!(made, 1);
1278        assert_eq!(bench_temps(), Vec::<String>::new());
1279    }
1280
1281    #[test]
1282    fn the_temp_guard_removes_on_panic() {
1283        let _lock = armed_lock();
1284        let seen = std::sync::Mutex::new(None::<PathBuf>);
1285        let r = std::panic::catch_unwind(|| {
1286            let (guard, _file) = TempOut::create().unwrap();
1287            *seen.lock().unwrap() = Some(guard.path().to_path_buf());
1288            assert!(guard.path().exists());
1289            panic!("mid-run");
1290        });
1291        assert!(r.is_err());
1292        let path = seen.into_inner().unwrap().expect("the guard was created");
1293        assert!(!path.exists(), "{} survived the panic", path.display());
1294        #[cfg(unix)]
1295        assert!(
1296            crate::compat::armed_path().is_none(),
1297            "still armed after the panic"
1298        );
1299    }
1300
1301    #[cfg(unix)]
1302    #[test]
1303    fn the_temp_file_is_armed_for_signals() {
1304        let _lock = armed_lock();
1305        let (guard, _file) = TempOut::create().unwrap();
1306        let path = guard.path().to_path_buf();
1307        let name = path.file_name().unwrap().to_str().unwrap().to_owned();
1308        assert!(
1309            name.starts_with(&format!("stuffr-bench-{}-", std::process::id())),
1310            "{name}"
1311        );
1312        assert_eq!(crate::compat::armed_path().as_deref(), Some(path.as_path()));
1313        drop(guard);
1314        assert!(
1315            crate::compat::armed_path().is_none(),
1316            "armed after the drop"
1317        );
1318        assert!(!path.exists());
1319    }
1320
1321    #[test]
1322    fn empty_input_measures_without_error() {
1323        for mode in [Mode::OneStream, Mode::PerFile] {
1324            for codec in crate::bench::levels::benchable_codecs() {
1325                let m = run(codec, &Input::Memory(vec![Vec::new()]), &plan(mode, 1));
1326                assert!(m.bytes_out < 1024, "{codec}: {m:?}");
1327            }
1328        }
1329    }
1330
1331    #[test]
1332    fn every_benchable_codec_round_trips_in_both_modes() {
1333        let _lock = armed_lock();
1334        let s = Scratch::new();
1335        let paths = vec![s.file("a", &text(8 * 1024, 5)), s.file("b", &text(4096, 8))];
1336        let files = load_input(&paths, 0).unwrap().0;
1337        let memory = load_input(&paths, 1 << 30).unwrap().0;
1338        for mode in [Mode::OneStream, Mode::PerFile] {
1339            for codec in crate::bench::levels::benchable_codecs() {
1340                for input in [&files, &memory] {
1341                    run(codec, input, &plan(mode, 1));
1342                    on_disk(|| run(codec, input, &plan(mode, 1)));
1343                }
1344            }
1345        }
1346    }
1347
1348    /// Counts the reads that reach the wrapped reader.
1349    struct CountReads<R> {
1350        inner: R,
1351        reads: Arc<std::sync::atomic::AtomicUsize>,
1352    }
1353
1354    impl<R: Read> Read for CountReads<R> {
1355        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1356            self.reads.fetch_add(1, Ordering::Relaxed);
1357            self.inner.read(buf)
1358        }
1359    }
1360
1361    impl<R: Seek> Seek for CountReads<R> {
1362        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1363            self.inner.seek(pos)
1364        }
1365    }
1366
1367    /// LZW's decoder reads one byte per call. Through the temp file's
1368    /// source those calls must not each reach the file (one system call
1369    /// per compressed byte made streamed decoding 17-34x slower than the
1370    /// same decode from memory).
1371    #[test]
1372    fn the_temp_file_is_read_in_large_pieces_by_a_byte_reader() {
1373        let input = text(64 * 1024, 4);
1374        let codec = stuffr::registry()
1375            .codec(stuffr::FormatId::new("compress"))
1376            .expect("compress is in every default build");
1377        let out = SharedVec::with_capacity(0);
1378        let mut sink = codec
1379            .encoder(Box::new(out.clone()), &EncodeOpts::default())
1380            .unwrap();
1381        sink.write_all(&input).unwrap();
1382        sink.finish().unwrap();
1383        let bytes = out.take();
1384        let len = bytes.len() as u64;
1385        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1386        let file = CountReads {
1387            inner: Cursor::new(bytes),
1388            reads: reads.clone(),
1389        };
1390        let src = temp_source(file, len);
1391        // The shape `MemSource` gives the in-memory path.
1392        assert_eq!(
1393            src.caps(),
1394            SourceCaps {
1395                seekable: true,
1396                len: Some(len)
1397            }
1398        );
1399        let mut buf = vec![0u8; CHUNK];
1400        let (decoded, _) = decode(
1401            codec.as_ref(),
1402            &DecodeOpts::default(),
1403            Box::new(src),
1404            &mut buf,
1405            &mut FakeClock(0),
1406            &mut Progress::new(&mut |_, _, _| {}, input.len() as u64),
1407        )
1408        .unwrap();
1409        assert_eq!(decoded, input.len() as u64);
1410        let reads = reads.load(Ordering::Relaxed);
1411        assert!(
1412            reads as u64 <= len / CHUNK as u64 + 4,
1413            "{reads} reads reached the file for {len} compressed bytes"
1414        );
1415    }
1416
1417    /// The same check through `measure`: LZW reads its input a byte at a
1418    /// time, so if the production temp-file path stopped buffering, the
1419    /// reads reaching the file would be about one per compressed byte.
1420    #[test]
1421    fn measure_reads_the_temp_file_in_large_pieces() {
1422        let _lock = armed_lock();
1423        let input = Input::Memory(vec![text(64 * 1024, 4)]);
1424        FILE_READS.with(|r| r.set(0));
1425        let m = on_disk(|| run("compress", &input, &plan(Mode::OneStream, 1)));
1426        let reads = FILE_READS.with(std::cell::Cell::get) as u64;
1427        assert!(m.bytes_out > 4096, "{} compressed bytes", m.bytes_out);
1428        assert!(reads > 0, "no read reached the temp file");
1429        assert!(
1430            reads <= m.bytes_out / CHUNK as u64 + 4,
1431            "{reads} reads reached the file for {} compressed bytes",
1432            m.bytes_out
1433        );
1434    }
1435
1436    /// `compress` can write twice its input; near the limit that must not be
1437    /// reserved in memory, over the budget. Each codec gets the destination
1438    /// its own worst case allows: `compress` goes to the temp file and its
1439    /// row says so; `gzip`, whose worst case fits, stays in memory beside it.
1440    #[test]
1441    fn compress_near_the_limit_goes_to_disk_and_is_marked() {
1442        let _lock = armed_lock();
1443        let len = 16 * 1024;
1444        let input = Input::Memory(vec![noise(len)]);
1445        // The input (16384) is between limit / 4 and limit / 2. gzip's
1446        // worst case (len + len / 8 + 1 KiB = 19456) fits in that half
1447        // exactly; compress's (2 * len + 1 KiB = 33792) does not.
1448        let p = Plan {
1449            memory_limit: 2 * 19_456,
1450            ..plan(Mode::OneStream, 1)
1451        };
1452        for (codec, want_temps, want_disk) in [("compress", 1, true), ("gzip", 0, false)] {
1453            let mut m = None;
1454            let made = temps_made(|| m = Some(run(codec, &input, &p)));
1455            assert_eq!(made, want_temps, "{codec}");
1456            assert_eq!(m.unwrap().on_disk, want_disk, "{codec}");
1457        }
1458        // Streamed: the whole limit is the budget.
1459        for (codec, limit, want) in [("gzip", 19_456, 0), ("compress", 33_791, 1)] {
1460            assert_eq!(
1461                destination(codec, len as u64, limit, true) == Dest::TempFile,
1462                want == 1,
1463                "{codec} streamed at {limit}"
1464            );
1465        }
1466        assert_eq!(
1467            destination("compress", len as u64, 33_792, true),
1468            Dest::Memory
1469        );
1470    }
1471
1472    #[test]
1473    fn the_output_goes_to_memory_whenever_its_worst_case_fits() {
1474        // 0 bytes in: worst case 1 KiB, which fits under 2048 / 2.
1475        // Beside input in memory: half the limit.
1476        assert_eq!(destination("gzip", 0, 2048, false), Dest::Memory);
1477        assert_eq!(destination("gzip", 0, 2047, false), Dest::TempFile);
1478        // 8000 + 1000 + 1024.
1479        assert_eq!(destination("gzip", 8000, 2 * 10_024, false), Dest::Memory);
1480        assert_eq!(
1481            destination("gzip", 8000, 2 * 10_024 - 1, false),
1482            Dest::TempFile
1483        );
1484        assert_eq!(
1485            destination("gzip", u64::MAX, u64::MAX, false),
1486            Dest::TempFile
1487        );
1488        // Streamed input holds no copy: the whole limit.
1489        assert_eq!(destination("gzip", 8000, 10_024, true), Dest::Memory);
1490        assert_eq!(destination("gzip", 8000, 10_023, true), Dest::TempFile);
1491        assert_eq!(
1492            destination("gzip", u64::MAX, u64::MAX, true),
1493            Dest::TempFile
1494        );
1495    }
1496
1497    /// Streamed input whose output fits in the whole limit stays off the
1498    /// disk, one stream included; only output past the limit makes a temp
1499    /// file.
1500    #[test]
1501    fn streamed_input_compresses_to_memory_when_the_output_fits() {
1502        let _lock = armed_lock();
1503        let s = Scratch::new();
1504        let (a, b) = (text(16 * 1024, 1), text(16 * 1024, 2));
1505        let paths = vec![s.file("a", &a), s.file("b", &b)];
1506        // 32 KiB is over 40000 / 2, so the input is streamed. One stream's
1507        // worst case (32768 + 4096 + 1024 = 37888) fits under 40000, not
1508        // under 37887; each file's (19456) fits under either.
1509        let files = load_input(&paths, 40_000).unwrap().0;
1510        assert!(matches!(files, Input::Files(_)));
1511        let memory = Input::Memory(vec![a, b]);
1512        for (mode, limit, want_temps) in [
1513            (Mode::PerFile, 40_000, 0),
1514            (Mode::OneStream, 40_000, 0),
1515            (Mode::OneStream, 37_888, 0),
1516            (Mode::OneStream, 37_887, 1),
1517        ] {
1518            let p = Plan {
1519                memory_limit: limit,
1520                ..plan(mode, 1)
1521            };
1522            let mut got = None;
1523            let made = temps_made(|| got = Some(run("gzip", &files, &p)));
1524            assert_eq!(made, want_temps, "{mode:?} at {limit}");
1525            let want = run("gzip", &memory, &plan(mode, 1)).bytes_out;
1526            assert_eq!(got.unwrap().bytes_out, want, "{mode:?}");
1527        }
1528    }
1529
1530    /// In-memory input whose output does not fit goes to the temp file too,
1531    /// for each codec whose own worst case is over the budget.
1532    #[test]
1533    fn memory_input_past_the_output_limit_uses_the_temp_file() {
1534        let _lock = armed_lock();
1535        let input = Input::Memory(vec![text(16 * 1024, 5)]);
1536        // The input fits under 32768 / 2; its worst case does not.
1537        let p = Plan {
1538            memory_limit: 32 * 1024,
1539            ..plan(Mode::OneStream, 1)
1540        };
1541        for codec in ["gzip", "compress"] {
1542            let made = temps_made(|| {
1543                run(codec, &input, &p);
1544            });
1545            assert_eq!(made, 1, "{codec}");
1546        }
1547    }
1548
1549    /// The reserved `Vec` must not reallocate inside a timed region, even
1550    /// on input no codec can shrink, at any level.
1551    #[test]
1552    fn the_reserved_room_holds_incompressible_output() {
1553        let input = noise(64 * 1024);
1554        let reg = stuffr::registry();
1555        for name in crate::bench::levels::benchable_codecs() {
1556            let codec = reg.codec(stuffr::FormatId::new(name)).unwrap();
1557            let sweep = crate::bench::levels::levels_of(name).unwrap().sweep;
1558            let levels: Vec<Option<i32>> = if sweep.is_empty() {
1559                vec![None]
1560            } else {
1561                sweep.iter().map(|&l| Some(l)).collect()
1562            };
1563            for level in levels {
1564                let room = output_room(name, input.len() as u64).unwrap() as usize;
1565                let shared = SharedVec::with_capacity(room);
1566                let cap = shared.capacity();
1567                let dst = BufWriter::with_capacity(CHUNK, shared.clone());
1568                let opts = EncodeOpts {
1569                    level,
1570                    ..Default::default()
1571                };
1572                let mut sink = codec.encoder(Box::new(dst), &opts).unwrap();
1573                sink.write_all(&input).unwrap();
1574                sink.finish().unwrap();
1575                assert_eq!(shared.capacity(), cap, "{name} {level:?} reallocated");
1576                assert!(shared.take().len() <= room, "{name} {level:?}");
1577            }
1578        }
1579    }
1580
1581    /// A log still being written: the rows bench it as it was at load.
1582    #[test]
1583    fn a_file_that_grows_after_load_is_benched_at_its_loaded_length() {
1584        let _lock = armed_lock();
1585        let s = Scratch::new();
1586        let original = text(40 * 1024, 3);
1587        let path = s.file("grow.log", &original);
1588        let (files, bytes_in) = load_input(std::slice::from_ref(&path), 0).unwrap();
1589        assert!(matches!(files, Input::Files(_)));
1590        assert_eq!(bytes_in, original.len() as u64);
1591        let mut f = fs::OpenOptions::new().append(true).open(&path).unwrap();
1592        f.write_all(&text(10 * 1024, 9)).unwrap();
1593        drop(f);
1594        let snapshot = Input::Memory(vec![original]);
1595        for mode in [Mode::OneStream, Mode::PerFile] {
1596            let p = plan(mode, 1);
1597            for codec in ["gzip", "compress"] {
1598                // Ok: the round trip gave back exactly the loaded length.
1599                let grown = run(codec, &files, &p);
1600                assert_eq!(
1601                    grown.bytes_out,
1602                    run(codec, &snapshot, &p).bytes_out,
1603                    "{codec}: the appended bytes were benched"
1604                );
1605            }
1606        }
1607    }
1608
1609    #[test]
1610    fn load_input_splits_at_half_the_memory_limit() {
1611        let s = Scratch::new();
1612        let paths = vec![s.file("a", &[1; 100]), s.file("b", &[2; 100])];
1613        match load_input(&paths, 400).unwrap() {
1614            (Input::Memory(parts), 200) => {
1615                assert_eq!(parts, vec![vec![1; 100], vec![2; 100]])
1616            }
1617            other => panic!("200 bytes fit in 400 / 2: {other:?}"),
1618        }
1619        assert!(matches!(
1620            load_input(&paths, 399).unwrap(),
1621            (Input::Files(_), 200)
1622        ));
1623    }
1624
1625    /// Restores a file's mode, so `Scratch` can remove it.
1626    #[cfg(unix)]
1627    struct Restore(PathBuf);
1628
1629    #[cfg(unix)]
1630    impl Drop for Restore {
1631        fn drop(&mut self) {
1632            use std::os::unix::fs::PermissionsExt;
1633            let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o600));
1634        }
1635    }
1636
1637    /// A file that cannot be opened is a usage error naming it, whether
1638    /// the input is loaded into memory or streamed (opened by `warm`).
1639    #[cfg(unix)]
1640    #[test]
1641    fn an_input_that_cannot_be_opened_is_a_usage_error_naming_it() {
1642        use std::os::unix::fs::PermissionsExt;
1643        let s = Scratch::new();
1644        let locked = s.file("locked.log", b"secret");
1645        let _restore = Restore(locked.clone());
1646        fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
1647        // Root opens it anyway; there is nothing to test.
1648        if File::open(&locked).is_ok() {
1649            return;
1650        }
1651        let want = format!("{}: cannot read it (", locked.display());
1652        let usage = |r: stuffr::Result<()>| match r {
1653            Err(Error::Usage(m)) => m,
1654            other => panic!("expected a usage error, got {other:?}"),
1655        };
1656        let paths = vec![locked.clone()];
1657        let m = usage(load_input(&paths, 1 << 30).map(drop));
1658        assert!(m.starts_with(&want), "in memory: {m}");
1659        // Streamed: loading only reads the size; the warm-up opens it.
1660        let (files, _) = load_input(&paths, 0).unwrap();
1661        assert!(matches!(files, Input::Files(_)));
1662        let m = usage(warm(&files));
1663        assert!(m.starts_with(&want), "streamed: {m}");
1664    }
1665}