use std::{fs::File, io::{self}, thread, path::Path, any::Any, sync::Arc};
use zip::write::FileOptions;
use crossbeam_channel::{bounded, Sender};
use crate::{fop::FileOp, errors::ErrorCollector, entry::{self, EntryReader, EntrySaver, EntrySaverSpec}};
const JOIN_ERR: fn(Box<dyn Any + Send>) -> io::Error = |_| {
io::Error::new(io::ErrorKind::Other, "Thread join failed")
};
pub fn optimize_with<R: EntryReader + Send + 'static, S: EntrySaverSpec>(
reader: R,
saver: EntrySaver<S>,
ps: &Sender<ProgressState>,
errors: &mut ErrorCollector,
use_blacklist: bool
) -> io::Result<()> {
let (tx, rx) = bounded(2);
let t1 = thread::spawn(move || {
reader.read_entries(tx, use_blacklist)
});
saver.save_entries(rx, errors, ps)?;
t1.join().map_err(JOIN_ERR)?
}
pub fn optimize_archive(
in_path: Box<Path>,
out_path: Box<Path>,
ps: &Sender<ProgressState>,
errors: &mut ErrorCollector,
file_opts: &FileOptions,
use_blacklist: bool
) -> io::Result<()> {
let (tx, rx) = bounded(2);
let t1 = thread::spawn(move || {
let fin = File::open(in_path)?;
entry::zip::ZipEntryReader::new(fin).read_entries(tx, use_blacklist)
});
let fout = File::create(out_path)?;
entry::zip::ZipEntrySaver::custom(fout, *file_opts).save_entries(rx, errors, ps)?;
t1.join().map_err(JOIN_ERR)?
}
pub fn optimize_fs_copy(
in_path: Box<Path>,
out_path: Box<Path>,
ps: &Sender<ProgressState>,
errors: &mut ErrorCollector,
use_blacklist: bool
) -> io::Result<()> {
if in_path == out_path {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "The paths are the same"))
}
let (tx, rx) = bounded(2);
let t1 = thread::spawn(move || {
entry::fs::FSEntryReader::new(in_path).read_entries(tx, use_blacklist)
});
entry::fs::FSEntrySaver::new(out_path).save_entries(rx, errors, ps)?;
t1.join().map_err(JOIN_ERR)?
}
pub enum EntryType {
Count(usize),
Directory(Arc<str>),
File(Arc<str>, Vec<u8>, FileOp)
}
#[derive(Debug, Clone)]
pub enum ProgressState {
Start(usize),
Push(usize, Arc<str>),
Finish
}