Skip to content

Commit

Permalink
add Lazy struct to prevent parsing unneeded objects (that may error)
Browse files Browse the repository at this point in the history
  • Loading branch information
s3bk committed Mar 15, 2024
1 parent bf26151 commit 28c9200
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 5 deletions.
3 changes: 2 additions & 1 deletion examples/src/bin/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ fn run() -> Result<(), PdfError> {
let resources = file.create(resources)?;

let page0 = file.get_page(0).unwrap();
for annot in &page0.annotations {
let annots = page0.annotations.load(&file.resolver()).expect("can't load annotations");
for annot in &annots {
if let Some(ref a) = annot.appearance_streams {
let normal = file.resolver().get(a.normal);
if let Ok(normal) = normal {
Expand Down
2 changes: 1 addition & 1 deletion pdf/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl CatalogBuilder {
lgi: page.lgi,
vp: page.vp,
other: page.other,
annotations: vec![]
annotations: Default::default(),
};
update.fulfill(promise, PagesNode::Leaf(page))?;
}
Expand Down
26 changes: 26 additions & 0 deletions pdf/src/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,32 @@ impl<T> PartialEq for MaybeRef<T> {
}
impl<T> Eq for MaybeRef<T> {}

#[derive(Debug, Clone, DataSize)]
pub struct Lazy<T> {
primitive: Primitive,
_marker: PhantomData<T>
}
impl<T: Object> Lazy<T> {
pub fn load(&self, resolve: &impl Resolve) -> Result<T> {
T::from_primitive(self.primitive.clone(), resolve)
}
}
impl<T: Object> Object for Lazy<T> {
fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> {
Ok(Self { primitive: p, _marker: PhantomData })
}
}
impl<T: ObjectWrite> ObjectWrite for Lazy<T> {
fn to_primitive(&self, update: &mut impl Updater) -> Result<Primitive> {
Ok(self.primitive.clone())
}
}
impl<T> Default for Lazy<T> {
fn default() -> Self {
Lazy { primitive: Primitive::Null, _marker: PhantomData }
}
}

//////////////////////////////////////
// Object for Primitives & other types
//////////////////////////////////////
Expand Down
6 changes: 3 additions & 3 deletions pdf/src/object/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,8 @@ pub struct Page {
#[pdf(key="VP")]
pub vp: Option<Primitive>,

#[pdf(key="Annots", default="vec![]")]
pub annotations: Vec<MaybeRef<Annot>>,
#[pdf(key="Annots")]
pub annotations: Lazy<Vec<MaybeRef<Annot>>>,

#[pdf(other)]
pub other: Dictionary,
Expand Down Expand Up @@ -326,7 +326,7 @@ impl Page {
lgi: None,
vp: None,
other: Dictionary::new(),
annotations: vec![]
annotations: Default::default(),
}
}
pub fn media_box(&self) -> Result<Rectangle> {
Expand Down

0 comments on commit 28c9200

Please sign in to comment.