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