use crate::{Object, ObjectRef};
use std::collections::{BTreeMap, VecDeque};
use std::ops::Index;
use std::sync::OnceLock;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct OutlineId(pub(crate) usize);
#[derive(Debug, Clone, PartialEq)]
pub struct OutlineItem {
pub source_ref: Option<ObjectRef>,
pub parent: Option<OutlineId>,
pub kids: Vec<OutlineId>,
pub object: Object,
pub title: String,
pub count: i32,
pub dest: Object,
}
impl OutlineItem {
pub fn dest_page(&self) -> Object {
match &self.dest {
Object::Array(items) if !items.is_empty() => items[0].clone(),
_ => Object::Null,
}
}
}
#[derive(Debug)]
pub struct OutlineTree {
pub(crate) items: Vec<OutlineItem>,
pub(crate) roots: Vec<OutlineId>,
by_page: OnceLock<BTreeMap<Option<ObjectRef>, Vec<OutlineId>>>,
}
impl OutlineTree {
pub(crate) fn new() -> Self {
Self {
items: Vec::new(),
roots: Vec::new(),
by_page: OnceLock::new(),
}
}
fn normalize_page_key(page: Option<ObjectRef>) -> Option<ObjectRef> {
page.filter(|reference| *reference != ObjectRef::new(0, 0))
}
fn page_key(item: &OutlineItem) -> Option<ObjectRef> {
match item.dest_page() {
Object::Reference(reference) => Self::normalize_page_key(Some(reference)),
_ => None,
}
}
fn by_page(&self) -> &BTreeMap<Option<ObjectRef>, Vec<OutlineId>> {
self.by_page.get_or_init(|| {
let mut index = BTreeMap::<Option<ObjectRef>, Vec<OutlineId>>::new();
let mut queue: VecDeque<OutlineId> = self.roots.iter().copied().collect();
while let Some(id) = queue.pop_front() {
index.entry(Self::page_key(&self[id])).or_default().push(id);
queue.extend(self[id].kids.iter().copied());
}
index
})
}
pub fn outlines_for_page(
&self,
page: Option<ObjectRef>,
) -> impl Iterator<Item = (OutlineId, &OutlineItem)> {
self.by_page()
.get(&Self::normalize_page_key(page))
.into_iter()
.flatten()
.copied()
.map(|id| (id, &self[id]))
}
pub fn roots(&self) -> &[OutlineId] {
&self.roots
}
pub fn get(&self, id: OutlineId) -> Option<&OutlineItem> {
self.items.get(id.0)
}
pub fn preorder(&self) -> OutlineTreeIter<'_> {
OutlineTreeIter {
tree: self,
stack: self.roots.iter().rev().map(|&id| (1, id)).collect(),
}
}
}
impl Index<OutlineId> for OutlineTree {
type Output = OutlineItem;
fn index(&self, id: OutlineId) -> &Self::Output {
&self.items[id.0]
}
}
pub struct OutlineTreeIter<'a> {
tree: &'a OutlineTree,
stack: Vec<(usize, OutlineId)>,
}
impl<'a> Iterator for OutlineTreeIter<'a> {
type Item = (usize, OutlineId, &'a OutlineItem);
fn next(&mut self) -> Option<Self::Item> {
let (depth, id) = self.stack.pop()?;
let item = &self.tree[id];
self.stack
.extend(item.kids.iter().rev().map(|&kid| (depth + 1, kid)));
Some((depth, id, item))
}
}