Skip to main content

hatchzip_core/archive/
storage.rs

1//! The archive's bytes, whether one file or a split set (`.001`, `.002`, ...,
2//! RAR volumes, or a native split ZIP's `.z01`, ..., `.zip`), and the only
3//! code allowed to shrink them.
4
5use std::fs::{self, File, OpenOptions};
6use std::io::{self, Read, Seek, SeekFrom};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10
11use anyhow::{Context, Result, anyhow, bail};
12
13use crate::platform;
14
15#[derive(Clone, Debug)]
16pub struct Part {
17    pub path: PathBuf,
18    /// Where this part begins in the joined archive.
19    pub start: u64,
20    /// The part's length before extraction started.
21    pub len: u64,
22}
23
24/// Bytes from the end of the archive saved to a side file, served back at
25/// their original offsets once the real ones are truncated away.
26pub struct Tail {
27    pub start: u64,
28    pub bytes: Vec<u8>,
29}
30
31pub struct Storage {
32    parts: Arc<[Part]>,
33    /// The first part stays open and locked for the whole run, so two runs
34    /// can't eat the same archive.
35    first: File,
36    /// Set for an extraction that keeps the archive. Every method that
37    /// changes the archive's bytes refuses from then on, so a bug elsewhere
38    /// can't cost the user an archive they asked to keep.
39    whole: AtomicBool,
40    reads: Arc<Reads>,
41    sfv_checked: AtomicBool,
42}
43
44/// How much of the archive its readers have read. Opening a compressed tar
45/// decodes all of it before anything else, which takes minutes for a large
46/// one, so front ends show this from another thread while an archive opens.
47#[derive(Debug, Default)]
48pub struct Reads {
49    pub done: AtomicU64,
50    /// How much the current pass reads in all: the archive's length, or
51    /// less when a resumed compressed tar is read from its resume point.
52    pub total: AtomicU64,
53}
54
55impl Reads {
56    pub fn reset(&self) {
57        self.done.store(0, Ordering::Relaxed);
58        self.total.store(0, Ordering::Relaxed);
59    }
60
61    /// The share of the pass read so far, if a pass is under way.
62    pub fn fraction(&self) -> Option<f64> {
63        let total = self.total.load(Ordering::Relaxed);
64        let done = self.done.load(Ordering::Relaxed);
65        (total > 0).then(|| (done as f64 / total as f64).min(1.0))
66    }
67}
68
69impl Storage {
70    /// Opens `path`, plus its sibling volumes if it is part of a split set.
71    pub fn open(path: &Path, writable: bool) -> Result<Self> {
72        let paths = volume_set(path)?;
73        let mut parts = Vec::with_capacity(paths.len());
74        let mut start = 0;
75        for p in paths {
76            let len = fs::metadata(&p)
77                .with_context(|| format!("reading {}", p.display()))?
78                .len();
79            parts.push(Part {
80                path: p,
81                start,
82                len,
83            });
84            start += len;
85        }
86        Self::with_parts(parts, writable)
87    }
88
89    /// Reopens a set whose original layout was recorded in the journal.
90    pub fn from_parts(recorded: &[(PathBuf, u64)], writable: bool) -> Result<Self> {
91        let mut parts = Vec::with_capacity(recorded.len());
92        let mut start = 0;
93        for (path, len) in recorded {
94            parts.push(Part {
95                path: path.clone(),
96                start,
97                len: *len,
98            });
99            start += len;
100        }
101        Self::with_parts(parts, writable)
102    }
103
104    fn with_parts(parts: Vec<Part>, writable: bool) -> Result<Self> {
105        // Extracting in place shrinks and deletes the volumes. Through a
106        // link, that would happen to whatever file it points to, which need
107        // not be an archive at all.
108        if writable {
109            for p in &parts {
110                if fs::symlink_metadata(&p.path).is_ok_and(|m| m.is_symlink()) {
111                    bail!(
112                        "{} is a link. HatchZip changes the archive file itself, so open the file \
113                         the link points to instead. Nothing was modified",
114                        p.path.display()
115                    );
116                }
117            }
118        }
119        let path = &parts[0].path;
120        let first = if writable {
121            platform::open_exclusive(path).map_err(|e| match e.kind() {
122                io::ErrorKind::WouldBlock => {
123                    anyhow!(
124                        "{} is in use by another program or HatchZip process",
125                        path.display()
126                    )
127                }
128                _ => anyhow!(e).context(format!(
129                    "opening {} for reading and writing",
130                    path.display()
131                )),
132            })?
133        } else {
134            File::open(path).with_context(|| format!("opening {}", path.display()))?
135        };
136        Ok(Self {
137            parts: parts.into(),
138            first,
139            whole: AtomicBool::new(false),
140            reads: Arc::default(),
141            sfv_checked: AtomicBool::new(false),
142        })
143    }
144
145    /// Whether this storage has already been verified against an .sfv file.
146    pub fn sfv_checked(&self) -> bool {
147        self.sfv_checked.load(Ordering::Relaxed)
148    }
149
150    pub fn mark_sfv_checked(&self) {
151        self.sfv_checked.store(true, Ordering::Relaxed);
152    }
153
154    /// From now on nothing may shrink, punch, write to or delete the
155    /// archive.
156    pub fn protect(&self) {
157        self.whole.store(true, Ordering::Relaxed);
158    }
159
160    pub fn protected(&self) -> bool {
161        self.whole.load(Ordering::Relaxed)
162    }
163
164    fn may_change(&self) -> Result<()> {
165        if self.protected() {
166            bail!(
167                "refusing to modify {}: this extraction keeps the archive",
168                self.primary().display()
169            );
170        }
171        Ok(())
172    }
173
174    /// The first volume that has another name, if any. Shrinking a file
175    /// shrinks it under every name it has, so extracting in place would
176    /// empty a hard link that may be the only copy someone meant to keep.
177    pub fn hard_linked(&self) -> Option<&Path> {
178        self.parts
179            .iter()
180            .find(|p| platform::link_count(&p.path).is_ok_and(|n| n > 1))
181            .map(|p| p.path.as_path())
182    }
183
184    pub fn primary(&self) -> &Path {
185        &self.parts[0].path
186    }
187
188    pub fn parts(&self) -> &[Part] {
189        &self.parts
190    }
191
192    pub fn record(&self) -> Vec<(PathBuf, u64)> {
193        self.parts.iter().map(|p| (p.path.clone(), p.len)).collect()
194    }
195
196    /// The archive's original length.
197    pub fn original_len(&self) -> u64 {
198        self.parts.last().map_or(0, |p| p.start + p.len)
199    }
200
201    /// How much of the archive is still on disk, checking that what is left
202    /// is an untouched prefix of the original.
203    pub fn current_len(&self) -> Result<u64> {
204        let mut end = 0;
205        for (i, p) in self.parts.iter().enumerate() {
206            let actual = match fs::metadata(&p.path) {
207                Ok(m) => m.len(),
208                Err(e) if e.kind() == io::ErrorKind::NotFound && i > 0 => 0,
209                Err(e) => return Err(e).with_context(|| format!("reading {}", p.path.display())),
210            };
211            if actual > p.len {
212                bail!(
213                    "{} has grown since extraction started and will not be modified",
214                    p.path.display()
215                );
216            }
217            if actual == 0 && i > 0 {
218                break;
219            }
220            if end != p.start {
221                bail!(
222                    "{} is missing a piece before {}",
223                    self.primary().display(),
224                    p.path.display()
225                );
226            }
227            end = p.start + actual;
228            if actual < p.len {
229                break;
230            }
231        }
232        Ok(end)
233    }
234
235    /// Shrinks the archive to its first `len` bytes: whole volumes past that
236    /// point are deleted, the one it falls in is truncated.
237    pub fn set_len(&self, len: u64) -> Result<()> {
238        self.may_change()?;
239        for (i, p) in self.parts.iter().enumerate().rev() {
240            if p.start + p.len <= len {
241                break;
242            }
243            if i == 0 {
244                platform::set_len_now(&self.first, len)?;
245            } else if p.start >= len {
246                match fs::remove_file(&p.path) {
247                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
248                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
249                    }
250                    _ => {}
251                }
252            } else {
253                let f = OpenOptions::new().write(true).open(&p.path)?;
254                if f.metadata()?.len() > len - p.start {
255                    platform::set_len_now(&f, len - p.start)?;
256                }
257            }
258        }
259        Ok(())
260    }
261
262    /// Gives back the disk space of the bytes in `[from, to)` while every
263    /// offset stays where it was; they read as zeros afterwards. Returns
264    /// false if the filesystem can't. Filesystems free whole blocks only, so
265    /// up to a block at each end may stay allocated until truncation.
266    pub fn punch(&self, from: u64, to: u64) -> Result<bool> {
267        self.may_change()?;
268        for (i, p) in self.parts.iter().enumerate() {
269            let (start, end) = (from.max(p.start), to.min(p.start + p.len));
270            if start >= end {
271                continue;
272            }
273            let (offset, len) = (start - p.start, end - start);
274            let punched = if i == 0 {
275                platform::punch_hole(&self.first, offset, len)
276            } else {
277                OpenOptions::new()
278                    .write(true)
279                    .open(&p.path)
280                    .and_then(|f| platform::punch_hole(&f, offset, len))
281            };
282            if !punched.with_context(|| format!("freeing space in {}", p.path.display()))? {
283                return Ok(false);
284            }
285        }
286        Ok(true)
287    }
288
289    /// Like [`set_len`](Self::set_len), but also cuts volumes that grew past
290    /// their original length. Only for undoing an interrupted restore, which
291    /// is the one thing that appends to an archive: the volume it appended to
292    /// may have been whole, and `set_len` never touches whole volumes.
293    pub fn cut_to(&self, len: u64) -> Result<()> {
294        self.may_change()?;
295        for (i, p) in self.parts.iter().enumerate().rev() {
296            let keep = len.saturating_sub(p.start).min(p.len);
297            if i > 0 && keep == 0 {
298                match fs::remove_file(&p.path) {
299                    Err(e) if e.kind() != io::ErrorKind::NotFound => {
300                        return Err(e).with_context(|| format!("deleting {}", p.path.display()));
301                    }
302                    _ => {}
303                }
304                continue;
305            }
306            let shrink = |f: &File| -> io::Result<()> {
307                if f.metadata()?.len() > keep {
308                    platform::set_len_now(f, keep)?;
309                    f.sync_all()?;
310                }
311                Ok(())
312            };
313            let done = if i == 0 {
314                shrink(&self.first)
315            } else {
316                match OpenOptions::new().write(true).open(&p.path) {
317                    Ok(f) => shrink(&f),
318                    Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
319                    Err(e) => Err(e),
320                }
321            };
322            done.with_context(|| format!("shortening {}", p.path.display()))?;
323        }
324        Ok(())
325    }
326
327    /// Writes `bytes` at `offset` of the joined archive and flushes them to
328    /// disk. Bytes inside the archive go to the volume that holds them; bytes
329    /// past its current end go to the last volume still there, which grows.
330    pub fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
331        self.may_change()?;
332        let end = self.current_len()?;
333        if offset > end {
334            bail!(
335                "{} is shorter than expected; refusing to write past its end",
336                self.primary().display()
337            );
338        }
339        let last = self.parts.partition_point(|p| p.start < end).max(1) - 1;
340        let mut at = offset;
341        let mut rest = bytes;
342        while !rest.is_empty() {
343            let i = if at >= end {
344                last
345            } else {
346                self.parts.partition_point(|p| p.start <= at) - 1
347            };
348            let p = &self.parts[i];
349            let room = if i == last {
350                rest.len()
351            } else {
352                ((p.start + p.len - at) as usize).min(rest.len())
353            };
354            let (now, later) = rest.split_at(room);
355            self.write_part(i, at - p.start, now)
356                .with_context(|| format!("writing to {}", p.path.display()))?;
357            at += room as u64;
358            rest = later;
359        }
360        Ok(())
361    }
362
363    fn write_part(&self, i: usize, at: u64, bytes: &[u8]) -> io::Result<()> {
364        let write = |mut f: &File| -> io::Result<()> {
365            f.seek(SeekFrom::Start(at))?;
366            io::Write::write_all(&mut f, bytes)?;
367            f.sync_all()
368        };
369        if i == 0 {
370            // On Windows the locked handle is the only one allowed to write.
371            write(&self.first)
372        } else {
373            write(&OpenOptions::new().write(true).open(&self.parts[i].path)?)
374        }
375    }
376
377    /// Deletes whatever is left of every part.
378    pub fn remove(self) -> Result<()> {
379        self.may_change()?;
380        let Self { parts, first, .. } = self;
381        drop(first);
382        for p in parts.iter() {
383            match fs::remove_file(&p.path) {
384                Err(e) if e.kind() != io::ErrorKind::NotFound => {
385                    return Err(e).with_context(|| format!("deleting {}", p.path.display()));
386                }
387                _ => {}
388            }
389        }
390        Ok(())
391    }
392
393    /// A reader of the joined archive. With a tail, the archive ends where
394    /// the tail does: a split ZIP's index is served rewritten, and can be
395    /// shorter or longer than the bytes it stands for. Every other tail ends
396    /// exactly at the archive's original end.
397    pub fn reader(&self, tail: Option<Arc<Tail>>) -> Reader {
398        let len = tail
399            .as_ref()
400            .map_or(self.original_len(), |t| t.start + t.bytes.len() as u64);
401        Reader {
402            parts: self.parts.clone(),
403            open: None,
404            tail,
405            len,
406            pos: 0,
407            reads: self.reads.clone(),
408        }
409    }
410
411    /// Counts what every reader made from now on reads into `reads`, a pass
412    /// over the whole archive by default.
413    pub fn count_reads(&mut self, reads: Arc<Reads>) {
414        reads.done.store(0, Ordering::Relaxed);
415        reads.total.store(self.original_len(), Ordering::Relaxed);
416        self.reads = reads;
417    }
418
419    /// Shares the byte counter used by archive reads with another reader.
420    pub fn reads(&self) -> Arc<Reads> {
421        self.reads.clone()
422    }
423
424    /// Starts the count over for a pass that reads `total` bytes.
425    pub fn expect_reads(&self, total: u64) {
426        self.reads.done.store(0, Ordering::Relaxed);
427        self.reads.total.store(total, Ordering::Relaxed);
428    }
429}
430
431/// The path of the first volume, if `path` names any volume of a split set.
432pub fn first_volume(path: &Path) -> PathBuf {
433    if let Some(rar) = rar_volume(path) {
434        return rar.first();
435    }
436    if let Some(zip) = zip_volume(path) {
437        return zip.segment(0);
438    }
439    match split_suffix(path) {
440        Some((base, width, _)) => numbered(&base, width, 1),
441        None => path.to_path_buf(),
442    }
443}
444
445/// The path volume `index` of the archive whose first volume is `primary`
446/// has, whether or not it exists. `None` past the only volume of an archive
447/// that is not split.
448pub fn volume_path(primary: &Path, index: usize) -> Option<PathBuf> {
449    if index == 0 {
450        return Some(primary.to_path_buf());
451    }
452    if let Some(rar) = rar_naming(primary) {
453        return rar.volume(index);
454    }
455    match split_suffix(primary) {
456        Some((base, width, _)) => Some(numbered(&base, width, index as u64 + 1)),
457        None => (index == 0).then(|| primary.to_path_buf()),
458    }
459}
460
461/// [`volume_path`] for a set of `count` volumes. Only a native split ZIP
462/// needs the count: its last segment is `<stem>.zip`, not the next number.
463/// A set of one is never split, whatever its name: an earlier build may have
464/// extracted a lone `data.z01` as the one file it is.
465pub fn volume_path_in(primary: &Path, index: usize, count: usize) -> Option<PathBuf> {
466    if count > 1
467        && let Some(zip) = split_zip_naming(primary)
468    {
469        return Some(if index + 1 == count {
470            zip.last()
471        } else {
472            zip.segment(index)
473        });
474    }
475    volume_path(primary, index)
476}
477
478/// Whether `primary` is the first segment of a native split ZIP by its name,
479/// `<stem>.z01`.
480pub fn is_split_zip(primary: &Path) -> bool {
481    split_zip_naming(primary).is_some()
482}
483
484/// Segment `disk` of the native split ZIP whose first segment is `primary`
485/// (`.z01` is disk 0), counting from `.z01` up and never `.zip`.
486pub fn split_zip_segment(primary: &Path, disk: usize) -> Option<PathBuf> {
487    split_zip_naming(primary).map(|z| z.segment(disk))
488}
489
490/// The last segment, `<stem>.zip`, of the native split ZIP whose first
491/// segment is `primary`.
492pub fn split_zip_last(primary: &Path) -> Option<PathBuf> {
493    split_zip_naming(primary).map(|z| z.last())
494}
495
496fn split_zip_naming(primary: &Path) -> Option<ZipSet> {
497    if rar_naming(primary).is_some() {
498        return None;
499    }
500    zip_naming(primary).filter(|z| z.disk == Some(0))
501}
502
503fn volume_set(path: &Path) -> Result<Vec<PathBuf>> {
504    if rar_volume(path).is_none()
505        && let Some(zip) = zip_volume(path)
506    {
507        if zip.disk != Some(0) {
508            bail!(
509                "{} is not the first part of a split ZIP. Open {} instead",
510                path.display(),
511                zip.segment(0).display()
512            );
513        }
514        let mut parts = vec![path.to_path_buf()];
515        while zip.segment(parts.len()).exists() {
516            parts.push(zip.segment(parts.len()));
517        }
518        let last = zip.last();
519        if !last.exists() {
520            bail!(
521                "{} is missing. It is the last part of this split ZIP and holds its index, so put \
522                 it next to {} and try again. Nothing was modified",
523                last.display(),
524                path.display()
525            );
526        }
527        parts.push(last);
528        return Ok(parts);
529    }
530    if let Some(rar) = rar_volume(path) {
531        if rar.index != 0 {
532            bail!(
533                "{} is not the first volume. Open {} instead",
534                path.display(),
535                rar.first().display()
536            );
537        }
538        let mut volumes = vec![path.to_path_buf()];
539        while let Some(next) = rar.volume(volumes.len()).filter(|p| p.exists()) {
540            volumes.push(next);
541        }
542        return Ok(volumes);
543    }
544    let Some((base, width, n)) = split_suffix(path) else {
545        return Ok(vec![path.to_path_buf()]);
546    };
547    if n != 1 {
548        bail!(
549            "{} is not the first part. Open {} instead",
550            path.display(),
551            numbered(&base, width, 1).display()
552        );
553    }
554    let mut parts = vec![path.to_path_buf()];
555    loop {
556        let next = numbered(&base, width, parts.len() as u64 + 1);
557        if !next.exists() {
558            return Ok(parts);
559        }
560        parts.push(next);
561    }
562}
563
564/// `game.7z.001` is `("game.7z", 3, 1)`. Only names with a real extension
565/// before the number count, so a file that just happens to end in digits
566/// isn't mistaken for a volume.
567fn split_suffix(path: &Path) -> Option<(PathBuf, usize, u64)> {
568    let name = path.file_name()?.to_str()?;
569    let (stem, digits) = name.rsplit_once('.')?;
570    if digits.len() < 3 || !digits.bytes().all(|b| b.is_ascii_digit()) || !stem.contains('.') {
571        return None;
572    }
573    Some((
574        path.with_file_name(stem),
575        digits.len(),
576        digits.parse().ok()?,
577    ))
578}
579
580fn numbered(base: &Path, width: usize, n: u64) -> PathBuf {
581    let mut s = base.as_os_str().to_owned();
582    s.push(format!(".{n:0width$}"));
583    PathBuf::from(s)
584}
585
586/// Reads the joined archive. Parts or regions that were already truncated
587/// away read as zeros: format parsers scan backwards over them looking for
588/// end records, and zeros never match a signature.
589pub struct Reader {
590    parts: Arc<[Part]>,
591    open: Option<(usize, File)>,
592    tail: Option<Arc<Tail>>,
593    len: u64,
594    pos: u64,
595    reads: Arc<Reads>,
596}
597
598impl Read for Reader {
599    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
600        let n = self.read_at_pos(buf)?;
601        self.reads.done.fetch_add(n as u64, Ordering::Relaxed);
602        Ok(n)
603    }
604}
605
606impl Reader {
607    fn read_at_pos(&mut self, buf: &mut [u8]) -> io::Result<usize> {
608        if self.pos >= self.len || buf.is_empty() {
609            return Ok(0);
610        }
611        let live_end = match &self.tail {
612            Some(t) if self.pos >= t.start => {
613                let at = (self.pos - t.start) as usize;
614                let src = t.bytes.get(at..).unwrap_or(&[]);
615                let n = src.len().min(buf.len());
616                buf[..n].copy_from_slice(&src[..n]);
617                self.pos += n as u64;
618                return Ok(n);
619            }
620            Some(t) => t.start,
621            None => self.len,
622        };
623        let i = self.parts.partition_point(|p| p.start <= self.pos) - 1;
624        let part = &self.parts[i];
625        let room = (part.start + part.len).min(live_end) - self.pos;
626        let room = room.min(buf.len() as u64) as usize;
627        if self.open.as_ref().is_none_or(|(j, _)| *j != i) {
628            self.open = File::open(&part.path).ok().map(|f| (i, f));
629        }
630        let n = match &mut self.open {
631            Some((_, f)) => {
632                f.seek(SeekFrom::Start(self.pos - part.start))?;
633                f.read(&mut buf[..room])?
634            }
635            None => 0,
636        };
637        let n = if n == 0 {
638            buf[..room].fill(0);
639            room
640        } else {
641            n
642        };
643        self.pos += n as u64;
644        Ok(n)
645    }
646}
647
648impl Seek for Reader {
649    fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
650        let pos = match to {
651            SeekFrom::Start(p) => Some(p),
652            SeekFrom::End(d) => self.len.checked_add_signed(d),
653            SeekFrom::Current(d) => self.pos.checked_add_signed(d),
654        };
655        self.pos = pos.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "bad seek"))?;
656        Ok(self.pos)
657    }
658}
659
660/// How the volumes of a RAR set are named, and which one a path is.
661struct RarSet {
662    /// The path without the part of the name that changes.
663    stem: PathBuf,
664    style: RarStyle,
665    /// 0 for the first volume.
666    index: usize,
667    /// Upper case extensions stay upper case.
668    upper: bool,
669}
670
671enum RarStyle {
672    /// `name.part1.rar`, `name.part01.rar`: the number's width is kept.
673    Part { width: usize },
674    /// `name.rar`, `name.r00`, `name.r01`, ..., `name.r99`, `name.s00`, ...
675    Old,
676}
677
678impl RarSet {
679    fn first(&self) -> PathBuf {
680        self.volume(0).expect("the first volume always has a name")
681    }
682
683    /// `None` past `name.z99`, the last name the old style has.
684    fn volume(&self, index: usize) -> Option<PathBuf> {
685        let mut name = self.stem.as_os_str().to_owned();
686        let case = |s: String| if self.upper { s.to_uppercase() } else { s };
687        match self.style {
688            RarStyle::Part { width } => {
689                name.push(case(format!(".part{:0width$}.rar", index.checked_add(1)?)));
690            }
691            RarStyle::Old if index == 0 => name.push(case(".rar".into())),
692            RarStyle::Old => {
693                let n = index - 1;
694                let letter = u8::try_from(n / 100)
695                    .ok()
696                    .and_then(|l| b'r'.checked_add(l))
697                    .filter(|l| *l <= b'z')?;
698                name.push(case(format!(".{}{:02}", letter as char, n % 100)));
699            }
700        }
701        Some(PathBuf::from(name))
702    }
703
704    fn has_volume(&self, index: usize) -> bool {
705        self.volume(index).is_some_and(|p| p.exists())
706    }
707}
708
709/// Recognises a volume of a RAR set by its name. A bare `name.rar` counts
710/// only if `name.r00` sits next to it, so a single RAR file is not a set.
711fn rar_volume(path: &Path) -> Option<RarSet> {
712    let set = rar_naming(path)?;
713    if matches!(set.style, RarStyle::Old) && set.index == 0 && !set.has_volume(1) {
714        return None;
715    }
716    Some(set)
717}
718
719/// [`rar_volume`] by the name alone: a bare `name.rar` is the first volume
720/// of a set whether or not `name.r00` is there, as it may already be gone.
721fn rar_naming(path: &Path) -> Option<RarSet> {
722    let name = path.file_name()?.to_str()?;
723    let lower = name.to_ascii_lowercase();
724    let upper = name.chars().rev().take(3).all(|c| !c.is_ascii_lowercase());
725    let (stem_len, ext) = lower.rsplit_once('.').map(|(s, e)| (s.len(), e))?;
726    let stem = &name[..stem_len];
727    if ext == "rar" {
728        if let Some((before, digits)) = stem.to_ascii_lowercase().rsplit_once(".part")
729            && !digits.is_empty()
730            && digits.bytes().all(|b| b.is_ascii_digit())
731        {
732            let n: usize = digits.parse().ok()?;
733            return Some(RarSet {
734                stem: path.with_file_name(&name[..before.len()]),
735                style: RarStyle::Part {
736                    width: digits.len(),
737                },
738                index: n.checked_sub(1)?,
739                upper,
740            });
741        }
742        return Some(RarSet {
743            stem: path.with_file_name(stem),
744            style: RarStyle::Old,
745            index: 0,
746            upper,
747        });
748    }
749    let bytes = ext.as_bytes();
750    if bytes.len() == 3
751        && (b'r'..=b'z').contains(&bytes[0])
752        && bytes[1].is_ascii_digit()
753        && bytes[2].is_ascii_digit()
754    {
755        let n = usize::from(bytes[0] - b'r') * 100
756            + usize::from(bytes[1] - b'0') * 10
757            + usize::from(bytes[2] - b'0');
758        let set = RarSet {
759            stem: path.with_file_name(stem),
760            style: RarStyle::Old,
761            index: n + 1,
762            upper,
763        };
764        // Other formats number their volumes the same way (`.z01` for a
765        // split ZIP), so it is a RAR volume only next to its first one. RAR
766        // reaches `.z00` only after `.y99`, and volumes are deleted from the
767        // last, so `.y99` is there for as long as a `.z` volume is.
768        let past_y = bytes[0] == b'z';
769        return (set.has_volume(0) && (!past_y || set.has_volume(800))).then_some(set);
770    }
771    None
772}
773
774/// How the segments of a native split ZIP are named: `game.z01`, `game.z02`,
775/// ..., `game.z99`, `game.z100`, ..., and last `game.zip`, which holds the
776/// index. Info-ZIP `zip -s`, WinZip and WinRAR write them so.
777struct ZipSet {
778    /// The path without its extension.
779    stem: PathBuf,
780    /// The disk a `.zNN` segment is (`.z01` is 0), `None` for the `.zip`.
781    disk: Option<usize>,
782    /// Upper case extensions stay upper case.
783    upper: bool,
784}
785
786impl ZipSet {
787    fn named(&self, ext: String) -> PathBuf {
788        let mut name = self.stem.as_os_str().to_owned();
789        name.push(if self.upper { ext.to_uppercase() } else { ext });
790        PathBuf::from(name)
791    }
792
793    fn segment(&self, disk: usize) -> PathBuf {
794        self.named(format!(".z{:02}", disk + 1))
795    }
796
797    fn last(&self) -> PathBuf {
798        self.named(".zip".into())
799    }
800}
801
802/// A native split ZIP segment by its name alone: any `.zNN`, and any `.zip`.
803fn zip_naming(path: &Path) -> Option<ZipSet> {
804    let name = path.file_name()?.to_str()?;
805    let (stem, ext) = name.rsplit_once('.')?;
806    if stem.is_empty() {
807        return None;
808    }
809    let upper = !ext.chars().any(|c| c.is_ascii_lowercase());
810    let lower = ext.to_ascii_lowercase();
811    let disk = if lower == "zip" {
812        None
813    } else {
814        let digits = lower.strip_prefix('z')?;
815        // `.z01` to `.z99`, then `.z100` with no padding.
816        if digits.len() < 2
817            || !digits.bytes().all(|b| b.is_ascii_digit())
818            || (digits.len() > 2 && digits.starts_with('0'))
819        {
820            return None;
821        }
822        let n: usize = digits.parse().ok()?;
823        Some(n.checked_sub(1)?)
824    };
825    Some(ZipSet {
826        stem: path.with_file_name(stem),
827        disk,
828        upper,
829    })
830}
831
832/// The native split ZIP `path` is a segment of. Any `.zNN` is one; a `.zip`
833/// only when `<stem>.z01` is next to it, or the journal of an extraction
834/// that has already deleted `<stem>.z01`'s neighbours is. Callers ask
835/// [`rar_volume`] first, which takes a `.zNN` next to its RAR set.
836fn zip_volume(path: &Path) -> Option<ZipSet> {
837    let set = zip_naming(path)?;
838    if set.disk.is_none() {
839        let first = set.segment(0);
840        let mut journal = first.as_os_str().to_owned();
841        journal.push(".hatchzip");
842        if !first.exists() && !Path::new(&journal).exists() {
843            return None;
844        }
845    }
846    Some(set)
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852
853    /// `.z01` up to `.z99`, then `.z100`; upper case stays; the `.zip` and
854    /// every segment find the first one, and only with it next to the
855    /// `.zip`.
856    #[test]
857    fn split_zip_segments_are_named_and_found() {
858        let dir = std::env::temp_dir().join(format!("hatchzip-zipset-{}", std::process::id()));
859        fs::create_dir_all(&dir).unwrap();
860        let first = dir.join("game.z01");
861        assert_eq!(split_zip_segment(&first, 98), Some(dir.join("game.z99")));
862        assert_eq!(split_zip_segment(&first, 99), Some(dir.join("game.z100")));
863        assert_eq!(split_zip_last(&first), Some(dir.join("game.zip")));
864        assert_eq!(
865            split_zip_segment(&dir.join("GAME.Z01"), 1),
866            Some(dir.join("GAME.Z02"))
867        );
868        assert_eq!(
869            volume_path_in(&first, 2, 3),
870            Some(dir.join("game.zip")),
871            "the last of three is the .zip"
872        );
873        assert_eq!(volume_path_in(&first, 1, 3), Some(dir.join("game.z02")));
874        assert_eq!(
875            volume_path_in(&first, 0, 1),
876            Some(first.clone()),
877            "a set of one is the file itself"
878        );
879        assert!(zip_naming(&dir.join("game.z1")).is_none());
880        assert!(zip_naming(&dir.join("game.z001")).is_none());
881        assert!(zip_naming(&dir.join("game.z00")).is_none());
882
883        // A lone .zip is not a set.
884        fs::write(dir.join("game.zip"), b"x").unwrap();
885        assert_eq!(first_volume(&dir.join("game.zip")), dir.join("game.zip"));
886        // With the first segment next to it, or its journal, it is.
887        fs::write(&first, b"x").unwrap();
888        assert_eq!(first_volume(&dir.join("game.zip")), first);
889        assert_eq!(first_volume(&dir.join("game.z07")), first);
890        fs::remove_file(&first).unwrap();
891        fs::write(dir.join("game.z01.hatchzip"), b"{}").unwrap();
892        assert_eq!(first_volume(&dir.join("game.zip")), first);
893        fs::remove_dir_all(&dir).unwrap();
894    }
895
896    /// A `.zNN` is a RAR volume only next to its `.rar` and `.y99`, which
897    /// RAR writes before it reaches `.z00`.
898    #[test]
899    fn a_z_volume_is_rar_only_past_y99() {
900        let dir = std::env::temp_dir().join(format!("hatchzip-rarz-{}", std::process::id()));
901        fs::create_dir_all(&dir).unwrap();
902        fs::write(dir.join("game.rar"), b"x").unwrap();
903        fs::write(dir.join("game.r00"), b"x").unwrap();
904        fs::write(dir.join("game.z01"), b"x").unwrap();
905        assert_eq!(first_volume(&dir.join("game.z01")), dir.join("game.z01"));
906        assert!(is_split_zip(&dir.join("game.z01")));
907        fs::write(dir.join("game.y99"), b"x").unwrap();
908        assert_eq!(first_volume(&dir.join("game.z01")), dir.join("game.rar"));
909        fs::remove_dir_all(&dir).unwrap();
910    }
911
912    /// A tail longer or shorter than the bytes it stands for moves the end
913    /// the reader reports, so a search for end records from the end finds
914    /// them.
915    #[test]
916    fn a_reader_ends_where_its_tail_does() {
917        let dir = std::env::temp_dir().join(format!("hatchzip-tailend-{}", std::process::id()));
918        fs::create_dir_all(&dir).unwrap();
919        let path = dir.join("game.bin");
920        fs::write(&path, vec![7u8; 100]).unwrap();
921        let storage = Storage::open(&path, false).unwrap();
922        for len in [10usize, 60] {
923            let tail = Arc::new(Tail {
924                start: 80,
925                bytes: vec![1; len],
926            });
927            let mut r = storage.reader(Some(tail));
928            assert_eq!(r.seek(SeekFrom::End(0)).unwrap(), 80 + len as u64);
929            let mut all = Vec::new();
930            r.seek(SeekFrom::Start(0)).unwrap();
931            r.read_to_end(&mut all).unwrap();
932            assert_eq!(all.len(), 80 + len);
933            assert!(all[80..].iter().all(|&b| b == 1));
934        }
935        drop(storage);
936        fs::remove_dir_all(&dir).unwrap();
937    }
938
939    /// The letter of `.r00` counts up to `z`; a set that needs more names is
940    /// not followed past `.z99`, where the letter would leave the alphabet.
941    #[test]
942    fn old_style_rar_volume_names_end_at_z99() {
943        let set = RarSet {
944            stem: PathBuf::from("set"),
945            style: RarStyle::Old,
946            index: 0,
947            upper: false,
948        };
949        let name = |i| set.volume(i).map(|p| p.to_string_lossy().into_owned());
950        assert_eq!(name(0).as_deref(), Some("set.rar"));
951        assert_eq!(name(1).as_deref(), Some("set.r00"));
952        assert_eq!(name(101).as_deref(), Some("set.s00"));
953        assert_eq!(name(900).as_deref(), Some("set.z99"));
954        assert_eq!(name(901), None);
955        assert_eq!(name(14_301), None);
956    }
957
958    /// What front ends show while an archive opens: every reader counts, a
959    /// split set is one pass, and a pass can start part way in.
960    #[test]
961    fn reads_are_counted_across_volumes() {
962        let dir = std::env::temp_dir().join(format!("hatchzip-reads-{}", std::process::id()));
963        fs::create_dir_all(&dir).unwrap();
964        fs::write(dir.join("game.7z.001"), vec![1u8; 3000]).unwrap();
965        fs::write(dir.join("game.7z.002"), vec![2u8; 1000]).unwrap();
966
967        let mut storage = Storage::open(&dir.join("game.7z.001"), false).unwrap();
968        let reads = Arc::new(Reads::default());
969        storage.count_reads(reads.clone());
970        assert_eq!(reads.fraction(), Some(0.0));
971
972        let mut half = vec![0; 2000];
973        storage.reader(None).read_exact(&mut half).unwrap();
974        assert_eq!(reads.fraction(), Some(0.5));
975        let mut rest = Vec::new();
976        let mut r = storage.reader(None);
977        r.seek(SeekFrom::Start(2000)).unwrap();
978        r.read_to_end(&mut rest).unwrap();
979        assert_eq!(reads.fraction(), Some(1.0));
980
981        // A resumed pass that starts at byte 3000 has 1000 bytes to read.
982        storage.expect_reads(1000);
983        let mut last = vec![0; 500];
984        r.seek(SeekFrom::Start(3000)).unwrap();
985        r.read_exact(&mut last).unwrap();
986        assert_eq!(reads.fraction(), Some(0.5));
987
988        reads.reset();
989        assert_eq!(reads.fraction(), None);
990        drop(storage);
991        fs::remove_dir_all(&dir).unwrap();
992    }
993}