use super::{Book, Chapter, Diagram, Formula, Landmark, Picture, Toc, TocItem};
use crate::container;
use crate::error::{Error, Result};
use crate::format::{CONTAINER_MAGIC, FORMAT, SERVICE_COUNT};
use crate::index::Index;
use crate::options::ReadOptions;
use mopenzl::TypedOutput;
use std::io::{Cursor, Read};
use std::path::Path;
impl Book {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::read(std::fs::File::open(path)?)
}
pub fn read(reader: impl Read) -> Result<Self> {
Self::read_with(reader, &ReadOptions::default())
}
pub fn read_with(mut reader: impl Read, options: &ReadOptions) -> Result<Self> {
let limits = options.limits;
let mut signature = Vec::with_capacity(CONTAINER_MAGIC.len());
let wanted = u64::try_from(CONTAINER_MAGIC.len()).unwrap_or(u64::MAX);
reader.by_ref().take(wanted).read_to_end(&mut signature)?;
if signature != CONTAINER_MAGIC {
return Err(Error::NotMbook);
}
let mut decoder = container::decoder(&limits, limits.max_file_bytes)?;
let mut resources = decoder.framed_reader(Cursor::new(signature).chain(reader));
let mut version = None;
let mut service = Vec::with_capacity(SERVICE_COUNT);
let mut contents = Vec::new();
let mut decoded_lens = Vec::new();
while let Some(resource) = resources.read_resource().map_err(container::error)? {
decoded_lens.push(resource.info.decoded_size);
if service.len() < SERVICE_COUNT {
if service.is_empty() {
version = Some(container::header(&resource.outputs)?);
}
service.push(resource.outputs);
contents.push(Vec::new());
} else {
contents.push(resource.outputs);
}
}
let version = version.ok_or(Error::NotMbook)?;
let [_, meta, table, toc, anchors] = service.as_slice() else {
return Err(Error::Malformed {
resource: FORMAT,
reason: "the file has fewer than five resources",
});
};
let index = Index::from_outputs(version, [meta, table, toc, anchors], &decoded_lens)?;
Self::assemble(&index, |number| {
let outputs = usize::try_from(number)
.ok()
.and_then(|at| contents.get_mut(at))
.map(std::mem::take);
Ok(outputs.unwrap_or_default())
})
}
pub(crate) fn assemble(
index: &Index,
mut outputs: impl FnMut(u32) -> Result<Vec<TypedOutput>>,
) -> Result<Self> {
let mut book = Self::empty(index.meta().clone());
for entry in index.chapters() {
let number = entry.id.number();
let table = index.anchor_table(number);
let extra_anchors = match table {
Some(table) => index.read_extra_anchors(number, table, &outputs(table)?)?,
None => Vec::new(),
};
let text = index.text(number, container::serial(number, outputs(number)?)?)?;
if let Some(table) = table {
Index::check_extra_positions(table, &extra_anchors, &text)?;
}
let chapter = Chapter {
path: entry.path.to_owned(),
text,
anchors: index.anchors(number).to_vec(),
extra_anchors,
};
book.place_chapter(book.chapters.len(), chapter);
}
for entry in index.pictures() {
let number = entry.id.number();
book.place_picture(Picture {
path: entry.path.to_owned(),
size: entry.size,
data: container::serial(number, outputs(number)?)?,
});
}
for entry in index.diagrams() {
let number = entry.id.number();
let source = Index::source(number, container::serial(number, outputs(number)?)?)?;
book.place_diagram(Diagram {
path: entry.path.to_owned(),
source,
});
}
for entry in index.formulas() {
let number = entry.id.number();
let source = Index::source(number, container::serial(number, outputs(number)?)?)?;
book.place_formula(Formula {
path: entry.path.to_owned(),
source,
});
}
book.toc = Toc::Explicit(
index
.toc()
.iter()
.map(|entry| toc_item(index, entry))
.collect(),
);
if let Some(table) = index.landmarks_table() {
for entry in index.read_landmarks(table, &outputs(table)?)? {
let position = entry.position;
let chapter = index
.chapter(position.chapter)
.and_then(|chapter| book.chapter(chapter.path));
let anchor = chapter.and_then(|chapter| {
let anchors = chapter.anchors.iter().chain(&chapter.extra_anchors);
anchors
.clone()
.find(|anchor| anchor.offset == position.offset)
.map(|anchor| anchor.name.clone())
});
if position.offset != 0 && anchor.is_none() {
return Err(Error::Malformed {
resource: table,
reason: "a row inside a chapter has no anchor",
});
}
book.landmarks.push(Landmark {
kind: entry.kind,
title: entry.title,
chapter: chapter.map_or_else(String::new, |chapter| chapter.path.clone()),
anchor: anchor.filter(|_| position.offset != 0),
});
}
}
Ok(book)
}
}
fn toc_item(index: &Index, entry: &crate::types::TocEntry) -> TocItem {
let position = entry.position;
let chapter = index.chapter(position.chapter);
let anchor = (position.offset != 0)
.then(|| index.anchors(position.chapter.number()))
.and_then(|anchors| {
anchors
.iter()
.find(|anchor| anchor.offset == position.offset)
})
.map(|anchor| anchor.name.clone());
TocItem {
level: entry.level,
title: entry.title.clone(),
chapter: chapter.map_or_else(String::new, |chapter| chapter.path.to_owned()),
anchor,
}
}