pub mod fs;
pub mod zip;
use std::io;
use crate::{optimizer::{EntryType, ProgressState, StrError, ERR_SIGNFILE}, errors::ErrorCollector, fop};
use crossbeam_channel::{Sender, Receiver, SendError};
pub trait EntryReader {
fn read_entries(
self,
tx: Sender<EntryType>,
use_blacklist: bool
) -> io::Result<()>;
}
pub struct EntrySaver<S: EntrySaverSpec>(S);
pub trait EntrySaverSpec {
fn save_dir(&mut self, dir: &str) -> io::Result<()>;
fn save_file(&mut self, fname: &str, buf: &[u8], min_compress: usize) -> io::Result<()>;
}
impl<T: EntrySaverSpec> EntrySaver<T> {
pub fn save_entries(
mut self,
rx: Receiver<EntryType>,
ev: &mut dyn ErrorCollector,
ps: &Sender<ProgressState>
) -> io::Result<()> {
const SEND_ERR: fn(SendError<ProgressState>) -> io::Error = |e: SendError<ProgressState>| {
io::Error::new(io::ErrorKind::Other, e)
};
let mut cv = Vec::new();
let mut n = 0;
for et in rx {
match et {
EntryType::Count(u) => {
ps.send(ProgressState::Start(u)).map_err(SEND_ERR)?;
}
EntryType::Directory(dir) => {
self.0.save_dir(&dir)?;
}
EntryType::File(fname, buf, fop) => {
ps.send(ProgressState::Push(n, fname.clone())).map_err(SEND_ERR)?;
n += 1;
use fop::FileOp::*;
match fop {
Ignore => {
ev.collect(&fname, Box::new(crate::blacklist::BlacklistedFile));
}
Signfile => {
ev.collect(&fname, Box::new(StrError(ERR_SIGNFILE.to_string())));
}
Minify(m) => {
let buf = match m.minify(&buf, &mut cv) {
Ok(()) => &cv,
Err(e) => {
ev.collect(&fname, e);
&buf
}
};
self.0.save_file(&fname, buf, m.compress_min())?;
cv.clear();
}
Recompress(x) => {
self.0.save_file(&fname, &buf, x)?;
}
}
}
}
}
ps.send(ProgressState::Finish).map_err(SEND_ERR)?;
Ok(())
}
}
impl<T: FnOnce(Sender<EntryType>, bool) -> io::Result<()>> EntryReader for T {
fn read_entries(
self,
tx: Sender<EntryType>,
use_blacklist: bool
) -> io::Result<()> {
self(tx, use_blacklist)
}
}