1use std::fs::File;
8use std::io::{Read, Seek};
9use std::path::Path;
10
11use serde::de::DeserializeOwned;
12use zip::ZipArchive;
13
14use crate::error::{OfdError, Result};
15
16pub struct OfdPackage<R> {
21 archive: ZipArchive<R>,
22}
23
24impl OfdPackage<File> {
25 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
27 Self::new(File::open(path)?)
28 }
29}
30
31impl<R: Read + Seek> OfdPackage<R> {
32 pub fn new(reader: R) -> Result<Self> {
34 Ok(OfdPackage {
35 archive: ZipArchive::new(reader)?,
36 })
37 }
38
39 pub fn read(&mut self, path: &str) -> Result<Vec<u8>> {
43 let name = normalize(path);
44 let mut entry = self
45 .archive
46 .by_name(&name)
47 .map_err(|_| OfdError::EntryNotFound(name.clone()))?;
48 let mut buf = Vec::with_capacity(entry.size() as usize);
49 entry.read_to_end(&mut buf)?;
50 Ok(buf)
51 }
52
53 pub fn read_to_string(&mut self, path: &str) -> Result<String> {
55 let bytes = self.read(path)?;
56 String::from_utf8(bytes)
57 .map_err(|e| OfdError::Structure(format!("entry {path} is not valid UTF-8: {e}")))
58 }
59
60 pub fn parse<T: DeserializeOwned>(&mut self, path: &str) -> Result<T> {
62 let text = self.read_to_string(path)?;
63 Ok(quick_xml::de::from_str(&text)?)
64 }
65
66 pub fn contains(&self, path: &str) -> bool {
68 let name = normalize(path);
69 self.archive.file_names().any(|n| n == name)
70 }
71
72 pub fn entries(&self) -> Vec<String> {
74 self.archive.file_names().map(|s| s.to_string()).collect()
75 }
76
77 pub fn len(&self) -> usize {
79 self.archive.len()
80 }
81
82 pub fn is_empty(&self) -> bool {
84 self.archive.is_empty()
85 }
86}
87
88fn normalize(path: &str) -> String {
90 path.trim_start_matches('/').to_string()
91}