laminapdf-model 0.9.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
//! Name trees and number trees (ISO 32000-2 §7.9.6, §7.9.7): lookup and ordered iteration.
//!
//! Both walks are iterative and tolerant: a kid that is missing, malformed, reached twice or
//! deeper than [`Limits::max_tree_depth`](laminapdf_cos::Limits::max_tree_depth) is skipped with
//! [`Warning::NameTreeNodeSkipped`]; so is a key of the wrong type. `/Limits` is only used to
//! prune a lookup, and only when it is well formed; a node without it is always searched.

use std::collections::BTreeSet;

use laminapdf_cos::{Object, Result, Warning};

use crate::document::{Document, object_number};

/// Which kind of tree: the key array's name and how to read a key.
trait TreeKind {
    type Key: Ord + Clone;
    const ENTRIES: &'static str;
    fn key(obj: &Object) -> Option<Self::Key>;
}

struct Names;
struct Nums;

impl TreeKind for Names {
    type Key = Vec<u8>;
    const ENTRIES: &'static str = "Names";
    fn key(obj: &Object) -> Option<Vec<u8>> {
        match obj {
            Object::String(s) => Some(s.bytes.clone()),
            // Some writers use names; accept them (they are byte strings too).
            Object::Name(n) => Some(n.as_bytes().to_vec()),
            _ => None,
        }
    }
}

impl TreeKind for Nums {
    type Key = i64;
    const ENTRIES: &'static str = "Nums";
    fn key(obj: &Object) -> Option<i64> {
        obj.as_int()
    }
}

/// One entry of a tree, with where it is stored.
pub(crate) struct Located<K> {
    pub(crate) key: K,
    pub(crate) value: Object,
    /// The node that holds it, as its parent (or the tree's holder) names it: a reference, or
    /// the node's dictionary when it is direct.
    pub(crate) node: Object,
    /// The value's index in the node's `/Names` or `/Nums` array.
    pub(crate) index: usize,
}

/// Walks the tree at `root` in tree order, collecting every entry, or (with `target`)
/// stopping at the first entry with that key. A lookup skips a node whose well-formed
/// `/Limits` excludes the key once it reaches that node, so kids are never read ahead.
fn walk<K: TreeKind>(doc: &Document, root: &Object, target: Option<&K::Key>) -> Result<Vec<(K::Key, Object)>> {
    Ok(walk_located::<K>(doc, root, target)?
        .into_iter()
        .map(|e| (e.key, e.value))
        .collect())
}

/// [`walk`], keeping where each entry is stored.
fn walk_located<K: TreeKind>(doc: &Document, root: &Object, target: Option<&K::Key>) -> Result<Vec<Located<K::Key>>> {
    let max_depth = doc.limits().max_tree_depth();
    let mut visited = BTreeSet::new();
    let mut stack = vec![(root.clone(), 0usize)];
    let mut out = Vec::new();
    while let Some((node_obj, depth)) = stack.pop() {
        let skip = || {
            doc.warn(Warning::NameTreeNodeSkipped {
                object: object_number(&node_obj),
            })
        };
        if depth > max_depth {
            skip()?;
            continue;
        }
        if let Some(r) = node_obj.as_ref()
            && !visited.insert(r.num)
        {
            skip()?;
            continue;
        }
        let Some(node) = doc.read(&node_obj)? else {
            skip()?;
            continue;
        };
        let Some(node) = node.as_dict() else {
            skip()?;
            continue;
        };
        if let Some(target) = target
            && !within_limits::<K>(doc, node, target)?
        {
            continue;
        }
        if let Some(entries) = node.get(K::ENTRIES) {
            let entries = doc.read(entries)?;
            match entries.as_deref().and_then(Object::as_array) {
                Some(items) => {
                    let (pairs, rest) = items.as_chunks::<2>();
                    for (pair, [key, value]) in pairs.iter().enumerate() {
                        let key = doc.read(key)?.and_then(|k| K::key(&k));
                        let located = |key| Located {
                            key,
                            value: value.clone(),
                            node: node_obj.clone(),
                            index: pair * 2 + 1,
                        };
                        match key {
                            Some(key) if target == Some(&key) => return Ok(vec![located(key)]),
                            Some(key) if target.is_none() => out.push(located(key)),
                            Some(_) => {}
                            None => skip()?,
                        }
                    }
                    if !rest.is_empty() {
                        skip()?;
                    }
                }
                None => skip()?,
            }
        }
        if let Some(kids) = node.get("Kids") {
            let kids = doc.read(kids)?;
            let Some(kids) = kids.as_deref().and_then(Object::as_array) else {
                skip()?;
                continue;
            };
            stack.extend(kids.iter().rev().map(|kid| (kid.clone(), depth + 1)));
        }
    }
    Ok(out)
}

/// False only when `node` has a well-formed `/Limits` that excludes `target`.
fn within_limits<K: TreeKind>(doc: &Document, node: &laminapdf_cos::Dict, target: &K::Key) -> Result<bool> {
    let Some(limits) = node.get("Limits") else {
        return Ok(true);
    };
    let Some(limits) = doc.read(limits)? else {
        return Ok(true);
    };
    let bounds = match limits.as_array() {
        Some([lo, hi]) => (doc.read(lo)?, doc.read(hi)?),
        _ => return Ok(true),
    };
    match bounds {
        (Some(lo), Some(hi)) => match (K::key(&lo), K::key(&hi)) {
            (Some(lo), Some(hi)) if lo <= hi => Ok(lo <= *target && *target <= hi),
            _ => Ok(true),
        },
        _ => Ok(true),
    }
}

/// A name tree (§7.9.6): string keys, in tree order, mapped to values.
///
/// Added in 0.2.0.
#[derive(Debug, Clone)]
pub struct NameTree<'d> {
    doc: &'d Document,
    root: Object,
}

impl<'d> NameTree<'d> {
    /// The name tree rooted at `root` (a dictionary or a reference to one).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn new(doc: &'d Document, root: Object) -> Self {
        Self { doc, root }
    }

    /// The value stored under `key` (as stored: often a reference), if any. When the tree
    /// holds the key twice, the first in tree order wins.
    ///
    /// # Errors
    /// [`laminapdf_cos::Error::Strict`] in strict mode when a node is skipped;
    /// [`laminapdf_cos::Error::DataPending`] / [`laminapdf_cos::Error::Source`].
    ///
    /// Added in 0.2.0.
    pub fn get(&self, key: &[u8]) -> Result<Option<Object>> {
        let key = key.to_vec();
        Ok(walk::<Names>(self.doc, &self.root, Some(&key))?
            .into_iter()
            .next()
            .map(|(_, v)| v))
    }

    /// Every entry in tree order (which ISO 32000 requires to be sorted by key).
    ///
    /// # Errors
    /// As [`NameTree::get`].
    ///
    /// Added in 0.2.0.
    pub fn entries(&self) -> Result<Vec<(Vec<u8>, Object)>> {
        walk::<Names>(self.doc, &self.root, None)
    }

    /// [`NameTree::entries`], each with the node that holds it.
    pub(crate) fn located_entries(&self) -> Result<Vec<Located<Vec<u8>>>> {
        walk_located::<Names>(self.doc, &self.root, None)
    }

    /// The tree's root, as its holder names it.
    pub(crate) const fn root(&self) -> &Object {
        &self.root
    }
}

/// A number tree (§7.9.7): integer keys, in tree order, mapped to values.
///
/// Added in 0.2.0.
#[derive(Debug, Clone)]
pub struct NumberTree<'d> {
    doc: &'d Document,
    root: Object,
}

impl<'d> NumberTree<'d> {
    /// The number tree rooted at `root` (a dictionary or a reference to one).
    ///
    /// Added in 0.2.0.
    #[must_use]
    pub const fn new(doc: &'d Document, root: Object) -> Self {
        Self { doc, root }
    }

    /// The value stored under `key` (as stored), if any; the first in tree order wins.
    ///
    /// # Errors
    /// As [`NameTree::get`].
    ///
    /// Added in 0.2.0.
    pub fn get(&self, key: i64) -> Result<Option<Object>> {
        Ok(walk::<Nums>(self.doc, &self.root, Some(&key))?
            .into_iter()
            .next()
            .map(|(_, v)| v))
    }

    /// Every entry in tree order (which ISO 32000 requires to be sorted by key).
    ///
    /// # Errors
    /// As [`NameTree::get`].
    ///
    /// Added in 0.2.0.
    pub fn entries(&self) -> Result<Vec<(i64, Object)>> {
        walk::<Nums>(self.doc, &self.root, None)
    }

    /// The value stored under `key` and the node whose `/Nums` holds it: a reference to the
    /// node, or the node itself when it is direct (a root given as a dictionary). An editor
    /// changes one entry there instead of writing the tree again.
    ///
    /// # Errors
    /// As [`NameTree::get`].
    ///
    /// Added in 0.6.0.
    pub fn locate(&self, key: i64) -> Result<Option<(Object, Object)>> {
        Ok(walk_located::<Nums>(self.doc, &self.root, Some(&key))?
            .into_iter()
            .next()
            .map(|e| (e.value, e.node)))
    }
}