1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use errors::Result;
use errors::ResultExt;
use zip::Zip;
use std::io;
use std::fmt;
use std::default;
use std::path::Path;
use std::io::Read;
use std::io::Write;
use std::io::Cursor;
use libzip::ZipWriter;
use libzip::write::FileOptions;
pub struct ZipLibrary {
writer: ZipWriter<Cursor<Vec<u8>>>,
}
impl fmt::Debug for ZipLibrary {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ZipLibrary")
}
}
impl default::Default for ZipLibrary {
fn default() -> ZipLibrary {
ZipLibrary::new()
}
}
impl ZipLibrary {
pub fn new() -> ZipLibrary {
ZipLibrary { writer: ZipWriter::new(Cursor::new(vec![])) }
}
}
impl Zip for ZipLibrary {
fn write_file<P: AsRef<Path>, R: Read>(&mut self, path: P, mut content: R) -> Result<()> {
let file = format!("{}", path.as_ref().display());
let options = FileOptions::default();
self.writer
.start_file(file.clone(), options)
.chain_err(|| format!("could not create file '{}' in epub", file))?;
io::copy(&mut content, &mut self.writer)
.chain_err(|| format!("could not write file '{}' in epub",
file))?;
Ok(())
}
fn generate<W: Write>(&mut self, mut to: W) -> Result<()> {
let cursor = self.writer
.finish()
.chain_err(|| "error writing zip file")?;
let bytes = cursor.into_inner();
to.write_all(bytes.as_ref())
.chain_err(|| "error writing zip file")?;
Ok(())
}
}