use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::sync::Arc;
use laminapdf_cos::{CosMut, Dict, Error, Limit, Limits, ObjRef, Object, Position, Result, strip_crypt_filter};
use sha2::{Digest as _, Sha256};
type Key = [u8; 32];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Copied {
Object(ObjRef),
Null,
}
impl Copied {
fn reference(self) -> Object {
match self {
Self::Object(r) => Object::Ref(r),
Self::Null => Object::Null,
}
}
}
#[derive(Debug)]
pub struct ObjectCopier<'s> {
source: &'s laminapdf_cos::Document,
limits: Limits,
copies: BTreeMap<ObjRef, Copied>,
streams: BTreeMap<Key, ObjRef>,
keys: BTreeMap<ObjRef, Option<Key>>,
outside: BTreeSet<ObjRef>,
}
#[derive(Default)]
struct Walk {
roots: BTreeSet<ObjRef>,
order: Vec<(ObjRef, Arc<Object>)>,
objects: BTreeMap<ObjRef, Arc<Object>>,
nulls: BTreeSet<ObjRef>,
outside: BTreeSet<ObjRef>,
annots: BTreeSet<ObjRef>,
bytes: usize,
}
#[derive(Default)]
struct Journal {
copies: Vec<(ObjRef, Option<Copied>)>,
streams: Vec<Key>,
}
const NULL_KEY: Key = [0; 32];
impl<'s> ObjectCopier<'s> {
#[must_use]
pub fn new(source: &'s laminapdf_cos::Document, limits: Limits) -> Self {
Self {
source,
limits,
copies: BTreeMap::new(),
streams: BTreeMap::new(),
keys: BTreeMap::new(),
outside: BTreeSet::new(),
}
}
pub fn copy_pages(&mut self, target: &mut CosMut<'_>, pages: &[&laminapdf_cos::Page]) -> Result<Vec<ObjRef>> {
let roots: Vec<Dict> = pages.iter().map(|page| page_dict(page)).collect();
let walk = self.walk(&roots, pages.iter().filter_map(|page| page.obj_ref).collect())?;
let mut journal = Journal::default();
let written = self
.key_streams(&walk)
.and_then(|()| self.write(target, pages, &roots, &walk, &mut journal));
if written.is_err() {
self.undo(journal);
} else {
self.outside.extend(&walk.outside);
let copies = &self.copies;
self.outside
.retain(|r| !matches!(copies.get(r), Some(Copied::Object(_))));
}
written
}
fn map(&mut self, journal: &mut Journal, source: ObjRef, copied: Copied) {
journal.copies.push((source, self.copies.insert(source, copied)));
}
fn undo(&mut self, journal: Journal) {
for (source, before) in journal.copies.into_iter().rev() {
match before {
Some(copied) => self.copies.insert(source, copied),
None => self.copies.remove(&source),
};
}
for key in journal.streams {
self.streams.remove(&key);
}
}
fn key_streams(&mut self, walk: &Walk) -> Result<()> {
for (r, object) in &walk.order {
if matches!(**object, Object::Stream(_)) {
self.key_of(*r, walk, &mut Vec::new())?;
}
}
Ok(())
}
fn write(
&mut self,
target: &mut CosMut<'_>,
pages: &[&laminapdf_cos::Page],
roots: &[Dict],
walk: &Walk,
journal: &mut Journal,
) -> Result<Vec<ObjRef>> {
let doc = target.document();
let copies = pages.iter().map(|_| doc.reserve_number()).collect::<Result<Vec<_>>>()?;
for (page, ©) in pages.iter().zip(&copies) {
if let Some(r) = page.obj_ref {
self.map(journal, r, Copied::Object(copy));
}
}
for &r in &walk.nulls {
self.map(journal, r, Copied::Null);
}
let mut writes = Vec::new();
for (r, object) in &walk.order {
let key = match **object {
Object::Stream(_) => self.keys.get(r).copied().flatten(),
_ => None,
};
if let Some(©) = key.and_then(|k| self.streams.get(&k)) {
self.map(journal, *r, Copied::Object(copy));
continue;
}
let copy = doc.reserve_number()?;
self.map(journal, *r, Copied::Object(copy));
if let Some(key) = key {
self.streams.insert(key, copy);
journal.streams.push(key);
}
writes.push((copy, Arc::clone(object)));
}
let encrypted = self.source.encryption().is_some();
for (copy, object) in writes {
let mut object = self.rewrite(&object);
if let Object::Stream(stream) = &mut object {
stream.dict.remove("Length");
if encrypted {
strip_crypt_filter(&mut stream.dict);
}
}
target.set(copy, object)?;
}
for (root, ©) in roots.iter().zip(&copies) {
target.set(copy, Object::Dict(self.rewrite_dict(root)))?;
}
Ok(copies)
}
#[must_use]
pub fn copy_of(&self, source: ObjRef) -> Option<Copied> {
self.copies.get(&source).copied()
}
#[must_use]
pub const fn outside(&self) -> &BTreeSet<ObjRef> {
&self.outside
}
fn walk(&self, roots: &[Dict], root_refs: BTreeSet<ObjRef>) -> Result<Walk> {
let mut walk = Walk {
roots: root_refs,
..Walk::default()
};
let mut queue = VecDeque::new();
for root in roots {
self.scan_dict(root, None, 0, &mut queue)?;
walk.annots.extend(self.annots(root)?);
}
while let Some(r) = queue.pop_front() {
if walk.roots.contains(&r)
|| matches!(self.copies.get(&r), Some(Copied::Object(_)))
|| walk.objects.contains_key(&r)
|| walk.nulls.contains(&r)
{
continue;
}
let object = self.source.resolve(r)?;
if matches!(*object, Object::Null) {
walk.nulls.insert(r);
continue;
}
if !walk.annots.contains(&r) && self.is_outside(&object, &walk.roots)? {
walk.outside.insert(r);
walk.nulls.insert(r);
continue;
}
match &*object {
Object::Stream(stream) => {
walk.bytes = walk.bytes.saturating_add(stream.data.len());
if walk.bytes > self.limits.max_decoded_total() {
return Err(limit(Limit::DecodedTotal, None));
}
self.scan_dict(&stream.dict, Some(r), 1, &mut queue)?;
}
other => self.scan(other, Some(r), 0, &mut queue)?,
}
walk.order.push((r, Arc::clone(&object)));
walk.objects.insert(r, object);
}
Ok(walk)
}
fn annots(&self, page: &Dict) -> Result<Vec<ObjRef>> {
let Some(annots) = page.get("Annots") else {
return Ok(Vec::new());
};
let annots = self.source.deref(annots)?;
Ok(annots
.as_array()
.map(|items| items.iter().filter_map(Object::as_ref).collect())
.unwrap_or_default())
}
fn is_outside(&self, object: &Object, roots: &BTreeSet<ObjRef>) -> Result<bool> {
let Some(dict) = object.as_dict() else {
return Ok(false);
};
if is_page_tree_or_catalog(dict) {
return Ok(true);
}
let Some(page) = dict.get("P").and_then(Object::as_ref) else {
return Ok(false);
};
if roots.contains(&page) || matches!(self.copies.get(&page), Some(Copied::Object(_))) {
return Ok(false);
}
Ok(self
.source
.resolve(page)?
.as_dict()
.is_some_and(is_page_tree_or_catalog))
}
fn scan(&self, object: &Object, at: Option<ObjRef>, depth: usize, queue: &mut VecDeque<ObjRef>) -> Result<()> {
if depth > self.limits.max_nesting_depth() {
return Err(limit(Limit::NestingDepth, at.map(|r| Position::Object(r.num))));
}
match object {
Object::Ref(r) => queue.push_back(*r),
Object::Array(items) => {
for item in items {
self.scan(item, at, depth + 1, queue)?;
}
}
Object::Dict(dict) => self.scan_dict(dict, at, depth + 1, queue)?,
Object::Stream(stream) => self.scan_dict(&stream.dict, at, depth + 1, queue)?,
_ => {}
}
Ok(())
}
fn scan_dict(&self, dict: &Dict, at: Option<ObjRef>, depth: usize, queue: &mut VecDeque<ObjRef>) -> Result<()> {
for (_, value) in dict.iter() {
self.scan(value, at, depth, queue)?;
}
Ok(())
}
fn key_of(&mut self, r: ObjRef, walk: &Walk, stack: &mut Vec<ObjRef>) -> Result<Option<Key>> {
if let Some(&known) = self.keys.get(&r) {
return Ok(known);
}
if walk.nulls.contains(&r) || self.copies.get(&r) == Some(&Copied::Null) {
return Ok(Some(NULL_KEY));
}
let mut hash = Sha256::new();
if walk.roots.contains(&r) {
hash.update(b"page");
hash.update(r.num.to_be_bytes());
hash.update(r.gen_nr.to_be_bytes());
return Ok(Some(hash.finalize().into()));
}
if let Some(Copied::Object(copy)) = self.copies.get(&r) {
hash.update(b"copy");
hash.update(copy.num.to_be_bytes());
return Ok(Some(hash.finalize().into()));
}
let Some(object) = walk.objects.get(&r) else {
return Ok(None);
};
if stack.contains(&r) || stack.len() >= self.limits.max_resolve_depth() {
return Ok(None);
}
stack.push(r);
let keyed = self.feed(&mut hash, object, walk, stack, 0);
stack.pop();
let key = keyed?.then(|| hash.finalize().into());
self.keys.insert(r, key);
Ok(key)
}
fn feed(
&mut self,
hash: &mut Sha256,
object: &Object,
walk: &Walk,
stack: &mut Vec<ObjRef>,
depth: usize,
) -> Result<bool> {
if depth > self.limits.max_nesting_depth() {
return Ok(false);
}
match object {
Object::Null => put(hash, tag::NULL, &[]),
Object::Bool(b) => put(hash, tag::BOOL, &[u8::from(*b)]),
Object::Integer(i) => put(hash, tag::INTEGER, &i.to_be_bytes()),
Object::Real(f) => put(hash, tag::REAL, &f.to_bits().to_be_bytes()),
Object::String(s) => put(hash, tag::STRING, &s.bytes),
Object::Name(n) => put(hash, tag::NAME, n.as_bytes()),
Object::Ref(r) => match self.key_of(*r, walk, stack)? {
Some(key) => put(hash, tag::REFERENCE, &key),
None => return Ok(false),
},
Object::Array(items) => {
put(hash, tag::ARRAY, &(items.len() as u64).to_be_bytes());
for item in items {
if !self.feed(hash, item, walk, stack, depth + 1)? {
return Ok(false);
}
}
}
Object::Dict(dict) => return self.feed_dict(hash, dict, walk, stack, depth),
Object::Stream(stream) => {
if !self.feed_dict(hash, &stream.dict, walk, stack, depth)? {
return Ok(false);
}
put(hash, tag::STREAM_DATA, &stream.data);
}
}
Ok(true)
}
fn feed_dict(
&mut self,
hash: &mut Sha256,
dict: &Dict,
walk: &Walk,
stack: &mut Vec<ObjRef>,
depth: usize,
) -> Result<bool> {
put(hash, tag::DICT, &(dict.len() as u64).to_be_bytes());
for (name, value) in dict.iter() {
if name.as_bytes() == b"Length" {
continue;
}
put(hash, tag::NAME, name.as_bytes());
if !self.feed(hash, value, walk, stack, depth + 1)? {
return Ok(false);
}
}
Ok(true)
}
fn rewrite(&self, object: &Object) -> Object {
match object {
Object::Ref(r) => self.copies.get(r).map_or(Object::Null, |copied| copied.reference()),
Object::Array(items) => Object::Array(items.iter().map(|item| self.rewrite(item)).collect()),
Object::Dict(dict) => Object::Dict(self.rewrite_dict(dict)),
Object::Stream(stream) => {
let mut copy = stream.clone();
copy.dict = self.rewrite_dict(&stream.dict);
Object::Stream(copy)
}
other => other.clone(),
}
}
fn rewrite_dict(&self, dict: &Dict) -> Dict {
let mut copy = Dict::new();
for (name, value) in dict.iter() {
copy.insert(name.clone(), self.rewrite(value));
}
copy
}
}
fn page_dict(page: &laminapdf_cos::Page) -> Dict {
let mut dict = page.dict.clone();
dict.remove("Parent");
for (key, value) in page.inherited.entries() {
if let Some(value) = value
&& matches!(dict.get(key), None | Some(Object::Null))
{
dict.insert(key, (**value).clone());
}
}
dict
}
mod tag {
pub(super) const NULL: u8 = 0;
pub(super) const BOOL: u8 = 1;
pub(super) const INTEGER: u8 = 2;
pub(super) const REAL: u8 = 3;
pub(super) const STRING: u8 = 4;
pub(super) const NAME: u8 = 5;
pub(super) const REFERENCE: u8 = 6;
pub(super) const ARRAY: u8 = 7;
pub(super) const DICT: u8 = 8;
pub(super) const STREAM_DATA: u8 = 9;
}
fn is_page_tree_or_catalog(dict: &Dict) -> bool {
let Some(Object::Name(kind)) = dict.get("Type") else {
return false;
};
matches!(kind.as_bytes(), b"Page" | b"Pages" | b"Catalog")
}
fn put(hash: &mut Sha256, tag: u8, data: &[u8]) {
hash.update([tag]);
hash.update((data.len() as u64).to_be_bytes());
hash.update(data);
}
fn limit(limit: Limit, at: Option<Position>) -> Error {
Error::LimitExceeded { limit, at }
}