1use 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
64const CHUNK: usize = 64 * 1024;
66
67pub trait Clock {
69 fn now(&mut self) -> u64;
70}
71
72pub 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#[derive(Debug)]
96pub enum Input {
97 Memory(Vec<Vec<u8>>),
98 Files(Vec<Snapshot>),
99}
100
101#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Snapshot {
105 pub path: PathBuf,
106 pub len: u64,
107}
108
109impl Snapshot {
110 fn open(&self) -> io::Result<io::Take<File>> {
112 Ok(File::open(&self.path)?.take(self.len))
113 }
114
115 fn open_input(&self) -> stuffr::Result<io::Take<File>> {
118 self.open().map_err(|e| super::unreadable(&self.path, &e))
119 }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum Mode {
125 OneStream,
126 PerFile,
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct Plan {
132 pub mode: Mode,
133 pub repeat: u32,
135 pub threads: Option<usize>,
137 pub memory_limit: u64,
138}
139
140pub 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
175pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum Phase {
192 Compress,
193 Decompress,
194}
195
196pub 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#[derive(Clone, Copy)]
223enum Part<'a> {
224 Memory(&'a [u8]),
225 File(&'a Snapshot),
226}
227
228impl Part<'_> {
229 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
238enum Feed<'a> {
240 Memory(&'a [u8]),
241 File(&'a Snapshot, io::Take<File>),
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249enum Dest {
250 Memory,
251 TempFile,
252}
253
254fn destination(codec: &str, input_len: u64, memory_limit: u64, streamed: bool) -> Dest {
261 #[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
278fn 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
379pub 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
392fn 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
398struct 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 fn start(&mut self) {
419 self.fed = 0;
420 self.decoded = 0;
421 (self.report)(Phase::Compress, 0, self.total);
422 }
423
424 fn fed(&mut self, n: usize) {
426 let fed = self.fed.saturating_add(n as u64).min(self.total);
427 if fed > self.fed {
429 self.fed = fed;
430 (self.report)(Phase::Compress, fed, self.total);
431 }
432 }
433
434 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
441fn 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
449struct 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 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 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 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 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
576fn 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
609fn 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
624fn 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#[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
668struct 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
710fn 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#[cfg(not(test))]
753fn counted(file: File) -> File {
754 file
755}
756
757#[cfg(test)]
760fn counted(file: File) -> tests::CountedFile {
761 tests::CountedFile(file)
762}
763
764static TEMP_SEQ: AtomicU32 = AtomicU32::new(0);
766
767struct TempOut {
771 path: PathBuf,
772 _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 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 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 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 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 pub(super) static FORCE_DISK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
903 }
904
905 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 static FILE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
916 }
917
918 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 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 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 assert_eq!(both.compress_ns, 2 * 30);
1014 assert_eq!(both.decompress_ns, 2 * 10);
1015 }
1016
1017 #[test]
1022 fn a_streamed_run_times_each_write_and_not_the_reads() {
1023 let _lock = armed_lock();
1024 let s = Scratch::new();
1025 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 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 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 #[test]
1065 fn the_fake_clock_still_times_only_codec_work() {
1066 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 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 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 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 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 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 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 #[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 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 #[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 #[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 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 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 assert_eq!(destination("gzip", 0, 2048, false), Dest::Memory);
1477 assert_eq!(destination("gzip", 0, 2047, false), Dest::TempFile);
1478 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 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 #[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 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 #[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 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 #[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 #[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 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 #[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 #[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 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 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}