Skip to main content

hatchzip_core/archive/
storage.rs

1//! The archive's bytes, whether one file or a split set (`.001`, `.002`, ...),
2//! and the only code allowed to shrink them.
3
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, Read, Seek, SeekFrom};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
10use anyhow::{Context, Result, anyhow, bail};
11
12use crate::platform;
13
14#[derive(Clone, Debug)]
15pub struct Part {
16    pub path: PathBuf,
17    /// Where this part begins in the joined archive.
18    pub start: u64,
19    /// The part's length before extraction started.
20    pub len: u64,
21}
22
23/// Bytes from the end of the archive saved to a side file, served back at
24/// their original offsets once the real ones are truncated away.
25pub struct Tail {
26    pub start: u64,
27    pub bytes: Vec<u8>,
28}
29
30pub struct Storage {
31    parts: Arc<[Part]>,
32    /// The first part stays open and locked for the whole run, so two runs
33    /// can't eat the same archive.
34    first: File,
35    /// Set for an extraction that keeps the archive. Every method that
36    /// changes the archive's bytes refuses from then on, so a bug elsewhere
37    /// can't cost the user an archive they asked to keep.
38    whole: AtomicBool,
39    reads: Arc<Reads>,
40}
41
42/// How much of the archive its readers have read. Opening a compressed tar
43/// decodes all of it before anything else, which takes minutes for a large
44/// one, so front ends show this from another thread while an archive opens.
45#[derive(Debug, Default)]
46pub struct Reads {
47    pub done: AtomicU64,
48    /// How much the current pass reads in all: the archive's length, or
49    /// less when a resumed compressed tar is read from its resume point.
50    pub total: AtomicU64,
51}
52
53impl Reads {
54    pub fn reset(&self) {
55        self.done.store(0, Ordering::Relaxed);
56        self.total.store(0, Ordering::Relaxed);
57    }
58
59    /// The share of the pass read so far, if a pass is under way.
60    pub fn fraction(&self) -> Option<f64> {
61        let total = self.total.load(Ordering::Relaxed);
62        let done = self.done.load(Ordering::Relaxed);
63        (total > 0).then(|| (done as f64 / total as f64).min(1.0))
64    }
65}
66
67impl Storage {
68    /// Opens `path`, plus its sibling volumes if it is part of a split set.
69    pub fn open(path: &Path, writable: bool) -> Result<Self> {
70        let paths = volume_set(path)?;
71        let mut parts = Vec::with_capacity(paths.len());
72        let mut start = 0;
73        for p in paths {
74            let len = fs::metadata(&p)
75                .with_context(|| format!("reading {}", p.display()))?
76                .len();
77            parts.push(Part {
78                path: p,
79                start,
80                len,
81            });
82            start += len;
83        }
84        Self::with_parts(parts, writable)
85    }
86
87    /// Reopens a set whose original layout was recorded in the journal.
88    pub fn from_parts(recorded: &[(PathBuf, u64)], writable: bool) -> Result<Self> {
89        let mut parts = Vec::with_capacity(recorded.len());
90        let mut start = 0;
91        for (path, len) in recorded {
92            parts.push(Part {
93                path: path.clone(),
94                start,
95                len: *len,
96            });
97            start += len;
98        }
99        Self::with_parts(parts, writable)
100    }
101
102    fn with_parts(parts: Vec<Part>, writable: bool) -> Result<Self> {
103        // Extracting in place shrinks and deletes the volumes. Through a
104        // link, that would happen to whatever file it points to, which need
105        // not be an archive at all.
106        if writable {
107            for p in &parts {
108                if fs::symlink_metadata(&p.path).is_ok_and(|m| m.is_symlink()) {
109                    bail!(
110                        "{} is a link. HatchZip changes the archive file itself, so open the file \
111                         the link points to instead. Nothing was modified",
112                        p.path.display()
113                    );
114                }
115            }
116        }
117        let path = &parts[0].path;
118        let first = if writable {
119            platform::open_exclusive(path).map_err(|e| match e.kind() {
120                io::ErrorKind::WouldBlock => {
121                    anyhow!(
122                        "{} is in use by another program or HatchZip process",
123                        path.display()
124                    )
125                }
126                _ => anyhow!(e).context(format!(
127                    "opening {} for reading and writing",
128                    path.display()
129                )),
130            })?
131        } else {
132            File::open(path).with_context(|| format!("opening {}", path.display()))?
133        };
134        Ok(Self {
135            parts: parts.into(),
136            first,
137            whole: AtomicBool::new(false),
138            reads: Arc::default(),
139        })
140    }
141
142    /// From now on nothing may shrink, punch, write to or delete the
143    /// archive.
144    pub fn protect(&self) {
145        self.whole.store(true, Ordering::Relaxed);
146    }
147
148    pub fn protected(&self) -> bool {
149        self.whole.load(Ordering::Relaxed)
150    }
151
152    fn may_change(&self) -> Result<()> {
153        if self.protected() {
154            bail!(
155                "refusing to modify {}: this extraction keeps the archive",
156                self.primary().display()
157            );
158        }
159        Ok(())
160    }
161
162    pub fn primary(&self) -> &Path {
163        &self.parts[0].path
164    }
165
166    pub fn parts(&self) -> &[Part] {
167        &self.parts
168    }
169
170    pub fn record(&self) -> Vec<(PathBuf, u64)> {
171        self.parts.iter().map(|p| (p.path.clone(), p.len)).collect()
172    }
173
174    /// The archive's original length.
175    pub fn original_len(&self) -> u64 {
176        self.parts.last().map_or(0, |p| p.start + p.len)
177    }
178
179    /// How much of the archive is still on disk, checking that what is left
180    /// is an untouched prefix of the original.
181    pub fn current_len(&self) -> Result<u64> {
182        let mut end = 0;
183        for (i, p) in self.parts.iter().enumerate() {
184            let actual = match fs::metadata(&p.path) {
185                Ok(m) => m.len(),
186                Err(e) if e.kind() == io::ErrorKind::NotFound && i > 0 => 0,
187                Err(e) => return Err(e).with_context(|| format!("reading {}", p.path.display())),
188            };
189            if actual > p.len {
190                bail!(
191                    "{} has grown since extraction started and will not be modified",
192                    p.path.display()
193                );
194            }
195            if actual == 0 && i > 0 {
196                break;
197            }
198            if end != p.start {
199                bail!(
200                    "{} is missing a piece before {}",
201                    self.primary().display(),
202                    p.path.display()
203                );
204            }
205            end = p.start + actual;
206            if actual < p.len {
207                break;
208            }
209        }
210        Ok(end)
211    }
212
213    /// Shrinks the archive to its first `len` bytes: whole volumes past that
214    /// point are deleted, the one it falls in is truncated.
215    pub fn set_len(&self, len: u64) -> Result<()> {
216        self.may_change()?;
217        for (i, p) in self.parts.iter().enumerate().rev() {
218            if p.start + p.len <= len {
219                break;
220            }
221            if i == 0 {
222                self.first.set_len(len)?;
223            } else if p.start >= len {
224                match fs::remove_file(&p.path) {
225                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
226                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
227                    }
228                    _ => {}
229                }
230            } else {
231                let f = OpenOptions::new().write(true).open(&p.path)?;
232                if f.metadata()?.len() > len - p.start {
233                    f.set_len(len - p.start)?;
234                }
235            }
236        }
237        Ok(())
238    }
239
240    /// Gives back the disk space of the bytes in `[from, to)` while every
241    /// offset stays where it was; they read as zeros afterwards. Returns
242    /// false if the filesystem can't. Filesystems free whole blocks only, so
243    /// up to a block at each end may stay allocated until truncation.
244    pub fn punch(&self, from: u64, to: u64) -> Result<bool> {
245        self.may_change()?;
246        for (i, p) in self.parts.iter().enumerate() {
247            let (start, end) = (from.max(p.start), to.min(p.start + p.len));
248            if start >= end {
249                continue;
250            }
251            let (offset, len) = (start - p.start, end - start);
252            let punched = if i == 0 {
253                platform::punch_hole(&self.first, offset, len)
254            } else {
255                OpenOptions::new()
256                    .write(true)
257                    .open(&p.path)
258                    .and_then(|f| platform::punch_hole(&f, offset, len))
259            };
260            if !punched.with_context(|| format!("freeing space in {}", p.path.display()))? {
261                return Ok(false);
262            }
263        }
264        Ok(true)
265    }
266
267    /// Like [`set_len`](Self::set_len), but also cuts volumes that grew past
268    /// their original length. Only for undoing an interrupted restore, which
269    /// is the one thing that appends to an archive: the volume it appended to
270    /// may have been whole, and `set_len` never touches whole volumes.
271    pub fn cut_to(&self, len: u64) -> Result<()> {
272        self.may_change()?;
273        for (i, p) in self.parts.iter().enumerate().rev() {
274            let keep = len.saturating_sub(p.start).min(p.len);
275            if i > 0 && keep == 0 {
276                match fs::remove_file(&p.path) {
277                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
278                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
279                    }
280                    _ => {}
281                }
282                continue;
283            }
284            let shrink = |f: &File| -> io::Result<()> {
285                if f.metadata()?.len() > keep {
286                    f.set_len(keep)?;
287                    f.sync_all()?;
288                }
289                Ok(())
290            };
291            let done = if i == 0 {
292                shrink(&self.first)
293            } else {
294                match OpenOptions::new().write(true).open(&p.path) {
295                    Ok(f) => shrink(&f),
296                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
297                    Err(e) => Err(e),
298                }
299            };
300            done.with_context(|| format!("shortening {}", p.path.display()))?;
301        }
302        Ok(())
303    }
304
305    /// Writes `bytes` at `offset` of the joined archive and flushes them to
306    /// disk. Bytes inside the archive go to the volume that holds them; bytes
307    /// past its current end go to the last volume still there, which grows.
308    pub fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
309        self.may_change()?;
310        let end = self.current_len()?;
311        if offset > end {
312            bail!(
313                "{} is shorter than expected; refusing to write past its end",
314                self.primary().display()
315            );
316        }
317        let last = self.parts.partition_point(|p| p.start < end).max(1) - 1;
318        let mut at = offset;
319        let mut rest = bytes;
320        while !rest.is_empty() {
321            let i = if at >= end {
322                last
323            } else {
324                self.parts.partition_point(|p| p.start <= at) - 1
325            };
326            let p = &self.parts[i];
327            let room = if i == last {
328                rest.len()
329            } else {
330                ((p.start + p.len - at) as usize).min(rest.len())
331            };
332            let (now, later) = rest.split_at(room);
333            self.write_part(i, at - p.start, now)
334                .with_context(|| format!("writing to {}", p.path.display()))?;
335            at += room as u64;
336            rest = later;
337        }
338        Ok(())
339    }
340
341    fn write_part(&self, i: usize, at: u64, bytes: &[u8]) -> io::Result<()> {
342        let write = |mut f: &File| -> io::Result<()> {
343            f.seek(SeekFrom::Start(at))?;
344            io::Write::write_all(&mut f, bytes)?;
345            f.sync_all()
346        };
347        if i == 0 {
348            // On Windows the locked handle is the only one allowed to write.
349            write(&self.first)
350        } else {
351            write(&OpenOptions::new().write(true).open(&self.parts[i].path)?)
352        }
353    }
354
355    /// Deletes whatever is left of every part.
356    pub fn remove(self) -> Result<()> {
357        self.may_change()?;
358        let Self { parts, first, .. } = self;
359        drop(first);
360        for p in parts.iter() {
361            match fs::remove_file(&p.path) {
362                Err(e) if e.kind() != io::ErrorKind::NotFound => {
363                    return Err(e).with_context(|| format!("deleting {}", p.path.display()));
364                }
365                _ => {}
366            }
367        }
368        Ok(())
369    }
370
371    pub fn reader(&self, tail: Option<Arc<Tail>>) -> Reader {
372        Reader {
373            parts: self.parts.clone(),
374            open: None,
375            tail,
376            len: self.original_len(),
377            pos: 0,
378            reads: self.reads.clone(),
379        }
380    }
381
382    /// Counts what every reader made from now on reads into `reads`, a pass
383    /// over the whole archive by default.
384    pub fn count_reads(&mut self, reads: Arc<Reads>) {
385        reads.done.store(0, Ordering::Relaxed);
386        reads.total.store(self.original_len(), Ordering::Relaxed);
387        self.reads = reads;
388    }
389
390    /// Starts the count over for a pass that reads `total` bytes.
391    pub fn expect_reads(&self, total: u64) {
392        self.reads.done.store(0, Ordering::Relaxed);
393        self.reads.total.store(total, Ordering::Relaxed);
394    }
395}
396
397/// The path of the first volume, if `path` names any volume of a split set.
398pub fn first_volume(path: &Path) -> PathBuf {
399    if let Some(rar) = rar_volume(path) {
400        return rar.first();
401    }
402    match split_suffix(path) {
403        Some((base, width, _)) => numbered(&base, width, 1),
404        None => path.to_path_buf(),
405    }
406}
407
408/// The path volume `index` of the archive whose first volume is `primary`
409/// has, whether or not it exists. `None` past the only volume of an archive
410/// that is not split.
411pub fn volume_path(primary: &Path, index: usize) -> Option<PathBuf> {
412    if index == 0 {
413        return Some(primary.to_path_buf());
414    }
415    if let Some(rar) = rar_naming(primary) {
416        return rar.volume(index);
417    }
418    match split_suffix(primary) {
419        Some((base, width, _)) => Some(numbered(&base, width, index as u64 + 1)),
420        None => (index == 0).then(|| primary.to_path_buf()),
421    }
422}
423
424fn volume_set(path: &Path) -> Result<Vec<PathBuf>> {
425    if let Some(rar) = rar_volume(path) {
426        if rar.index != 0 {
427            bail!(
428                "{} is not the first volume. Open {} instead",
429                path.display(),
430                rar.first().display()
431            );
432        }
433        let mut volumes = vec![path.to_path_buf()];
434        while let Some(next) = rar.volume(volumes.len()).filter(|p| p.exists()) {
435            volumes.push(next);
436        }
437        return Ok(volumes);
438    }
439    let Some((base, width, n)) = split_suffix(path) else {
440        return Ok(vec![path.to_path_buf()]);
441    };
442    if n != 1 {
443        bail!(
444            "{} is not the first part. Open {} instead",
445            path.display(),
446            numbered(&base, width, 1).display()
447        );
448    }
449    let mut parts = vec![path.to_path_buf()];
450    loop {
451        let next = numbered(&base, width, parts.len() as u64 + 1);
452        if !next.exists() {
453            return Ok(parts);
454        }
455        parts.push(next);
456    }
457}
458
459/// `game.7z.001` is `("game.7z", 3, 1)`. Only names with a real extension
460/// before the number count, so a file that just happens to end in digits
461/// isn't mistaken for a volume.
462fn split_suffix(path: &Path) -> Option<(PathBuf, usize, u64)> {
463    let name = path.file_name()?.to_str()?;
464    let (stem, digits) = name.rsplit_once('.')?;
465    if digits.len() < 3 || !digits.bytes().all(|b| b.is_ascii_digit()) || !stem.contains('.') {
466        return None;
467    }
468    Some((
469        path.with_file_name(stem),
470        digits.len(),
471        digits.parse().ok()?,
472    ))
473}
474
475fn numbered(base: &Path, width: usize, n: u64) -> PathBuf {
476    let mut s = base.as_os_str().to_owned();
477    s.push(format!(".{n:0width$}"));
478    PathBuf::from(s)
479}
480
481/// Reads the joined archive. Parts or regions that were already truncated
482/// away read as zeros: format parsers scan backwards over them looking for
483/// end records, and zeros never match a signature.
484pub struct Reader {
485    parts: Arc<[Part]>,
486    open: Option<(usize, File)>,
487    tail: Option<Arc<Tail>>,
488    len: u64,
489    pos: u64,
490    reads: Arc<Reads>,
491}
492
493impl Read for Reader {
494    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
495        let n = self.read_at_pos(buf)?;
496        self.reads.done.fetch_add(n as u64, Ordering::Relaxed);
497        Ok(n)
498    }
499}
500
501impl Reader {
502    fn read_at_pos(&mut self, buf: &mut [u8]) -> io::Result<usize> {
503        if self.pos >= self.len || buf.is_empty() {
504            return Ok(0);
505        }
506        let live_end = match &self.tail {
507            Some(t) if self.pos >= t.start => {
508                let at = (self.pos - t.start) as usize;
509                let src = t.bytes.get(at..).unwrap_or(&[]);
510                let n = src.len().min(buf.len());
511                buf[..n].copy_from_slice(&src[..n]);
512                self.pos += n as u64;
513                return Ok(n);
514            }
515            Some(t) => t.start,
516            None => self.len,
517        };
518        let i = self.parts.partition_point(|p| p.start <= self.pos) - 1;
519        let part = &self.parts[i];
520        let room = (part.start + part.len).min(live_end) - self.pos;
521        let room = room.min(buf.len() as u64) as usize;
522        if self.open.as_ref().is_none_or(|(j, _)| *j != i) {
523            self.open = File::open(&part.path).ok().map(|f| (i, f));
524        }
525        let n = match &mut self.open {
526            Some((_, f)) => {
527                f.seek(SeekFrom::Start(self.pos - part.start))?;
528                f.read(&mut buf[..room])?
529            }
530            None => 0,
531        };
532        let n = if n == 0 {
533            buf[..room].fill(0);
534            room
535        } else {
536            n
537        };
538        self.pos += n as u64;
539        Ok(n)
540    }
541}
542
543impl Seek for Reader {
544    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
545        let pos = match to {
546            SeekFrom::Start(p) => Some(p),
547            SeekFrom::End(d) => self.len.checked_add_signed(d),
548            SeekFrom::Current(d) => self.pos.checked_add_signed(d),
549        };
550        self.pos = pos.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "bad seek"))?;
551        Ok(self.pos)
552    }
553}
554
555/// How the volumes of a RAR set are named, and which one a path is.
556struct RarSet {
557    /// The path without the part of the name that changes.
558    stem: PathBuf,
559    style: RarStyle,
560    /// 0 for the first volume.
561    index: usize,
562    /// Upper case extensions stay upper case.
563    upper: bool,
564}
565
566enum RarStyle {
567    /// `name.part1.rar`, `name.part01.rar`: the number's width is kept.
568    Part { width: usize },
569    /// `name.rar`, `name.r00`, `name.r01`, ..., `name.r99`, `name.s00`, ...
570    Old,
571}
572
573impl RarSet {
574    fn first(&self) -> PathBuf {
575        self.volume(0).expect("the first volume always has a name")
576    }
577
578    /// `None` past `name.z99`, the last name the old style has.
579    fn volume(&self, index: usize) -> Option<PathBuf> {
580        let mut name = self.stem.as_os_str().to_owned();
581        let case = |s: String| if self.upper { s.to_uppercase() } else { s };
582        match self.style {
583            RarStyle::Part { width } => {
584                name.push(case(format!(".part{:0width$}.rar", index.checked_add(1)?)));
585            }
586            RarStyle::Old if index == 0 => name.push(case(".rar".into())),
587            RarStyle::Old => {
588                let n = index - 1;
589                let letter = u8::try_from(n / 100)
590                    .ok()
591                    .and_then(|l| b'r'.checked_add(l))
592                    .filter(|l| *l <= b'z')?;
593                name.push(case(format!(".{}{:02}", letter as char, n % 100)));
594            }
595        }
596        Some(PathBuf::from(name))
597    }
598
599    fn has_volume(&self, index: usize) -> bool {
600        self.volume(index).is_some_and(|p| p.exists())
601    }
602}
603
604/// Recognises a volume of a RAR set by its name. A bare `name.rar` counts
605/// only if `name.r00` sits next to it, so a single RAR file is not a set.
606fn rar_volume(path: &Path) -> Option<RarSet> {
607    let set = rar_naming(path)?;
608    if matches!(set.style, RarStyle::Old) && set.index == 0 && !set.has_volume(1) {
609        return None;
610    }
611    Some(set)
612}
613
614/// [`rar_volume`] by the name alone: a bare `name.rar` is the first volume
615/// of a set whether or not `name.r00` is there, as it may already be gone.
616fn rar_naming(path: &Path) -> Option<RarSet> {
617    let name = path.file_name()?.to_str()?;
618    let lower = name.to_ascii_lowercase();
619    let upper = name.chars().rev().take(3).all(|c| !c.is_ascii_lowercase());
620    let (stem_len, ext) = lower.rsplit_once('.').map(|(s, e)| (s.len(), e))?;
621    let stem = &name[..stem_len];
622    if ext == "rar" {
623        if let Some((before, digits)) = stem.to_ascii_lowercase().rsplit_once(".part")
624            && !digits.is_empty()
625            && digits.bytes().all(|b| b.is_ascii_digit())
626        {
627            let n: usize = digits.parse().ok()?;
628            return Some(RarSet {
629                stem: path.with_file_name(&name[..before.len()]),
630                style: RarStyle::Part {
631                    width: digits.len(),
632                },
633                index: n.checked_sub(1)?,
634                upper,
635            });
636        }
637        return Some(RarSet {
638            stem: path.with_file_name(stem),
639            style: RarStyle::Old,
640            index: 0,
641            upper,
642        });
643    }
644    let bytes = ext.as_bytes();
645    if bytes.len() == 3
646        && (b'r'..=b'z').contains(&bytes[0])
647        && bytes[1].is_ascii_digit()
648        && bytes[2].is_ascii_digit()
649    {
650        let n = usize::from(bytes[0] - b'r') * 100
651            + usize::from(bytes[1] - b'0') * 10
652            + usize::from(bytes[2] - b'0');
653        let set = RarSet {
654            stem: path.with_file_name(stem),
655            style: RarStyle::Old,
656            index: n + 1,
657            upper,
658        };
659        // Other formats number their volumes the same way (`.z01` for a
660        // split ZIP), so it is a RAR volume only next to its first one.
661        return set.has_volume(0).then_some(set);
662    }
663    None
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    /// The letter of `.r00` counts up to `z`; a set that needs more names is
671    /// not followed past `.z99`, where the letter would leave the alphabet.
672    #[test]
673    fn old_style_rar_volume_names_end_at_z99() {
674        let set = RarSet {
675            stem: PathBuf::from("set"),
676            style: RarStyle::Old,
677            index: 0,
678            upper: false,
679        };
680        let name = |i| set.volume(i).map(|p| p.to_string_lossy().into_owned());
681        assert_eq!(name(0).as_deref(), Some("set.rar"));
682        assert_eq!(name(1).as_deref(), Some("set.r00"));
683        assert_eq!(name(101).as_deref(), Some("set.s00"));
684        assert_eq!(name(900).as_deref(), Some("set.z99"));
685        assert_eq!(name(901), None);
686        assert_eq!(name(14_301), None);
687    }
688
689    /// What front ends show while an archive opens: every reader counts, a
690    /// split set is one pass, and a pass can start part way in.
691    #[test]
692    fn reads_are_counted_across_volumes() {
693        let dir = std::env::temp_dir().join(format!("hatchzip-reads-{}", std::process::id()));
694        fs::create_dir_all(&dir).unwrap();
695        fs::write(dir.join("game.7z.001"), vec![1u8; 3000]).unwrap();
696        fs::write(dir.join("game.7z.002"), vec![2u8; 1000]).unwrap();
697
698        let mut storage = Storage::open(&dir.join("game.7z.001"), false).unwrap();
699        let reads = Arc::new(Reads::default());
700        storage.count_reads(reads.clone());
701        assert_eq!(reads.fraction(), Some(0.0));
702
703        let mut half = vec![0; 2000];
704        storage.reader(None).read_exact(&mut half).unwrap();
705        assert_eq!(reads.fraction(), Some(0.5));
706        let mut rest = Vec::new();
707        let mut r = storage.reader(None);
708        r.seek(SeekFrom::Start(2000)).unwrap();
709        r.read_to_end(&mut rest).unwrap();
710        assert_eq!(reads.fraction(), Some(1.0));
711
712        // A resumed pass that starts at byte 3000 has 1000 bytes to read.
713        storage.expect_reads(1000);
714        let mut last = vec![0; 500];
715        r.seek(SeekFrom::Start(3000)).unwrap();
716        r.read_exact(&mut last).unwrap();
717        assert_eq!(reads.fraction(), Some(0.5));
718
719        reads.reset();
720        assert_eq!(reads.fraction(), None);
721        drop(storage);
722        fs::remove_dir_all(&dir).unwrap();
723    }
724}