use crate::{Content, ContentExtractor, ContentType, ExtractionPool};
use std::marker::PhantomData;
use super::{FolderContent, FileContent};
pub struct FolderExtractor<T: ContentType> {
_marker: PhantomData<T>,
pool: ExtractionPool<std::fs::ReadDir>,
entry: crate::Entry,
current_is_folder: bool,
recursive: bool,
open_files_exclusively: bool,
}
impl<T: ContentType> FolderExtractor<T> {
pub fn new(recursive: bool, open_files_exclusively: bool) -> Self {
Self {
_marker: PhantomData,
pool: ExtractionPool::new(4),
entry: crate::Entry::default(),
current_is_folder: false,
recursive,
open_files_exclusively,
}
}
}
impl<T: ContentType + 'static> ContentExtractor<T> for FolderExtractor<T> {
fn acquire(&mut self, content: &mut dyn Content<T>, _: &mut varmap::VarMap) -> Option<crate::ExtractionHandle> {
let obj = std::fs::read_dir(content.path().as_path()).ok()?;
Some(self.pool.acquire_slot(obj))
}
fn advance(&mut self, handle: crate::ExtractionHandle, _: &mut dyn Content<T>) -> Option<&crate::Entry> {
let rd = self.pool.get_mut(handle)?;
loop {
let folder_ent = match rd.next() {
Some(Ok(ent)) => ent,
Some(Err(_)) => continue, None => return None,
};
let ft = match folder_ent.file_type() {
Ok(ft) => ft,
Err(_) => continue, };
self.current_is_folder = ft.is_dir();
let symlink = ft.is_symlink();
if self.current_is_folder && symlink {
continue;
} if !self.recursive && self.current_is_folder {
continue;
} self.entry.path.clear();
self.entry.path.set_from_os(&folder_ent.path());
self.entry.size = if self.current_is_folder { 0 } else { folder_ent.metadata().map(|m| m.len()).unwrap_or(0) }; self.entry.skip_from_filtering = self.current_is_folder;
return Some(&self.entry);
}
}
fn extract(&mut self, _: crate::ExtractionHandle, content: &mut dyn Content<T>) -> Option<Box<dyn Content<T>>> {
if self.current_is_folder {
Some(Box::new(FolderContent::with_content_type(self.entry.path.as_path(), content.content_type()?)))
} else {
Some(Box::new(FileContent::with_size(self.entry.path.as_path(), self.entry.size, self.open_files_exclusively)))
}
}
fn release(&mut self, handle: crate::ExtractionHandle) {
self.pool.release_slot(handle);
}
}