1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//! 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)))
}
}