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