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
64pub(super) const 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 pub(super) 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(shrank(snap, read));
550 }
551 break;
552 }
553 read += n as u64;
554 let chunk = &self.buf[..n];
555 let (r, t) = timed(clock, || sink.write_all(chunk));
556 r?;
557 ns += t;
558 progress.fed(n);
559 }
560 }
561 }
562 }
563 let (r, t) = timed(clock, || sink.finish());
564 r?;
565 Ok(ns + t)
566 }
567}
568
569fn decode(
574 codec: &dyn Codec,
575 opts: &DecodeOpts,
576 src: Box<dyn Source>,
577 buf: &mut [u8],
578 clock: &mut dyn Clock,
579 progress: &mut Progress<'_>,
580) -> stuffr::Result<(u64, u64)> {
581 let (first, mut ns) = timed(clock, || {
582 let mut decoder = codec.decoder(src, opts)?;
583 let n = fill(&mut decoder, buf).map_err(Error::from_decode_io)?;
584 Ok::<_, Error>((decoder, n))
585 });
586 let (mut decoder, mut n) = first?;
587 let mut total = 0u64;
588 loop {
589 total += n as u64;
590 progress.decoded(n);
591 if n < buf.len() {
592 break;
593 }
594 let (r, t) = timed(clock, || fill(&mut decoder, buf));
595 ns += t;
596 n = r.map_err(Error::from_decode_io)?;
597 }
598 drop(decoder);
599 Ok((total, ns))
600}
601
602pub(super) fn shrank(snap: &Snapshot, read: u64) -> Error {
605 Error::Io(io::Error::new(
606 io::ErrorKind::UnexpectedEof,
607 format!(
608 "{} shrank to {read} bytes from {} while bench ran",
609 snap.path.display(),
610 snap.len
611 ),
612 ))
613}
614
615pub(super) fn fill(r: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
618 let mut filled = 0;
619 while filled < buf.len() {
620 match r.read(&mut buf[filled..]) {
621 Ok(0) => break,
622 Ok(n) => filled += n,
623 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
624 Err(e) => return Err(e),
625 }
626 }
627 Ok(filled)
628}
629
630pub(super) fn read_some(r: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
632 loop {
633 match r.read(buf) {
634 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
635 other => return other,
636 }
637 }
638}
639
640#[derive(Clone)]
643struct SharedVec(Arc<Mutex<Vec<u8>>>);
644
645impl SharedVec {
646 fn with_capacity(n: usize) -> Self {
647 Self(Arc::new(Mutex::new(Vec::with_capacity(n))))
648 }
649
650 #[cfg(test)]
651 fn capacity(&self) -> usize {
652 self.0.lock().unwrap_or_else(|e| e.into_inner()).capacity()
653 }
654
655 fn take(&self) -> Vec<u8> {
656 std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()))
657 }
658}
659
660impl Write for SharedVec {
661 fn write(&mut self, b: &[u8]) -> io::Result<usize> {
662 self.0
663 .lock()
664 .unwrap_or_else(|e| e.into_inner())
665 .extend_from_slice(b);
666 Ok(b.len())
667 }
668
669 fn flush(&mut self) -> io::Result<()> {
670 Ok(())
671 }
672}
673
674struct MemSource {
677 cursor: Cursor<Vec<u8>>,
678 len: u64,
679}
680
681impl MemSource {
682 fn new(bytes: Vec<u8>) -> Self {
683 let len = bytes.len() as u64;
684 Self {
685 cursor: Cursor::new(bytes),
686 len,
687 }
688 }
689}
690
691impl Read for MemSource {
692 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
693 self.cursor.read(buf)
694 }
695}
696
697impl Seek for MemSource {
698 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
699 self.cursor.seek(pos)
700 }
701}
702
703impl Source for MemSource {
704 fn caps(&self) -> SourceCaps {
705 SourceCaps {
706 seekable: true,
707 len: Some(self.len),
708 }
709 }
710
711 fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
712 Some(self)
713 }
714}
715
716pub(super) fn temp_source<R: Read + Seek + Send>(inner: R, len: u64) -> BufSource<R> {
721 BufSource {
722 inner: BufReader::with_capacity(CHUNK, inner),
723 len,
724 }
725}
726
727pub(super) struct BufSource<R> {
728 inner: BufReader<R>,
729 len: u64,
730}
731
732impl<R: Read> Read for BufSource<R> {
733 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
734 self.inner.read(buf)
735 }
736}
737
738impl<R: Seek> Seek for BufSource<R> {
739 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
740 self.inner.seek(pos)
741 }
742}
743
744impl<R: Read + Seek + Send> Source for BufSource<R> {
745 fn caps(&self) -> SourceCaps {
746 SourceCaps {
747 seekable: true,
748 len: Some(self.len),
749 }
750 }
751
752 fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
753 Some(self)
754 }
755}
756
757#[cfg(not(test))]
759fn counted(file: File) -> File {
760 file
761}
762
763#[cfg(test)]
766fn counted(file: File) -> tests::CountedFile {
767 tests::CountedFile(file)
768}
769
770static TEMP_SEQ: AtomicU32 = AtomicU32::new(0);
772
773pub(super) struct TempOut {
777 path: PathBuf,
778 _armed: CleanupGuard,
781}
782
783impl TempOut {
784 pub(super) fn create() -> io::Result<(Self, File)> {
785 let dir = std::env::temp_dir();
786 let mut tries = 0;
787 loop {
788 let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
789 let path = dir.join(format!("stuffr-bench-{}-{n}", std::process::id()));
790 match create_armed(&path) {
791 Ok((file, armed)) => {
792 return Ok((
793 Self {
794 path,
795 _armed: armed,
796 },
797 file,
798 ));
799 }
800 Err(e) if e.kind() == io::ErrorKind::AlreadyExists && tries < 1000 => tries += 1,
801 Err(e) => return Err(e),
802 }
803 }
804 }
805
806 pub(super) fn path(&self) -> &Path {
807 &self.path
808 }
809}
810
811impl Drop for TempOut {
812 fn drop(&mut self) {
813 let _ = fs::remove_file(&self.path);
814 }
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820 use std::fs;
821 use std::path::PathBuf;
822 use std::sync::atomic::{AtomicU32, Ordering};
823
824 struct FakeClock(u64);
826
827 impl Clock for FakeClock {
828 fn now(&mut self) -> u64 {
829 let t = self.0;
830 self.0 += 10;
831 t
832 }
833 }
834
835 struct ScriptClock {
837 durations: Vec<u64>,
838 reads: usize,
839 t: u64,
840 }
841
842 impl Clock for ScriptClock {
843 fn now(&mut self) -> u64 {
844 if self.reads % 2 == 1 {
845 self.t += self.durations[self.reads / 2];
846 } else {
847 self.t += 1_000;
848 }
849 self.reads += 1;
850 self.t
851 }
852 }
853
854 struct Scratch(PathBuf);
856
857 impl Scratch {
858 fn new() -> Self {
859 static N: AtomicU32 = AtomicU32::new(0);
860 let n = N.fetch_add(1, Ordering::Relaxed);
861 let dir =
862 std::env::temp_dir().join(format!("stuffr-benchtest-{}-{n}", std::process::id()));
863 fs::create_dir_all(&dir).unwrap();
864 Scratch(dir)
865 }
866
867 fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
868 let p = self.0.join(name);
869 fs::write(&p, bytes).unwrap();
870 p
871 }
872 }
873
874 impl Drop for Scratch {
875 fn drop(&mut self) {
876 let _ = fs::remove_dir_all(&self.0);
877 }
878 }
879
880 fn armed_lock() -> std::sync::MutexGuard<'static, ()> {
882 crate::compat::ARM_TEST_LOCK
883 .lock()
884 .unwrap_or_else(|e| e.into_inner())
885 }
886
887 fn text(len: usize, seed: u8) -> Vec<u8> {
888 b"the quick brown fox jumps over the lazy dog, "
889 .iter()
890 .cycle()
891 .enumerate()
892 .map(|(i, &b)| b.wrapping_add(seed).wrapping_add((i / 997) as u8))
893 .take(len)
894 .collect()
895 }
896
897 fn plan(mode: Mode, repeat: u32) -> Plan {
898 Plan {
899 mode,
900 repeat,
901 threads: None,
902 memory_limit: 1 << 30,
903 }
904 }
905
906 thread_local! {
907 pub(super) static FORCE_DISK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
909 }
910
911 fn on_disk<T>(f: impl FnOnce() -> T) -> T {
913 FORCE_DISK.with(|d| d.set(true));
914 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
915 FORCE_DISK.with(|d| d.set(false));
916 r.unwrap_or_else(|e| std::panic::resume_unwind(e))
917 }
918
919 thread_local! {
920 static FILE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
922 }
923
924 pub(super) struct CountedFile(pub(super) File);
926
927 impl Read for CountedFile {
928 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
929 FILE_READS.with(|r| r.set(r.get() + 1));
930 self.0.read(buf)
931 }
932 }
933
934 impl Seek for CountedFile {
935 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
936 self.0.seek(pos)
937 }
938 }
939
940 fn temps_made(f: impl FnOnce()) -> u32 {
943 let before = TEMP_SEQ.load(Ordering::Relaxed);
944 f();
945 TEMP_SEQ.load(Ordering::Relaxed) - before
946 }
947
948 fn noise(len: usize) -> Vec<u8> {
950 let mut x = 0x9e37_79b9_7f4a_7c15u64;
951 (0..len)
952 .map(|_| {
953 x ^= x << 13;
954 x ^= x >> 7;
955 x ^= x << 17;
956 (x >> 24) as u8
957 })
958 .collect()
959 }
960
961 fn ok(o: Outcome) -> Measured {
962 match o {
963 Outcome::Ok(m) => m,
964 Outcome::Failed(e) => panic!("failed: {e}"),
965 }
966 }
967
968 fn run(codec: &str, input: &Input, plan: &Plan) -> Measured {
969 ok(measure(
970 codec,
971 None,
972 input,
973 plan,
974 &mut FakeClock(0),
975 &mut |_, _, _| {},
976 ))
977 }
978
979 fn bench_temps() -> Vec<String> {
980 let prefix = format!("stuffr-bench-{}-", std::process::id());
981 fs::read_dir(std::env::temp_dir())
982 .unwrap()
983 .filter_map(|e| e.ok()?.file_name().into_string().ok())
984 .filter(|n| n.starts_with(&prefix))
985 .collect()
986 }
987
988 #[test]
989 fn one_stream_compresses_the_concatenation() {
990 let (a, b) = (text(20_000, 0), text(30_000, 7));
991 let both = [a.clone(), b.clone()].concat();
992 let p = plan(Mode::OneStream, 1);
993 for codec in ["gzip", "zstd", "bzip2"] {
994 let parts = run(codec, &Input::Memory(vec![a.clone(), b.clone()]), &p);
995 let whole = run(codec, &Input::Memory(vec![both.clone()]), &p);
996 assert_eq!(parts.bytes_out, whole.bytes_out, "{codec}");
997 }
998 }
999
1000 #[test]
1001 fn per_file_sums_each_file() {
1002 let (a, b) = (text(20_000, 0), text(30_000, 7));
1003 let p = plan(Mode::PerFile, 1);
1004 let both = run("gzip", &Input::Memory(vec![a.clone(), b.clone()]), &p);
1005 let one = run("gzip", &Input::Memory(vec![a]), &p);
1006 let two = run("gzip", &Input::Memory(vec![b]), &p);
1007 assert_eq!(both.bytes_out, one.bytes_out + two.bytes_out);
1008 let stream = run(
1009 "gzip",
1010 &Input::Memory(vec![text(20_000, 0), text(30_000, 7)]),
1011 &plan(Mode::OneStream, 1),
1012 );
1013 assert_ne!(
1014 both.bytes_out, stream.bytes_out,
1015 "per-file is not one stream"
1016 );
1017 assert_eq!(both.compress_ns, 2 * 30);
1020 assert_eq!(both.decompress_ns, 2 * 10);
1021 }
1022
1023 #[test]
1028 fn a_streamed_run_times_each_write_and_not_the_reads() {
1029 let _lock = armed_lock();
1030 let s = Scratch::new();
1031 let paths = vec![s.file("a", &text(100 * 1024, 6))];
1033 let files = load_input(&paths, 0).unwrap().0;
1034 let mut clock = FakeClock(0);
1035 let m = ok(measure(
1036 "gzip",
1037 None,
1038 &files,
1039 &plan(Mode::OneStream, 1),
1040 &mut clock,
1041 &mut |_, _, _| {},
1042 ));
1043 let regions = 1 + 2 + 1;
1044 let fills = 2;
1046 assert_eq!(m.compress_ns, 10 * regions);
1047 assert_eq!(m.decompress_ns, 10 * fills);
1048 assert_eq!(clock.0, 10 * 2 * (regions + fills), "no other clock reads");
1049 }
1050
1051 #[test]
1052 fn no_threads_means_no_governor() {
1053 assert!(governor_for(&plan(Mode::OneStream, 1)).is_none());
1059 let two = Plan {
1060 threads: Some(2),
1061 ..plan(Mode::OneStream, 1)
1062 };
1063 assert!(governor_for(&two).is_some());
1064 }
1065
1066 #[test]
1071 fn the_fake_clock_still_times_only_codec_work() {
1072 let input = Input::Memory(vec![text(160 * 1024, 3)]);
1074 let mut clock = FakeClock(0);
1075 let m = ok(measure(
1076 "gzip",
1077 None,
1078 &input,
1079 &plan(Mode::OneStream, 1),
1080 &mut clock,
1081 &mut |_, _, _| {},
1082 ));
1083 let compress_pieces = 1 + 3 + 1;
1084 let decompress_pieces = 3;
1086 assert_eq!(m.compress_ns, 10 * compress_pieces);
1087 assert_eq!(m.decompress_ns, 10 * decompress_pieces);
1088 assert_eq!(
1089 clock.0,
1090 10 * 2 * (compress_pieces + decompress_pieces),
1091 "two reads per piece, nothing else"
1092 );
1093 }
1094
1095 struct SeenClock(std::rc::Rc<std::cell::Cell<u64>>);
1098
1099 impl Clock for SeenClock {
1100 fn now(&mut self) -> u64 {
1101 let n = self.0.get();
1102 self.0.set(n + 1);
1103 10 * n
1104 }
1105 }
1106
1107 fn check_reports(seen: &[(Phase, u64, u64)], total: u64, repeats: usize, what: &str) {
1111 let opens: Vec<usize> = (0..seen.len())
1112 .filter(|&i| matches!(seen[i], (Phase::Compress, 0, _)))
1113 .collect();
1114 assert_eq!(opens.len(), repeats, "{what}: {seen:?}");
1115 assert_eq!(opens[0], 0, "{what}: the first report opens a repeat");
1116 for (i, &start) in opens.iter().enumerate() {
1117 let end = opens.get(i + 1).copied().unwrap_or(seen.len());
1118 let one = &seen[start..end];
1119 assert!(one.iter().all(|r| r.2 == total), "{what}: {one:?}");
1120 let fed: Vec<u64> = one
1121 .iter()
1122 .filter(|r| r.0 == Phase::Compress)
1123 .map(|r| r.1)
1124 .collect();
1125 let decoded: Vec<u64> = one
1126 .iter()
1127 .filter(|r| r.0 == Phase::Decompress)
1128 .map(|r| r.1)
1129 .collect();
1130 assert!(fed.windows(2).all(|w| w[0] < w[1]), "{what}: {fed:?}");
1131 assert!(
1132 decoded.windows(2).all(|w| w[0] <= w[1]),
1133 "{what}: {decoded:?}"
1134 );
1135 assert_eq!(fed.last(), Some(&total), "{what}: compression");
1136 assert_eq!(decoded.last(), Some(&total), "{what}: decompression");
1137 assert!(fed.len() > 2 && decoded.len() > 1, "{what}: {one:?}");
1138 }
1139 }
1140
1141 #[test]
1142 fn progress_is_reported_between_pieces_only() {
1143 use std::{cell::Cell, rc::Rc};
1144 let _lock = armed_lock();
1145 let s = Scratch::new();
1146 let data = text(160 * 1024, 5);
1147 let paths = vec![
1148 s.file("a", &data[..100 * 1024]),
1149 s.file("b", &data[100 * 1024..]),
1150 ];
1151 let memory = load_input(&paths, 1 << 30).unwrap().0;
1152 let files = load_input(&paths, 0).unwrap().0;
1153 for (input, disk, name) in [
1154 (&memory, false, "memory"),
1155 (&memory, true, "memory, temp file"),
1156 (&files, false, "streamed"),
1157 (&files, true, "streamed, temp file"),
1158 ] {
1159 for mode in [Mode::OneStream, Mode::PerFile] {
1160 let reads = Rc::new(Cell::new(0));
1161 let mut clock = SeenClock(reads.clone());
1162 let mut seen = Vec::new();
1163 let mut report = |phase, done, total| {
1164 assert_eq!(reads.get() % 2, 0, "a report inside a timed region");
1165 seen.push((phase, done, total));
1166 };
1167 let p = plan(mode, 2);
1168 let mut go = || measure("gzip", None, input, &p, &mut clock, &mut report);
1169 let o = if disk { on_disk(go) } else { go() };
1170 ok(o);
1171 check_reports(&seen, data.len() as u64, 2, &format!("{name} {mode:?}"));
1172 }
1173 }
1174 }
1175
1176 #[test]
1177 fn repeat_reports_the_median() {
1178 let input = Input::Memory(vec![text(4096, 1)]);
1179 let mut clock = ScriptClock {
1182 durations: vec![10, 10, 10, 7, 2, 3, 5, 5, 5, 5, 10, 9],
1183 reads: 0,
1184 t: 0,
1185 };
1186 let m = ok(measure(
1187 "gzip",
1188 None,
1189 &input,
1190 &plan(Mode::OneStream, 3),
1191 &mut clock,
1192 &mut |_, _, _| {},
1193 ));
1194 assert_eq!(m.compress_ns, 20);
1195 assert_eq!(m.decompress_ns, 7);
1196 assert_eq!(clock.reads, 24, "two reads per piece, nothing else");
1197 }
1198
1199 #[test]
1200 fn an_even_repeat_reports_the_lower_median() {
1201 let input = Input::Memory(vec![text(4096, 1)]);
1202 let mut clock = ScriptClock {
1203 durations: vec![20, 10, 10, 1, 4, 3, 3, 2, 10, 10, 10, 3, 5, 5, 10, 4],
1205 reads: 0,
1206 t: 0,
1207 };
1208 let m = ok(measure(
1209 "gzip",
1210 None,
1211 &input,
1212 &plan(Mode::OneStream, 4),
1213 &mut clock,
1214 &mut |_, _, _| {},
1215 ));
1216 assert_eq!(m.compress_ns, 20);
1217 assert_eq!(m.decompress_ns, 2);
1218 }
1219
1220 #[test]
1221 fn a_rejected_level_is_a_failed_row() {
1222 let input = Input::Memory(vec![text(1024, 0)]);
1223 let mut clock = FakeClock(0);
1224 match measure(
1225 "gzip",
1226 Some(99),
1227 &input,
1228 &plan(Mode::OneStream, 1),
1229 &mut clock,
1230 &mut |_, _, _| {},
1231 ) {
1232 Outcome::Failed(msg) => assert!(msg.contains("99"), "{msg}"),
1233 Outcome::Ok(m) => panic!("level 99 accepted: {m:?}"),
1234 }
1235 assert_eq!(clock.0, 0, "nothing was timed");
1236 }
1237
1238 #[test]
1239 fn an_unknown_format_is_a_failed_row() {
1240 let input = Input::Memory(vec![text(1024, 0)]);
1241 let o = measure(
1242 "nope",
1243 None,
1244 &input,
1245 &plan(Mode::OneStream, 1),
1246 &mut FakeClock(0),
1247 &mut |_, _, _| {},
1248 );
1249 assert!(matches!(o, Outcome::Failed(_)), "{o:?}");
1250 }
1251
1252 #[test]
1253 fn streamed_input_matches_memory_input() {
1254 let _lock = armed_lock();
1255 let s = Scratch::new();
1256 let (a, b) = (text(32 * 1024, 2), text(32 * 1024, 9));
1257 let paths = vec![s.file("a", &a), s.file("b", &b)];
1258 let files = load_input(&paths, 0).unwrap().0;
1259 assert!(matches!(files, Input::Files(_)));
1260 warm(&files).unwrap();
1261 let memory = load_input(&paths, 1 << 30).unwrap().0;
1262 assert!(matches!(memory, Input::Memory(_)));
1263 for mode in [Mode::OneStream, Mode::PerFile] {
1264 let p = plan(mode, 1);
1265 for codec in ["gzip", "xz", "lz4"] {
1266 let want = run(codec, &memory, &p).bytes_out;
1267 assert_eq!(run(codec, &files, &p).bytes_out, want, "{codec}");
1268 let disk = on_disk(|| run(codec, &files, &p)).bytes_out;
1269 assert_eq!(disk, want, "{codec} via the temp file");
1270 }
1271 }
1272 }
1273
1274 #[test]
1275 fn the_output_temp_file_is_removed() {
1276 let _lock = armed_lock();
1277 let s = Scratch::new();
1278 let paths = vec![s.file("a", &text(16 * 1024, 4))];
1279 let files = load_input(&paths, 0).unwrap().0;
1280 let made = temps_made(|| {
1281 on_disk(|| run("gzip", &files, &plan(Mode::OneStream, 2)));
1282 });
1283 assert_eq!(made, 1);
1284 assert_eq!(bench_temps(), Vec::<String>::new());
1285 }
1286
1287 #[test]
1288 fn the_temp_guard_removes_on_panic() {
1289 let _lock = armed_lock();
1290 let seen = std::sync::Mutex::new(None::<PathBuf>);
1291 let r = std::panic::catch_unwind(|| {
1292 let (guard, _file) = TempOut::create().unwrap();
1293 *seen.lock().unwrap() = Some(guard.path().to_path_buf());
1294 assert!(guard.path().exists());
1295 panic!("mid-run");
1296 });
1297 assert!(r.is_err());
1298 let path = seen.into_inner().unwrap().expect("the guard was created");
1299 assert!(!path.exists(), "{} survived the panic", path.display());
1300 #[cfg(unix)]
1301 assert!(
1302 crate::compat::armed_path().is_none(),
1303 "still armed after the panic"
1304 );
1305 }
1306
1307 #[cfg(unix)]
1308 #[test]
1309 fn the_temp_file_is_armed_for_signals() {
1310 let _lock = armed_lock();
1311 let (guard, _file) = TempOut::create().unwrap();
1312 let path = guard.path().to_path_buf();
1313 let name = path.file_name().unwrap().to_str().unwrap().to_owned();
1314 assert!(
1315 name.starts_with(&format!("stuffr-bench-{}-", std::process::id())),
1316 "{name}"
1317 );
1318 assert_eq!(crate::compat::armed_path().as_deref(), Some(path.as_path()));
1319 drop(guard);
1320 assert!(
1321 crate::compat::armed_path().is_none(),
1322 "armed after the drop"
1323 );
1324 assert!(!path.exists());
1325 }
1326
1327 #[test]
1328 fn empty_input_measures_without_error() {
1329 for mode in [Mode::OneStream, Mode::PerFile] {
1330 for codec in crate::bench::levels::benchable_codecs() {
1331 let m = run(codec, &Input::Memory(vec![Vec::new()]), &plan(mode, 1));
1332 assert!(m.bytes_out < 1024, "{codec}: {m:?}");
1333 }
1334 }
1335 }
1336
1337 #[test]
1338 fn every_benchable_codec_round_trips_in_both_modes() {
1339 let _lock = armed_lock();
1340 let s = Scratch::new();
1341 let paths = vec![s.file("a", &text(8 * 1024, 5)), s.file("b", &text(4096, 8))];
1342 let files = load_input(&paths, 0).unwrap().0;
1343 let memory = load_input(&paths, 1 << 30).unwrap().0;
1344 for mode in [Mode::OneStream, Mode::PerFile] {
1345 for codec in crate::bench::levels::benchable_codecs() {
1346 for input in [&files, &memory] {
1347 run(codec, input, &plan(mode, 1));
1348 on_disk(|| run(codec, input, &plan(mode, 1)));
1349 }
1350 }
1351 }
1352 }
1353
1354 struct CountReads<R> {
1356 inner: R,
1357 reads: Arc<std::sync::atomic::AtomicUsize>,
1358 }
1359
1360 impl<R: Read> Read for CountReads<R> {
1361 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1362 self.reads.fetch_add(1, Ordering::Relaxed);
1363 self.inner.read(buf)
1364 }
1365 }
1366
1367 impl<R: Seek> Seek for CountReads<R> {
1368 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
1369 self.inner.seek(pos)
1370 }
1371 }
1372
1373 #[test]
1378 fn the_temp_file_is_read_in_large_pieces_by_a_byte_reader() {
1379 let input = text(64 * 1024, 4);
1380 let codec = stuffr::registry()
1381 .codec(stuffr::FormatId::new("compress"))
1382 .expect("compress is in every default build");
1383 let out = SharedVec::with_capacity(0);
1384 let mut sink = codec
1385 .encoder(Box::new(out.clone()), &EncodeOpts::default())
1386 .unwrap();
1387 sink.write_all(&input).unwrap();
1388 sink.finish().unwrap();
1389 let bytes = out.take();
1390 let len = bytes.len() as u64;
1391 let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1392 let file = CountReads {
1393 inner: Cursor::new(bytes),
1394 reads: reads.clone(),
1395 };
1396 let src = temp_source(file, len);
1397 assert_eq!(
1399 src.caps(),
1400 SourceCaps {
1401 seekable: true,
1402 len: Some(len)
1403 }
1404 );
1405 let mut buf = vec![0u8; CHUNK];
1406 let (decoded, _) = decode(
1407 codec.as_ref(),
1408 &DecodeOpts::default(),
1409 Box::new(src),
1410 &mut buf,
1411 &mut FakeClock(0),
1412 &mut Progress::new(&mut |_, _, _| {}, input.len() as u64),
1413 )
1414 .unwrap();
1415 assert_eq!(decoded, input.len() as u64);
1416 let reads = reads.load(Ordering::Relaxed);
1417 assert!(
1418 reads as u64 <= len / CHUNK as u64 + 4,
1419 "{reads} reads reached the file for {len} compressed bytes"
1420 );
1421 }
1422
1423 #[test]
1427 fn measure_reads_the_temp_file_in_large_pieces() {
1428 let _lock = armed_lock();
1429 let input = Input::Memory(vec![text(64 * 1024, 4)]);
1430 FILE_READS.with(|r| r.set(0));
1431 let m = on_disk(|| run("compress", &input, &plan(Mode::OneStream, 1)));
1432 let reads = FILE_READS.with(std::cell::Cell::get) as u64;
1433 assert!(m.bytes_out > 4096, "{} compressed bytes", m.bytes_out);
1434 assert!(reads > 0, "no read reached the temp file");
1435 assert!(
1436 reads <= m.bytes_out / CHUNK as u64 + 4,
1437 "{reads} reads reached the file for {} compressed bytes",
1438 m.bytes_out
1439 );
1440 }
1441
1442 #[test]
1447 fn compress_near_the_limit_goes_to_disk_and_is_marked() {
1448 let _lock = armed_lock();
1449 let len = 16 * 1024;
1450 let input = Input::Memory(vec![noise(len)]);
1451 let p = Plan {
1455 memory_limit: 2 * 19_456,
1456 ..plan(Mode::OneStream, 1)
1457 };
1458 for (codec, want_temps, want_disk) in [("compress", 1, true), ("gzip", 0, false)] {
1459 let mut m = None;
1460 let made = temps_made(|| m = Some(run(codec, &input, &p)));
1461 assert_eq!(made, want_temps, "{codec}");
1462 assert_eq!(m.unwrap().on_disk, want_disk, "{codec}");
1463 }
1464 for (codec, limit, want) in [("gzip", 19_456, 0), ("compress", 33_791, 1)] {
1466 assert_eq!(
1467 destination(codec, len as u64, limit, true) == Dest::TempFile,
1468 want == 1,
1469 "{codec} streamed at {limit}"
1470 );
1471 }
1472 assert_eq!(
1473 destination("compress", len as u64, 33_792, true),
1474 Dest::Memory
1475 );
1476 }
1477
1478 #[test]
1479 fn the_output_goes_to_memory_whenever_its_worst_case_fits() {
1480 assert_eq!(destination("gzip", 0, 2048, false), Dest::Memory);
1483 assert_eq!(destination("gzip", 0, 2047, false), Dest::TempFile);
1484 assert_eq!(destination("gzip", 8000, 2 * 10_024, false), Dest::Memory);
1486 assert_eq!(
1487 destination("gzip", 8000, 2 * 10_024 - 1, false),
1488 Dest::TempFile
1489 );
1490 assert_eq!(
1491 destination("gzip", u64::MAX, u64::MAX, false),
1492 Dest::TempFile
1493 );
1494 assert_eq!(destination("gzip", 8000, 10_024, true), Dest::Memory);
1496 assert_eq!(destination("gzip", 8000, 10_023, true), Dest::TempFile);
1497 assert_eq!(
1498 destination("gzip", u64::MAX, u64::MAX, true),
1499 Dest::TempFile
1500 );
1501 }
1502
1503 #[test]
1507 fn streamed_input_compresses_to_memory_when_the_output_fits() {
1508 let _lock = armed_lock();
1509 let s = Scratch::new();
1510 let (a, b) = (text(16 * 1024, 1), text(16 * 1024, 2));
1511 let paths = vec![s.file("a", &a), s.file("b", &b)];
1512 let files = load_input(&paths, 40_000).unwrap().0;
1516 assert!(matches!(files, Input::Files(_)));
1517 let memory = Input::Memory(vec![a, b]);
1518 for (mode, limit, want_temps) in [
1519 (Mode::PerFile, 40_000, 0),
1520 (Mode::OneStream, 40_000, 0),
1521 (Mode::OneStream, 37_888, 0),
1522 (Mode::OneStream, 37_887, 1),
1523 ] {
1524 let p = Plan {
1525 memory_limit: limit,
1526 ..plan(mode, 1)
1527 };
1528 let mut got = None;
1529 let made = temps_made(|| got = Some(run("gzip", &files, &p)));
1530 assert_eq!(made, want_temps, "{mode:?} at {limit}");
1531 let want = run("gzip", &memory, &plan(mode, 1)).bytes_out;
1532 assert_eq!(got.unwrap().bytes_out, want, "{mode:?}");
1533 }
1534 }
1535
1536 #[test]
1539 fn memory_input_past_the_output_limit_uses_the_temp_file() {
1540 let _lock = armed_lock();
1541 let input = Input::Memory(vec![text(16 * 1024, 5)]);
1542 let p = Plan {
1544 memory_limit: 32 * 1024,
1545 ..plan(Mode::OneStream, 1)
1546 };
1547 for codec in ["gzip", "compress"] {
1548 let made = temps_made(|| {
1549 run(codec, &input, &p);
1550 });
1551 assert_eq!(made, 1, "{codec}");
1552 }
1553 }
1554
1555 #[test]
1558 fn the_reserved_room_holds_incompressible_output() {
1559 let input = noise(64 * 1024);
1560 let reg = stuffr::registry();
1561 for name in crate::bench::levels::benchable_codecs() {
1562 let codec = reg.codec(stuffr::FormatId::new(name)).unwrap();
1563 let sweep = crate::bench::levels::levels_of(name).unwrap().sweep;
1564 let levels: Vec<Option<i32>> = if sweep.is_empty() {
1565 vec![None]
1566 } else {
1567 sweep.iter().map(|&l| Some(l)).collect()
1568 };
1569 for level in levels {
1570 let room = output_room(name, input.len() as u64).unwrap() as usize;
1571 let shared = SharedVec::with_capacity(room);
1572 let cap = shared.capacity();
1573 let dst = BufWriter::with_capacity(CHUNK, shared.clone());
1574 let opts = EncodeOpts {
1575 level,
1576 ..Default::default()
1577 };
1578 let mut sink = codec.encoder(Box::new(dst), &opts).unwrap();
1579 sink.write_all(&input).unwrap();
1580 sink.finish().unwrap();
1581 assert_eq!(shared.capacity(), cap, "{name} {level:?} reallocated");
1582 assert!(shared.take().len() <= room, "{name} {level:?}");
1583 }
1584 }
1585 }
1586
1587 #[test]
1589 fn a_file_that_grows_after_load_is_benched_at_its_loaded_length() {
1590 let _lock = armed_lock();
1591 let s = Scratch::new();
1592 let original = text(40 * 1024, 3);
1593 let path = s.file("grow.log", &original);
1594 let (files, bytes_in) = load_input(std::slice::from_ref(&path), 0).unwrap();
1595 assert!(matches!(files, Input::Files(_)));
1596 assert_eq!(bytes_in, original.len() as u64);
1597 let mut f = fs::OpenOptions::new().append(true).open(&path).unwrap();
1598 f.write_all(&text(10 * 1024, 9)).unwrap();
1599 drop(f);
1600 let snapshot = Input::Memory(vec![original]);
1601 for mode in [Mode::OneStream, Mode::PerFile] {
1602 let p = plan(mode, 1);
1603 for codec in ["gzip", "compress"] {
1604 let grown = run(codec, &files, &p);
1606 assert_eq!(
1607 grown.bytes_out,
1608 run(codec, &snapshot, &p).bytes_out,
1609 "{codec}: the appended bytes were benched"
1610 );
1611 }
1612 }
1613 }
1614
1615 #[test]
1616 fn load_input_splits_at_half_the_memory_limit() {
1617 let s = Scratch::new();
1618 let paths = vec![s.file("a", &[1; 100]), s.file("b", &[2; 100])];
1619 match load_input(&paths, 400).unwrap() {
1620 (Input::Memory(parts), 200) => {
1621 assert_eq!(parts, vec![vec![1; 100], vec![2; 100]])
1622 }
1623 other => panic!("200 bytes fit in 400 / 2: {other:?}"),
1624 }
1625 assert!(matches!(
1626 load_input(&paths, 399).unwrap(),
1627 (Input::Files(_), 200)
1628 ));
1629 }
1630
1631 #[cfg(unix)]
1633 struct Restore(PathBuf);
1634
1635 #[cfg(unix)]
1636 impl Drop for Restore {
1637 fn drop(&mut self) {
1638 use std::os::unix::fs::PermissionsExt;
1639 let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o600));
1640 }
1641 }
1642
1643 #[cfg(unix)]
1646 #[test]
1647 fn an_input_that_cannot_be_opened_is_a_usage_error_naming_it() {
1648 use std::os::unix::fs::PermissionsExt;
1649 let s = Scratch::new();
1650 let locked = s.file("locked.log", b"secret");
1651 let _restore = Restore(locked.clone());
1652 fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
1653 if File::open(&locked).is_ok() {
1655 return;
1656 }
1657 let want = format!("{}: cannot read it (", locked.display());
1658 let usage = |r: stuffr::Result<()>| match r {
1659 Err(Error::Usage(m)) => m,
1660 other => panic!("expected a usage error, got {other:?}"),
1661 };
1662 let paths = vec![locked.clone()];
1663 let m = usage(load_input(&paths, 1 << 30).map(drop));
1664 assert!(m.starts_with(&want), "in memory: {m}");
1665 let (files, _) = load_input(&paths, 0).unwrap();
1667 assert!(matches!(files, Input::Files(_)));
1668 let m = usage(warm(&files));
1669 assert!(m.starts_with(&want), "streamed: {m}");
1670 }
1671}