use std::collections::BTreeSet;
use std::sync::Arc;
use crate::ids::PageId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EntryKind {
Body,
Annotation,
Signature,
Resource,
Other,
}
impl EntryKind {
pub fn of(name: &str) -> Self {
if name.ends_with("Annotation.xml")
|| name.ends_with("Annotations.xml")
|| name.contains("/Annots/")
{
EntryKind::Annotation
} else if name.ends_with("Page.xml") || name.ends_with("Document.xml") || name == "OFD.xml"
{
EntryKind::Body
} else if name.starts_with("Doc_") && name.contains("/Signs/") {
EntryKind::Signature
} else if name.contains("/Res/") {
EntryKind::Resource
} else {
EntryKind::Other
}
}
}
#[derive(Clone)]
pub struct PkgEntry {
pub name: String,
pub kind: EntryKind,
pub bytes: Arc<Vec<u8>>,
}
impl std::fmt::Debug for PkgEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PkgEntry")
.field("name", &self.name)
.field("kind", &self.kind)
.field("len", &self.bytes.len())
.finish()
}
}
#[derive(Debug, Clone, Default)]
pub struct PackageHandle {
pub entries: Vec<PkgEntry>,
pub consumed: BTreeSet<String>,
pub document_entry: Option<String>,
pub annotations_entry: Option<String>,
pub annotation_files: Vec<(PageId, String)>,
pub signatures_declared: bool,
pub signatures_entry: Option<String>,
}
impl PackageHandle {
pub fn empty() -> Self {
Self::default()
}
pub fn find(&self, name: &str) -> Option<&PkgEntry> {
self.entries.iter().find(|e| e.name == name)
}
pub fn annotation_entries(&self) -> impl Iterator<Item = &PkgEntry> {
self.entries
.iter()
.filter(|e| e.kind == EntryKind::Annotation)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entry_kind_follows_the_name() {
assert_eq!(EntryKind::of("OFD.xml"), EntryKind::Body);
assert_eq!(EntryKind::of("Doc_0/Document.xml"), EntryKind::Body);
assert_eq!(
EntryKind::of("Doc_0/Annots/Annotations.xml"),
EntryKind::Annotation
);
assert_eq!(
EntryKind::of("Doc_0/Pages/Page_0/Annotation.xml"),
EntryKind::Annotation
);
assert_eq!(
EntryKind::of("Doc_0/Signs/Sign_0/Seal.esl"),
EntryKind::Signature
);
assert_eq!(EntryKind::of("Doc_0/Res/a.png"), EntryKind::Resource);
assert_eq!(
EntryKind::of("Doc_0/Pages/Page_0/Content.xml"),
EntryKind::Other
);
assert_eq!(EntryKind::of("Doc_0/Attachs/note.txt"), EntryKind::Other);
}
#[test]
fn debug_shows_a_length_not_the_bytes() {
let entry = PkgEntry {
name: "a".to_owned(),
kind: EntryKind::Other,
bytes: Arc::new(vec![7u8; 4096]),
};
let text = format!("{entry:?}");
assert!(text.contains("4096"), "{text}");
assert!(!text.contains("7, 7, 7"), "{text}");
}
#[test]
fn empty_handle_finds_nothing() {
let h = PackageHandle::empty();
assert!(h.find("anything").is_none());
assert_eq!(h.annotation_entries().count(), 0);
}
}