unshield/
archive.rs

1use crate::format::{FileInfo, Format, FormatStep};
2
3use std::collections::HashMap;
4use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom};
5
6/// An interface for reading an InstallShield Z archive.
7///
8/// You can use this to read a Z archive out of any type that
9/// implements [`Read`][Read] and [`Seek`][Seek].
10///
11///  [Read]: https://doc.rust-lang.org/std/io/trait.Read.html
12///  [Seek]: https://doc.rust-lang.org/std/io/trait.Seek.html
13#[derive(Debug)]
14pub struct Archive<R> {
15    inner: R,
16    files: HashMap<String, FileInfo>,
17}
18
19impl<R> Archive<R>
20where
21    R: Read + Seek,
22{
23    /// Create a new Z archive from an underlying reader.
24    ///
25    /// This function will parse the file header and table of
26    /// contents. If either of these fail, it will return an `Err`.
27    pub fn new(mut inner: R) -> Result<Self> {
28        let mut fmt = Format::new();
29        loop {
30            match fmt.next()? {
31                FormatStep::Read(s, ref mut buf) => {
32                    inner.seek(s)?;
33                    inner.read_exact(buf)?;
34                }
35
36                FormatStep::Done(filesvec) => {
37                    let mut files = HashMap::with_capacity(filesvec.len());
38                    for f in filesvec.into_iter() {
39                        files.insert(f.path.clone(), f);
40                    }
41                    return Ok(Archive { inner, files });
42                }
43            }
44        }
45    }
46
47    /// List the files contained in the archive.
48    pub fn list(&self) -> impl Iterator<Item = &FileInfo> {
49        self.files.values()
50    }
51
52    fn find(&self, path: &str) -> Result<&FileInfo> {
53        self.files
54            .get(path)
55            .ok_or_else(|| Error::new(ErrorKind::NotFound, "file not found"))
56    }
57
58    /// Load a file into a `Vec`.
59    pub fn load(&mut self, path: &str) -> Result<Vec<u8>> {
60        explode::explode(&self.load_compressed(path)?)
61            .map_err(|e| Error::new(ErrorKind::InvalidData, e))
62    }
63
64    /// Load a file into a `Vec` without decompressing it.
65    pub fn load_compressed(&mut self, path: &str) -> Result<Vec<u8>> {
66        let info = self.find(path)?;
67        let size = info.size;
68        let offset = info.offset;
69        let mut ret = vec![0; size];
70        self.inner.seek(SeekFrom::Start(offset))?;
71        self.inner.read_exact(&mut ret)?;
72        Ok(ret)
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::Archive;
79    use crate::examples::EXAMPLES;
80    use std::io::Cursor;
81
82    #[test]
83    fn archive_new() {
84        for (arcdata, _files) in EXAMPLES {
85            let c = Cursor::new(arcdata);
86            let _ar = Archive::new(c).unwrap();
87        }
88    }
89
90    #[test]
91    fn archive_list() {
92        for (arcdata, files) in EXAMPLES {
93            let c = Cursor::new(arcdata);
94            let ar = Archive::new(c).unwrap();
95            // are all files we can list expected?
96            for file in ar.list() {
97                let i = files.iter().find(|(name, _)| *name == file.path);
98                if i.is_none() {
99                    panic!("unexpected file {:?}", file.path);
100                }
101            }
102        }
103    }
104
105    #[test]
106    fn archive_load() {
107        for (arcdata, files) in EXAMPLES {
108            let c = Cursor::new(arcdata);
109            let mut ar = Archive::new(c).unwrap();
110            // do all expected files have the right contents?
111            for (fname, contents) in files.iter() {
112                let ours = ar.load(fname).unwrap();
113                assert_eq!(ours, *contents);
114            }
115        }
116    }
117}