anyreader_walker/
utils.rs

1use crate::EntryDetails;
2use std::path::{Path, PathBuf};
3
4/// A utility struct to keep track of the current archive stack.
5/// This is useful when processing nested archives - it supports
6/// pushing and popping archives from the stack, and provides the
7/// current nested path - including all previous nested paths.
8///
9/// # Example
10/// ```
11/// # use std::path::Path;
12/// # use anyreader_walker::{ArchiveStack, EntryDetails};
13/// let mut stack = ArchiveStack::new();
14/// stack.push_details(EntryDetails::new("first.tar", 5));
15/// stack.push_details(EntryDetails::new("second.tar", 10));
16/// stack.push_details(EntryDetails::new("third.tar", 7));
17/// assert_eq!(stack.root_path(), Path::new("first.tar"));
18/// assert_eq!(stack.nested_path(), Path::new("second.tar/third.tar"));
19/// assert_eq!(stack.current_depth(), 3);
20/// stack.pop_details();
21/// assert_eq!(stack.nested_path(), Path::new("second.tar"));
22/// ```
23#[derive(Debug, Default)]
24pub struct ArchiveStack {
25    stack: smallvec::SmallVec<[EntryDetails; 6]>,
26}
27
28impl ArchiveStack {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn last_entry(&self) -> Option<&EntryDetails> {
34        self.stack.last()
35    }
36
37    pub fn push_details(&mut self, details: EntryDetails) {
38        self.stack.push(details);
39    }
40
41    pub fn pop_details(&mut self) -> Option<EntryDetails> {
42        self.stack.pop()
43    }
44
45    pub fn current_depth(&self) -> usize {
46        self.stack.len()
47    }
48
49    pub fn is_empty(&self) -> bool {
50        self.stack.is_empty()
51    }
52
53    pub fn full_path(&self) -> PathBuf {
54        PathBuf::from_iter(self.stack.iter().map(|d| d.path.as_path()))
55    }
56
57    pub fn root_path(&self) -> &Path {
58        self.stack
59            .first()
60            .map(|d| d.path.as_path())
61            .unwrap_or(Path::new(""))
62    }
63
64    pub fn nested_path(&self) -> PathBuf {
65        PathBuf::from_iter(self.nested_path_iter())
66    }
67
68    pub fn nested_path_iter(&self) -> impl Iterator<Item = &Path> {
69        self.stack.iter().skip(1).map(|d| d.path.as_path())
70    }
71}