use std::sync::Arc;
use crate::object::{Dictionary, ObjectId};
pub mod decode;
mod loader;
pub mod objstm;
pub mod predictor;
pub use loader::{StructureLimits, load_structure, load_structure_rebuilt, scan_for_object_header};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectLocation {
Offset(u64),
InObjectStream {
container: u32,
index: u32,
},
Free,
}
#[derive(Debug, Clone, Copy)]
pub struct XrefEntry {
pub id: ObjectId,
pub location: ObjectLocation,
}
#[derive(Debug)]
pub struct XrefMap {
entries: Box<[ObjectLocation]>,
generations: Box<[u16]>,
}
impl XrefMap {
pub fn from_parts(entries: Box<[ObjectLocation]>, generations: Box<[u16]>) -> Self {
assert_eq!(entries.len(), generations.len());
Self {
entries,
generations,
}
}
pub fn locate(&self, id: ObjectId) -> ObjectLocation {
let n = id.number as usize;
if n >= self.entries.len() || self.generations[n] != id.generation {
return ObjectLocation::Free;
}
self.entries[n]
}
pub fn live_entries(&self) -> impl Iterator<Item = XrefEntry> + '_ {
self.entries
.iter()
.copied()
.zip(self.generations.iter().copied())
.enumerate()
.filter_map(|(number, (location, generation))| {
(!matches!(location, ObjectLocation::Free)).then_some(XrefEntry {
id: ObjectId::new(number as u32, generation),
location,
})
})
}
pub fn size(&self) -> u32 {
self.entries.len() as u32
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XrefSectionKind {
Classic,
Stream,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RevisionXrefEntry {
pub id: ObjectId,
pub location: ObjectLocation,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct XrefEntryCounts {
pub total: u32,
pub live: u32,
pub compressed: u32,
pub free: u32,
}
impl XrefEntryCounts {
pub(crate) fn tally(&mut self, location: ObjectLocation) {
self.total = self.total.saturating_add(1);
match location {
ObjectLocation::Offset(_) => self.live = self.live.saturating_add(1),
ObjectLocation::InObjectStream { .. } => {
self.compressed = self.compressed.saturating_add(1);
}
ObjectLocation::Free => self.free = self.free.saturating_add(1),
}
}
}
#[derive(Debug, Clone)]
pub struct XrefSection {
pub offset: u64,
pub kind: XrefSectionKind,
pub entry_counts: XrefEntryCounts,
pub entries: Arc<[RevisionXrefEntry]>,
pub trailer: Arc<Dictionary>,
pub prev: Option<u64>,
pub auxiliary_of: Option<u32>,
pub recovery: Arc<[RecoveryEvent]>,
}
#[derive(Debug, Clone)]
pub struct Trailer {
pub dict: Arc<Dictionary>,
pub root: ObjectId,
pub info: Option<ObjectId>,
pub encrypt: Option<ObjectId>,
pub file_id: Option<[crate::object::PdfString; 2]>,
}
#[derive(Debug, Clone)]
pub enum RecoveryEvent {
StartXrefRecovered { reported: Option<u64>, used: u64 },
ObjectOffsetRepaired {
id: ObjectId,
declared: u64,
actual: u64,
},
StreamLengthRepaired {
id: ObjectId,
declared: Option<i64>,
actual: u64,
},
ReferenceGenerationRepaired {
id: ObjectId,
referenced: u32,
offset: u64,
},
XrefRebuilt,
SizeRepaired { declared: i64, actual: u32 },
Other(String),
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum StructureError {
#[error("not a PDF: header not found")]
NoHeader,
#[error("no usable cross-reference information (recovery failed)")]
NoUsableXref,
#[error("trailer has no /Root catalog reference")]
NoCatalog,
#[error("cross-reference data forms a cycle at offset {0}")]
XrefCycle(u64),
#[error("structural limit exceeded: {0}")]
LimitExceeded(&'static str),
#[error(transparent)]
Syntax(#[from] crate::syntax::SyntaxError),
#[error(transparent)]
Source(#[from] crate::source::SourceError),
#[error(transparent)]
Decode(#[from] decode::DecodeError),
}
#[derive(Debug)]
pub struct DocumentStructure {
pub version: PdfVersion,
pub header_offset: u64,
pub xref: XrefMap,
pub trailer: Trailer,
pub sections: Box<[XrefSection]>,
pub recovery: Box<[RecoveryEvent]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct PdfVersion {
pub major: u8,
pub minor: u8,
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn xref_map_shadows_by_generation() {
let map = XrefMap::from_parts(
vec![ObjectLocation::Free, ObjectLocation::Offset(15)].into_boxed_slice(),
vec![0, 0].into_boxed_slice(),
);
assert_eq!(map.locate(ObjectId::new(1, 0)), ObjectLocation::Offset(15));
assert_eq!(map.locate(ObjectId::new(1, 1)), ObjectLocation::Free);
assert_eq!(map.locate(ObjectId::new(9, 0)), ObjectLocation::Free);
}
#[test]
fn live_entries_skip_free_objects_and_preserve_generations() {
let map = XrefMap::from_parts(
vec![
ObjectLocation::Free,
ObjectLocation::Offset(15),
ObjectLocation::InObjectStream {
container: 9,
index: 2,
},
]
.into_boxed_slice(),
vec![u16::MAX, 4, 0].into_boxed_slice(),
);
let entries: Vec<_> = map.live_entries().collect();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].id, ObjectId::new(1, 4));
assert_eq!(entries[0].location, ObjectLocation::Offset(15));
assert_eq!(entries[1].id, ObjectId::new(2, 0));
assert_eq!(
entries[1].location,
ObjectLocation::InObjectStream {
container: 9,
index: 2
}
);
}
}