use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use crate::fidelity::{Direction, FidelityReport, Synthesis};
use crate::source::{EntryKind, FileContent, Source, SourceEntry};
use crate::tree::{FsTree, NodeKind, TreeError, made_by_the_format};
#[derive(Clone)]
pub struct ImageFile {
reader: Arc<Mutex<dyn ReadNode>>,
index: usize,
len: u64,
}
trait ReadNode: Send {
fn read_node(&mut self, index: usize, offset: u64, buf: &mut [u8]) -> Result<usize, TreeError>;
}
struct Held<T: FsTree> {
tree: T,
nodes: Vec<T::Node>,
}
impl<T> ReadNode for Held<T>
where
T: FsTree + Send,
T::Node: Send,
{
fn read_node(&mut self, index: usize, offset: u64, buf: &mut [u8]) -> Result<usize, TreeError> {
self.tree.read_bytes(&self.nodes[index], offset, buf)
}
}
impl ImageFile {
#[must_use]
pub const fn len(&self) -> u64 {
self.len
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
pub fn read_at(&self, at: u64, buf: &mut [u8]) -> std::io::Result<()> {
let end = at.checked_add(buf.len() as u64);
if end.is_none_or(|end| end > self.len) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"{} bytes at {at} run past the end of a file of {} bytes in an image",
buf.len(),
self.len
),
));
}
let mut reader = self.reader.lock().unwrap_or_else(PoisonError::into_inner);
let mut done = 0;
while done < buf.len() {
let n = reader
.read_node(self.index, at + done as u64, &mut buf[done..])
.map_err(io_error)?;
if n == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"a file of {} bytes in an image ends after {}",
self.len,
at + done as u64
),
));
}
done += n;
}
Ok(())
}
}
fn io_error(e: TreeError) -> std::io::Error {
match e {
TreeError::Io { kind, message } => std::io::Error::new(kind, message),
other => std::io::Error::new(std::io::ErrorKind::InvalidData, other.to_string()),
}
}
impl PartialEq for ImageFile {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.reader, &other.reader) && self.index == other.index
}
}
impl Eq for ImageFile {}
impl std::fmt::Debug for ImageFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImageFile")
.field("index", &self.index)
.field("len", &self.len)
.finish_non_exhaustive()
}
}
pub struct ImageSource {
entries: Vec<SourceEntry>,
fidelity: FidelityReport,
}
impl ImageSource {
pub fn read<T>(tree: T, synthesis: &Synthesis) -> Result<Self, TreeError>
where
T: FsTree + Send + 'static,
T::Node: Send + 'static,
{
let mut tree = tree;
let mut fidelity = FidelityReport::new();
let mut nodes: Vec<T::Node> = Vec::new();
let mut found: Vec<(SourceEntry, Option<(usize, u64)>)> = Vec::new();
let mut first_name: HashMap<u64, Vec<u8>> = HashMap::new();
tree.walk_tree(|tree, entry| -> Result<(), TreeError> {
if made_by_the_format(&entry.path, tree.family()) {
return Ok(());
}
let path = if entry.path.is_empty() {
b"/".to_vec()
} else {
entry.path.clone()
};
let second = match entry.shared {
Some(id) => match first_name.get(&id) {
Some(first) => Some(first.clone()),
None => {
first_name.insert(id, path.clone());
None
}
},
None => None,
};
if let Some(target) = second {
let meta = tree.stat(&entry.node, synthesis)?.meta;
found.push((
SourceEntry::new(path, EntryKind::HardLink { target }, meta),
None,
));
return Ok(());
}
let attributes = tree.stat(&entry.node, synthesis)?;
let darwin = tree.darwin(&entry.node)?;
for property in &attributes.synthesized {
fidelity.record(Direction::Synthesized, &path, *property);
}
let mut content = None;
let kind = match entry.kind {
NodeKind::Directory => EntryKind::Directory,
NodeKind::File { size } => {
tree.check_file_size(&path, size)?;
content = Some((nodes.len(), size));
nodes.push(entry.node);
EntryKind::File(FileContent::Owned(Vec::new()))
}
NodeKind::Symlink => EntryKind::Symlink(tree.link_target(&entry.node)?),
NodeKind::CharDevice { major, minor } => EntryKind::CharDevice { major, minor },
NodeKind::BlockDevice { major, minor } => EntryKind::BlockDevice { major, minor },
NodeKind::Fifo => EntryKind::Fifo,
NodeKind::Socket => EntryKind::Socket,
};
let mut source =
SourceEntry::new(path, kind, attributes.meta).with_xattrs(attributes.xattrs);
source.darwin = darwin;
found.push((source, content));
Ok(())
})?;
let reader: Arc<Mutex<dyn ReadNode>> = Arc::new(Mutex::new(Held { tree, nodes }));
let entries = found
.into_iter()
.map(|(mut entry, content)| {
if let Some((index, len)) = content {
entry.kind = EntryKind::File(FileContent::Image(ImageFile {
reader: Arc::clone(&reader),
index,
len,
}));
}
entry
})
.collect();
Ok(Self { entries, fidelity })
}
#[must_use]
pub const fn fidelity(&self) -> &FidelityReport {
&self.fidelity
}
#[must_use]
pub fn entries(&self) -> &[SourceEntry] {
&self.entries
}
}
impl Source for ImageSource {
fn into_entries(self) -> Vec<SourceEntry> {
self.entries
}
}