use crate::PdfVersion;
use crate::graph::ObjectGraph;
use crate::object::{ObjId, Object};
use crate::span::ByteSpan;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamSource<'a> {
Contiguous(&'a [u8]),
Split {
base: &'a [u8],
staged: &'a [u8],
},
}
impl<'a> StreamSource<'a> {
#[must_use]
pub fn slice(&self, span: ByteSpan) -> Option<&'a [u8]> {
match *self {
Self::Contiguous(buf) => span.slice(buf),
Self::Split { base, staged } => {
if span.start >= base.len() {
let local = span.start.checked_sub(base.len())?;
ByteSpan::new(local, span.len).slice(staged)
} else if span.end() <= base.len() {
span.slice(base)
} else {
None
}
}
}
}
#[must_use]
pub const fn len(&self) -> usize {
match *self {
Self::Contiguous(buf) => buf.len(),
Self::Split { base, staged } => base.len().saturating_add(staged.len()),
}
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub struct DocumentView<'a> {
graph: &'a dyn ObjectGraph,
source: StreamSource<'a>,
version: PdfVersion,
}
impl<'a> DocumentView<'a> {
#[must_use]
pub const fn new(graph: &'a dyn ObjectGraph, bytes: &'a [u8], version: PdfVersion) -> Self {
Self {
graph,
source: StreamSource::Contiguous(bytes),
version,
}
}
#[must_use]
pub const fn with_source(
graph: &'a dyn ObjectGraph,
source: StreamSource<'a>,
version: PdfVersion,
) -> Self {
Self {
graph,
source,
version,
}
}
#[must_use]
pub const fn graph(&self) -> &'a dyn ObjectGraph {
self.graph
}
#[must_use]
pub const fn source(&self) -> StreamSource<'a> {
self.source
}
#[must_use]
pub fn slice(&self, span: ByteSpan) -> Option<&'a [u8]> {
self.source.slice(span)
}
#[must_use]
pub const fn bytes(&self) -> Option<&'a [u8]> {
match self.source {
StreamSource::Contiguous(buf) => Some(buf),
StreamSource::Split { .. } => None,
}
}
#[must_use]
pub const fn version(&self) -> PdfVersion {
self.version
}
}
impl ObjectGraph for DocumentView<'_> {
fn value(&self, id: ObjId) -> Option<&Object> {
self.graph.value(id)
}
fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
self.graph.trailer_entry(key)
}
fn stream_raw(&self, stream: &crate::object::Stream) -> Option<&[u8]> {
self.slice(stream.data_span)
}
}
impl std::fmt::Debug for DocumentView<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DocumentView")
.field("version", &self.version)
.field("source", &self.source)
.field("source_len", &self.source.len())
.finish()
}
}
impl DocumentView<'_> {
#[must_use]
pub const fn clone_view(&self) -> DocumentView<'_> {
DocumentView::with_source(self.graph(), self.source(), self.version())
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
use crate::object::{Dict, Name};
use std::collections::BTreeMap;
struct TestGraph {
objects: BTreeMap<ObjId, Object>,
trailer: Dict,
}
impl ObjectGraph for TestGraph {
fn value(&self, id: ObjId) -> Option<&Object> {
self.objects.get(&id)
}
fn trailer_entry(&self, key: &[u8]) -> Option<&Object> {
self.trailer.get(key)
}
}
fn graph() -> TestGraph {
let mut objects = BTreeMap::new();
let mut catalog = Dict::new();
catalog.insert(Name::from(b"Type"), Object::Name(Name::from(b"Catalog")));
objects.insert(ObjId::new(1, 0), Object::Dict(catalog));
objects.insert(ObjId::new(2, 0), Object::Integer(7));
let mut trailer = Dict::new();
trailer.insert(Name::from(b"Root"), Object::Reference(ObjId::new(1, 0)));
TestGraph { objects, trailer }
}
#[test]
fn contiguous_source_slices_like_a_plain_buffer() {
let src = StreamSource::Contiguous(b"hello world");
assert_eq!(src.slice(ByteSpan::new(6, 5)), Some(&b"world"[..]));
assert_eq!(src.slice(ByteSpan::new(6, 99)), None);
assert_eq!(src.len(), 11);
}
#[test]
fn split_source_dispatches_on_the_base_length() {
let base = b"0123456789";
let staged = b"ABCDEF";
let src = StreamSource::Split { base, staged };
assert_eq!(src.slice(ByteSpan::new(2, 3)), Some(&b"234"[..]));
assert_eq!(src.slice(ByteSpan::new(0, 10)), Some(&base[..]));
assert_eq!(src.slice(ByteSpan::new(10, 6)), Some(&b"ABCDEF"[..]));
assert_eq!(src.slice(ByteSpan::new(13, 2)), Some(&b"DE"[..]));
assert_eq!(src.slice(ByteSpan::new(14, 9)), None);
assert_eq!(src.len(), 16);
}
#[test]
fn straddling_span_is_refused_not_spliced() {
let base = b"0123456789";
let staged = b"ABCDEF";
let src = StreamSource::Split { base, staged };
assert_eq!(src.slice(ByteSpan::new(9, 3)), None);
assert_eq!(src.slice(ByteSpan::new(0, 16)), None);
assert_eq!(src.slice(ByteSpan::new(9, 1)), Some(&b"9"[..]));
assert_eq!(src.slice(ByteSpan::new(10, 1)), Some(&b"A"[..]));
}
#[test]
fn empty_span_at_the_boundary_is_served_not_refused() {
let src = StreamSource::Split {
base: b"0123456789",
staged: b"ABCDEF",
};
assert_eq!(src.slice(ByteSpan::new(10, 0)), Some(&b""[..]));
}
#[test]
fn split_with_empty_staging_matches_contiguous() {
let base = b"0123456789";
let split = StreamSource::Split { base, staged: b"" };
let contiguous = StreamSource::Contiguous(base);
for start in 0..base.len() {
for len in 0..=(base.len() - start) {
let span = ByteSpan::new(start, len);
assert_eq!(split.slice(span), contiguous.slice(span), "{span}");
}
}
}
#[test]
fn the_view_delegates_every_graph_question() {
let g = graph();
let view = DocumentView::new(&g, b"", PdfVersion { major: 1, minor: 7 });
assert_eq!(view.value(ObjId::new(2, 0)), Some(&Object::Integer(7)));
assert_eq!(view.resolved(ObjId::new(2, 0)), &Object::Integer(7));
assert_eq!(view.catalog_id(), Some(ObjId::new(1, 0)));
assert!(view.catalog_dict().is_some());
assert_eq!(view.resolved(ObjId::new(99, 0)), &Object::Null);
}
#[test]
fn bytes_is_none_for_a_split_view() {
let g = graph();
let contiguous = DocumentView::new(&g, b"abc", PdfVersion { major: 1, minor: 7 });
assert_eq!(contiguous.bytes(), Some(&b"abc"[..]));
let split = DocumentView::with_source(
&g,
StreamSource::Split {
base: b"abc",
staged: b"de",
},
PdfVersion { major: 1, minor: 7 },
);
assert_eq!(
split.bytes(),
None,
"a split view has no single buffer; answering with one would be the X5 mis-slice"
);
assert_eq!(split.slice(ByteSpan::new(3, 2)), Some(&b"de"[..]));
}
}