Read file-backed PDF objects at their actual write boundary

This commit is contained in:
gloamxun committed 2026-11-21 01:02:40 +08:00
1 parent 4f4a4567ea
commit a958954308
5 files changed
+139 -17

No files matched your search

@@ -12,7 +12,15 @@ use std::{
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) enum ObjectBody {
Direct(Vec<u8>),
Stream { attributes: Vec<u8>, bytes: Vec<u8> },
Stream {
attributes: Vec<u8>,
bytes: Vec<u8>,
},
File {
attributes: Option<Vec<u8>>,
name: String,
from: String,
},
}
impl ObjectBody {
@@ -20,12 +28,22 @@ impl ObjectBody {
match self {
Self::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
Self::File {
attributes,
name,
from,
} => attributes
.as_ref()
.map_or(0, Vec::len)
.saturating_add(name.len())
.saturating_add(from.len()),
}
}
fn parse(&self) -> Result<Object, String> {
match self {
Self::Direct(bytes) => parse_value(bytes),
Self::File { .. } => Err("PDF object file payload was not read before export".into()),
Self::Stream { attributes, bytes } => {
let mut dictionary = parse_entries(attributes)?;
if dictionary.has(b"Length") {
@@ -89,8 +107,29 @@ impl PdfObjects {
Ok(number)
}
pub(crate) fn write(&mut self, number: u32) -> Result<(), String> {
self.body(number)?;
pub(crate) fn unwritten(&self, number: u32) -> Result<Option<&ObjectBody>, String> {
if self.written.contains(&number) {
Ok(None)
} else {
self.body(number).map(Some)
}
}
pub(crate) fn write(
&mut self,
number: u32,
materialized: Option<ObjectBody>,
limit: usize,
) -> Result<(), String> {
let old = self.body(number)?;
if let Some(value) = materialized {
let bytes = (self.bytes - old.len()).saturating_add(value.len());
if bytes > limit {
return Err("native PDF object payload capacity exceeded".into());
}
self.values[number as usize - 1] = Some(Arc::new(value));
self.bytes = bytes;
}
self.written.insert(number);
Ok(())
}