use super::output::{
decimal_u64_len, write_decimal_i64, write_decimal_u64, write_object_ref, OutputSink,
};
use crate::object_handle::{LiveDictionaryKeyBuffer, ObjectHandle, ObjectValue};
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::{Error, ObjectRef, Result};
use std::collections::BTreeSet;
#[allow(dead_code)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TrailerKind {
Normal { size: i64 },
LinearizedFirst { size: i64, prev: u64 },
LinearizedSecond { size: i64 },
}
pub(crate) const TRIMMED_TRAILER_KEYS: &[&[u8]] = &[
b"/ID",
b"/Encrypt",
b"/Prev",
b"/Index",
b"/W",
b"/Length",
b"/Filter",
b"/DecodeParms",
b"/Type",
b"/XRefStm",
];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct StreamDictionaryOptions {
pub(crate) remove_filter_parameters: bool,
pub(crate) add_flate_filter: bool,
}
impl StreamDictionaryOptions {
pub(crate) const fn new(remove_filter_parameters: bool, add_flate_filter: bool) -> Self {
Self {
remove_filter_parameters,
add_flate_filter,
}
}
pub(crate) const fn preserve() -> Self {
Self::new(false, false)
}
pub(crate) const fn from_refiltered(refiltered: bool) -> Self {
Self::new(refiltered, refiltered)
}
}
#[allow(dead_code)]
pub(crate) trait ObjectWriterEmission {
fn unparse_object(&self, out: &mut OutputSink<'_>) -> Result<()>;
#[cfg(test)]
fn unparse_object_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[cfg(test)]
fn unparse_object_qdf(&self, out: &mut OutputSink<'_>, indent: usize) -> Result<()>;
fn unparse_object_qdf_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_object_qdf_with_qpdf_obj_gen_map_and_removed(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()>;
#[cfg(test)]
fn unparse_object_qdf_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_object_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_object_with_qpdf_obj_gen_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()>;
#[cfg(test)]
fn unparse_root_object_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<()>;
fn output_root_copy_with_adbe(
&self,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<ObjectHandle> {
let _ = (
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
);
Err(Error::Internal(
"root output copy is unavailable for this emission owner".into(),
))
}
fn unparse_object_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let _ = (out, map, removed_refs);
Err(Error::Internal(
"dynamic writer map is unavailable for this emission owner".into(),
))
}
fn unparse_root_object_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<()> {
let _ = (
out,
map,
removed_refs,
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
);
Err(Error::Internal(
"dynamic root writer map is unavailable for this emission owner".into(),
))
}
fn unparse_stream_body_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let _ = (out, options, map, removed_refs);
Err(Error::Internal(
"dynamic stream writer map is unavailable for this emission owner".into(),
))
}
#[allow(clippy::type_complexity)]
fn unparse_stream_body_with_dynamic_ref_map_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized;
fn unparse_object_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_object_with_qpdf_obj_gen_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_object_qdf_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_object_qdf_with_qpdf_obj_gen_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_stream_body(&self, out: &mut OutputSink<'_>, refiltered: bool) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_qdf(&self, out: &mut OutputSink<'_>, indent: usize) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
) -> Result<()>;
fn unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[allow(clippy::too_many_arguments)]
fn unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_string_writer_with_options<
F,
>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[allow(clippy::too_many_arguments)]
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer_with_options<
F,
>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_qdf_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body_with_ref_map_and_removed_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()>;
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length: usize,
) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_and_length(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length: usize,
) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length: usize,
) -> Result<()>;
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_stream_body_with_ref_map_and_removed_with_options_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>;
#[cfg(test)]
fn write_trailer(
&self,
out: &mut OutputSink<'_>,
xref_stream: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
) -> Result<()>;
#[allow(clippy::too_many_arguments)]
fn write_trailer_with_ref_map(
&self,
out: &mut OutputSink<'_>,
xref_stream: bool,
qdf: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()>;
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)] fn write_trailer_with_ref_map_and_kind(
&self,
out: &mut OutputSink<'_>,
kind: TrailerKind,
xref_stream: bool,
qdf: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()>;
#[cfg(test)]
fn write_dictionary_with_ref_map_and_id_writer(
&self,
out: &mut OutputSink<'_>,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()>;
fn write_id_value_with_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn write_id_value_with_qpdf_obj_gen_map(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()>;
}
#[cfg(test)]
pub(crate) trait ObjectWriterEmissionVecTestExt {
fn unparse_object(&self, out: &mut Vec<u8>) -> Result<()>;
fn unparse_object_qdf(&self, out: &mut Vec<u8>, indent: usize) -> Result<()>;
fn unparse_object_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
fn unparse_object_qdf_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
fn unparse_object_with_ref_map_and_removed(
&self,
out: &mut Vec<u8>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body(&self, out: &mut Vec<u8>, refiltered: bool) -> Result<()>;
fn unparse_stream_body_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
refiltered: bool,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
fn unparse_stream_body_qdf(&self, out: &mut Vec<u8>, indent: usize) -> Result<()>;
fn unparse_stream_body_qdf_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
fn unparse_stream_body_with_ref_map_and_removed(
&self,
out: &mut Vec<u8>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length(
&self,
out: &mut Vec<u8>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
) -> Result<()>;
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>;
#[allow(clippy::type_complexity)] fn write_trailer(
&self,
out: &mut Vec<u8>,
xref_stream: bool,
id_writer: Option<&mut dyn FnMut(&mut Vec<u8>)>,
) -> Result<()>;
}
#[cfg(test)]
impl ObjectWriterEmissionVecTestExt for ObjectHandle {
fn unparse_object(&self, out: &mut Vec<u8>) -> Result<()> {
super::output::with_buffer_sink(out, |out| ObjectWriterEmission::unparse_object(self, out))
}
fn unparse_object_qdf(&self, out: &mut Vec<u8>, indent: usize) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_object_qdf(self, out, indent)
})
}
fn unparse_object_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_object_with_string_writer(self, out, &mut sink_writer)
})
}
fn unparse_object_qdf_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_object_qdf_with_string_writer(
self,
out,
indent,
&mut sink_writer,
)
})
}
fn unparse_object_with_ref_map_and_removed(
&self,
out: &mut Vec<u8>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_object_with_ref_map_and_removed(
self,
out,
map,
removed_refs,
)
})
}
fn unparse_stream_body(&self, out: &mut Vec<u8>, refiltered: bool) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body(self, out, refiltered)
})
}
fn unparse_stream_body_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
refiltered: bool,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_with_string_writer(
self,
out,
refiltered,
&mut sink_writer,
)
})
}
fn unparse_stream_body_qdf(&self, out: &mut Vec<u8>, indent: usize) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_qdf(self, out, indent)
})
}
fn unparse_stream_body_qdf_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_qdf_with_string_writer(
self,
out,
indent,
&mut sink_writer,
)
})
}
fn unparse_stream_body_with_ref_map_and_removed(
&self,
out: &mut Vec<u8>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_with_ref_map_and_removed(
self,
out,
refiltered,
map,
removed_refs,
)
})
}
fn unparse_stream_body_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_with_ref_map_and_removed_with_string_writer(
self,
out,
refiltered,
map,
removed_refs,
&mut sink_writer,
)
})
}
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length(
&self,
out: &mut Vec<u8>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
) -> Result<()> {
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_qdf_with_ref_map_and_removed_and_length(
self,
out,
indent,
map,
removed_refs,
length_ref,
)
})
}
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer<F>(
&self,
out: &mut Vec<u8>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut Vec<u8>, &[u8]) -> Result<()>,
{
let mut sink_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
let mut bytes = Vec::new();
write_string(&mut bytes, value)?;
out.write_bytes(&bytes)
};
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer(self, out, indent, map, removed_refs, length_ref, &mut sink_writer)
})
}
fn write_trailer(
&self,
out: &mut Vec<u8>,
xref_stream: bool,
mut id_writer: Option<&mut dyn FnMut(&mut Vec<u8>)>,
) -> Result<()> {
let has_id_writer = id_writer.is_some();
let mut sink_writer = |out: &mut OutputSink<'_>| {
let mut bytes = Vec::new();
if let Some(write_id) = id_writer.as_deref_mut() {
write_id(&mut bytes);
}
out.write_bytes(&bytes)
};
let sink_writer =
has_id_writer.then_some(&mut sink_writer as crate::pdf_syntax::TrailerIdWriter<'_>);
super::output::with_buffer_sink(out, |out| {
ObjectWriterEmission::write_trailer(self, out, xref_stream, sink_writer)
})
}
}
const UNPARSE_STACK_RED_ZONE: usize = 32 * 1024;
const UNPARSE_STACK_GROWTH_SIZE: usize = 1024 * 1024;
thread_local! {
static UNPARSE_WALK_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
struct UnparseWalkDepthGuard;
impl UnparseWalkDepthGuard {
#[deprecated(
note = "no qpdf counterpart; QPDFWriter::unparseObject has no upper nesting limit"
)]
fn enter() -> Result<Self> {
let depth = UNPARSE_WALK_DEPTH.with(|depth| {
let entered = depth.get();
depth.set(entered + 1);
entered
});
let guard = Self;
if depth > crate::parser::MAX_PARSE_DEPTH {
return Err(Error::Unsupported(format!(
"writer: direct object nesting exceeds maximum of {}",
crate::parser::MAX_PARSE_DEPTH
)));
}
Ok(guard)
}
}
impl Drop for UnparseWalkDepthGuard {
fn drop(&mut self) {
UNPARSE_WALK_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
}
}
#[allow(deprecated)]
fn unparse_object_walk_hub<T>(body: impl FnOnce() -> Result<T>) -> Result<T> {
let _depth = UnparseWalkDepthGuard::enter()?;
stacker::maybe_grow(UNPARSE_STACK_RED_ZONE, UNPARSE_STACK_GROWTH_SIZE, body)
}
fn reserved_unparse_error() -> Error {
Error::System("QPDFObjectHandle: attempting to unparse a reserved object".to_owned())
}
fn unresolved_unparse_error() -> Error {
Error::Internal("attempted to unparse an unresolved QPDFObjectHandle".to_owned())
}
fn destroyed_unparse_error() -> Error {
Error::Internal("attempted to unparse a QPDFObjectHandle from a destroyed QPDF".to_owned())
}
fn write_dictionary_key(out: &mut OutputSink<'_>, key: &[u8]) -> Result<()> {
if let Some(key) = key.strip_prefix(b"/") {
out.write_bytes(b"/")?;
crate::pdf_syntax::write_name_escaped(out, key)?;
} else {
crate::pdf_syntax::write_name_escaped(out, key)?;
}
Ok(())
}
fn write_qpdf_object_gen(out: &mut OutputSink<'_>, object_gen: QpdfObjGen) -> Result<()> {
write_decimal_i64(out, i64::from(object_gen.get_obj()))?;
out.write_bytes(b" ")?;
write_decimal_i64(out, i64::from(object_gen.get_gen()))?;
out.write_bytes(b" R")
}
impl ObjectWriterEmission for ObjectHandle {
fn unparse_object(&self, out: &mut OutputSink<'_>) -> Result<()> {
unparse_object_walk(self, out)
}
#[cfg(test)]
fn unparse_object_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_with_string_writer(self, out, write_string)
}
#[cfg(test)]
fn unparse_object_qdf(&self, out: &mut OutputSink<'_>, indent: usize) -> Result<()> {
unparse_object_walk_qdf(self, indent, out)
}
fn unparse_object_qdf_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_object_walk_qdf_with_ref_map(self, indent, out, &map, &removed_refs)
}
fn unparse_object_qdf_with_qpdf_obj_gen_map_and_removed(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_qdf_with_ref_map(self, indent, out, map, removed_refs)
}
#[cfg(test)]
fn unparse_object_qdf_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_qdf_with_string_writer(self, indent, out, write_string)
}
fn unparse_object_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_object_walk_with_ref_map(self, out, &map, &removed_refs)
}
fn unparse_object_with_qpdf_obj_gen_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_with_ref_map(self, out, map, removed_refs)
}
#[cfg(test)]
fn unparse_root_object_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<()> {
let root = root_output_copy_with_adbe(
self,
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
)?; let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_object_walk_with_ref_map(&root, out, &map, &removed_refs)
}
fn unparse_object_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
unparse_object_walk_with_dynamic_ref_map(self, out, map, removed_refs)
}
fn unparse_root_object_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<()> {
let root = root_output_copy_with_adbe(
self,
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
)?; unparse_object_walk_with_dynamic_ref_map(&root, out, map, removed_refs)
}
fn output_root_copy_with_adbe(
&self,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<ObjectHandle> {
root_output_copy_with_adbe(
self,
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
)
}
fn unparse_stream_body_with_dynamic_ref_map(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_with_dynamic_ref_map(&entries, options, out, map, removed_refs)
}
fn unparse_stream_body_with_dynamic_ref_map_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &mut dyn FnMut(&ObjectHandle) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_with_dynamic_ref_map_and_string_writer(
&entries,
options,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)
}
fn unparse_object_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_object_walk_with_ref_map_and_string_writer(
self,
out,
&map,
&removed_refs,
write_string,
)
}
fn unparse_object_with_qpdf_obj_gen_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_with_ref_map_and_string_writer(
self,
out,
map,
removed_refs,
write_string,
)
}
fn unparse_object_qdf_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_object_walk_qdf_with_ref_map_and_string_writer(
self,
indent,
out,
&map,
&removed_refs,
write_string,
)
}
fn unparse_object_qdf_with_qpdf_obj_gen_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_qdf_with_ref_map_and_string_writer(
self,
indent,
out,
map,
removed_refs,
write_string,
)
}
fn unparse_stream_body(&self, out: &mut OutputSink<'_>, refiltered: bool) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries(
&entries,
StreamDictionaryOptions::from_refiltered(refiltered),
out,
)
}
#[cfg(test)]
fn unparse_stream_body_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_with_string_writer(&entries, refiltered, out, write_string)
}
#[cfg(test)]
fn unparse_stream_body_qdf(&self, out: &mut OutputSink<'_>, indent: usize) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_qdf(&entries, indent, out)
}
#[cfg(test)]
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
) -> Result<()> {
self.unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_options(
out,
indent,
map,
removed_refs,
length_ref,
StreamDictionaryOptions::preserve(),
)
}
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_stream_dict_entries_qdf_with_ref_map(
&entries,
indent,
out,
&map,
&removed_refs,
length_ref,
options,
)
}
fn unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_qdf_with_ref_map(
&entries,
indent,
out,
map,
removed_refs,
length_ref,
options,
)
}
#[cfg(test)]
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
self.unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer_with_options(
out,
indent,
map,
removed_refs,
length_ref,
StreamDictionaryOptions::preserve(),
write_string,
)
}
fn unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer_with_options<
F,
>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_stream_dict_entries_qdf_with_ref_map_and_string_writer(
&entries,
indent,
out,
&map,
&removed_refs,
length_ref,
options,
write_string,
)
}
fn unparse_stream_body_qdf_with_qpdf_obj_gen_map_and_removed_and_length_with_string_writer_with_options<
F,
>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_qdf_with_ref_map_and_string_writer(
&entries,
indent,
out,
map,
removed_refs,
length_ref,
options,
write_string,
)
}
#[cfg(test)]
fn unparse_stream_body_qdf_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
indent: usize,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
self.with_value(|value| {
let entries = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
Some(ObjectValue::Stream(stream)) => {
stream.stream_dict.try_dereference()?;
stream
.stream_dict
.with_value(|dict_value| match dict_value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Vec::new(),
})
}
_ => Vec::new(),
};
unparse_stream_dict_entries_qdf_with_string_writer(&entries, indent, out, write_string)
})
}
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
self.unparse_stream_body_with_ref_map_and_removed_with_options(
out,
StreamDictionaryOptions::from_refiltered(refiltered),
map,
removed_refs,
)
}
fn unparse_stream_body_with_ref_map_and_removed_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_stream_dict_entries_with_ref_map(&entries, options, out, &map, &removed_refs)
}
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_with_ref_map(&entries, options, out, map, removed_refs)
}
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
length: usize,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
let is_dictionary =
self.with_value(|value| matches!(value, Some(ObjectValue::Dictionary(_))));
if !is_dictionary {
let entries = stream_dictionary_entries_for_emission(self)?;
return unparse_stream_dict_entries_with_ref_map_and_length(
&entries,
options,
out,
map,
removed_refs,
Some(length),
);
}
unparse_stream_dictionary_live_with_qpdf_obj_gen_map_and_removed_and_length(
self,
options,
out,
map,
removed_refs,
length,
)
}
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_and_length(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length: usize,
) -> Result<()> {
self.unparse_stream_body_with_ref_map_and_removed_and_length_with_options(
out,
StreamDictionaryOptions::from_refiltered(refiltered),
map,
removed_refs,
length,
)
}
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_and_length_with_options(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
length: usize,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_stream_dict_entries_with_ref_map_and_length(
&entries,
options,
out,
&map,
&removed_refs,
Some(length),
)
}
#[cfg(test)]
fn unparse_stream_body_with_ref_map_and_removed_with_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
refiltered: bool,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
self.unparse_stream_body_with_ref_map_and_removed_with_options_and_string_writer(
out,
StreamDictionaryOptions::from_refiltered(refiltered),
map,
removed_refs,
write_string,
)
}
fn unparse_stream_body_with_ref_map_and_removed_with_options_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
unparse_stream_dict_entries_with_ref_map_and_string_writer(
&entries,
options,
out,
&map,
&removed_refs,
write_string,
)
}
fn unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_string_writer<F>(
&self,
out: &mut OutputSink<'_>,
options: StreamDictionaryOptions,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if self.is_reserved() {
return Err(reserved_unparse_error());
}
let entries = stream_dictionary_entries_for_emission(self)?;
unparse_stream_dict_entries_with_ref_map_and_string_writer(
&entries,
options,
out,
map,
removed_refs,
write_string,
)
}
#[cfg(test)]
fn write_trailer(
&self,
out: &mut OutputSink<'_>,
xref_stream: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
self.with_value(|value| {
let entries: Vec<(Vec<u8>, ObjectHandle)> = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Vec::new(),
};
unparse_trailer_entries(&entries, xref_stream, id_writer, out)
})
}
#[allow(clippy::too_many_arguments)] fn write_trailer_with_ref_map(
&self,
out: &mut OutputSink<'_>,
xref_stream: bool,
qdf: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
self.with_value(|value| {
let entries: Vec<(Vec<u8>, ObjectHandle)> = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Vec::new(),
};
unparse_trailer_entries_with_ref_map(
&entries,
xref_stream,
qdf,
id_writer,
map,
removed_refs,
suppress_null_values,
out,
)
})
}
#[allow(clippy::too_many_arguments)]
fn write_trailer_with_ref_map_and_kind(
&self,
out: &mut OutputSink<'_>,
kind: TrailerKind,
xref_stream: bool,
qdf: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
self.with_value(|value| {
let entries: Vec<(Vec<u8>, ObjectHandle)> = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Vec::new(),
};
unparse_trailer_entries_with_ref_map_and_kind(
&entries,
kind,
xref_stream,
qdf,
id_writer,
map,
removed_refs,
suppress_null_values,
None,
out,
)
})
}
#[cfg(test)]
fn write_dictionary_with_ref_map_and_id_writer(
&self,
out: &mut OutputSink<'_>,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
) -> Result<()> {
if self.is_reserved() {
return Err(reserved_unparse_error());
}
self.try_dereference()?;
self.with_value(|value| {
let entries: Vec<(Vec<u8>, ObjectHandle)> = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
_ => Vec::new(),
};
unparse_dictionary_entries_with_ref_map_and_id_writer(
&entries,
id_writer,
map,
removed_refs,
suppress_null_values,
out,
)
})
}
fn write_id_value_with_ref_map(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let map = qpdf_obj_gen_map_from_object_ref_map(map);
let removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
write_id_style_value_handle_with_ref_map(self, out, &map, &removed_refs)
}
fn write_id_value_with_qpdf_obj_gen_map(
&self,
out: &mut OutputSink<'_>,
map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
write_id_style_value_handle_with_ref_map(self, out, map, removed_refs)
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_trailer_with_ref_map_and_kind_and_direct_root(
trailer: &ObjectHandle,
out: &mut OutputSink<'_>,
kind: TrailerKind,
xref_stream: bool,
qdf: bool,
id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
direct_root: &ObjectHandle,
) -> Result<()> {
if trailer.is_reserved() {
return Err(reserved_unparse_error());
}
trailer.try_dereference()?;
trailer.with_value(|value| {
let entries: Vec<(Vec<u8>, ObjectHandle)> = match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
_ => Vec::new(), };
unparse_trailer_entries_with_ref_map_and_kind(
&entries,
kind,
xref_stream,
qdf,
id_writer,
map,
removed_refs,
suppress_null_values,
Some(direct_root),
out,
)
})
}
fn prepare_stream_dict_entries(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
) -> Result<Vec<(Vec<u8>, ObjectHandle)>> {
let mut prepared: Vec<_> = entries.to_vec();
if let Some((index, value)) = prepared
.iter()
.enumerate()
.find(|(_, (key, _))| key.as_slice() == b"/DecodeParms")
{
if value.1.try_array_len()?.is_some_and(|length| length == 0) {
prepared.remove(index);
}
}
if options.remove_filter_parameters {
prepared
.retain(|(key, _)| key.as_slice() != b"/Filter" && key.as_slice() != b"/DecodeParms");
} else {
remove_crypt_filter_from_entries(&mut prepared)?;
}
Ok(prepared)
}
pub(crate) fn prepared_stream_dictionary_children(
dictionary: &ObjectHandle,
options: StreamDictionaryOptions,
) -> Result<Vec<ObjectHandle>> {
let entries = stream_dictionary_entries_for_emission(dictionary)?;
let discovery_entries = entries
.iter()
.map(|(key, value)| {
if matches!(key.as_slice(), b"/Filter" | b"/DecodeParms") {
value.try_dereference()?;
if let Some(items) = value.try_as_array()? {
return Ok((key.clone(), ObjectHandle::array(items)));
}
}
Ok((key.clone(), value.clone()))
})
.collect::<Result<Vec<_>>>()?;
let prepared = prepare_stream_dict_entries(&discovery_entries, options)?;
Ok(visible_dict_entries(&prepared)?
.into_iter()
.filter(|(key, _)| key.as_slice() != b"/Length")
.map(|(key, value)| {
if matches!(key.as_slice(), b"/Filter" | b"/DecodeParms") {
entries
.iter()
.find(|(original_key, _)| original_key.as_slice() == key.as_slice())
.map(|(_, original_value)| original_value.clone())
.unwrap_or_else(|| value.clone())
} else {
value.clone()
}
})
.collect())
}
fn remove_crypt_filter_from_entries(entries: &mut Vec<(Vec<u8>, ObjectHandle)>) -> Result<()> {
let Some(filter_index) = entries
.iter()
.position(|(key, _)| key.as_slice() == b"/Filter")
else {
return Ok(());
};
let filter = entries[filter_index].1.clone();
if filter.try_is_name_and_equals(b"Crypt")? {
entries.remove(filter_index);
entries.retain(|(key, _)| key.as_slice() != b"/DecodeParms");
return Ok(());
}
let Some(filters) = filter.try_as_array()? else {
return Ok(());
};
let mut crypt_index = None;
for (index, item) in filters.iter().enumerate() {
if item.try_is_name_and_equals(b"Crypt")? {
crypt_index = Some(index);
break;
}
}
let Some(crypt_index) = crypt_index else {
return Ok(());
};
filter.erase_array_item(crypt_index)?;
let Some(decode_index) = entries
.iter()
.position(|(key, _)| key.as_slice() == b"/DecodeParms")
else {
let output_dictionary = ObjectHandle::dictionary(
entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
);
let decode = output_dictionary.try_get_key(b"/DecodeParms")?;
decode.erase_array_item(crypt_index)?;
return Ok(()); };
let decode = entries[decode_index].1.clone();
decode.erase_array_item(crypt_index)?;
Ok(())
}
type StreamDictionaryEntries = Vec<(Vec<u8>, ObjectHandle)>;
fn stream_dictionary_entries_for_emission(
handle: &ObjectHandle,
) -> Result<StreamDictionaryEntries> {
handle.try_dereference()?;
if let Some(entries) = handle.with_value(|value| match value {
Some(ObjectValue::Dictionary(entries)) => Some(
entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
),
_ => None,
}) {
return Ok(entries);
}
let Some(stream_dict) = handle.with_value(|value| match value {
Some(ObjectValue::Stream(stream)) => Some(stream.stream_dict.clone()),
_ => None,
}) else {
return Ok(Vec::new());
};
stream_dict.try_dereference()?;
let entries = stream_dict.with_value(|value| match value {
Some(ObjectValue::Dictionary(entries)) => entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
_ => Vec::new(),
});
Ok(entries)
}
fn dictionary_entry_handle(dictionary: &ObjectHandle, key: &[u8]) -> Option<ObjectHandle> {
dictionary.with_value(|value| match value {
Some(ObjectValue::Dictionary(entries)) => entries.get(key).cloned(),
_ => None,
})
}
fn unparse_stream_dict_entries(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
) -> Result<()> {
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child(value, out)?;
}
}
if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child(length, out)?;
}
if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
#[cfg(test)]
fn unparse_stream_dict_entries_qdf(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
) -> Result<()> {
let entries = prepare_stream_dict_entries(entries, StreamDictionaryOptions::preserve())?;
out.write_bytes(b"<<\n")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_qdf(value, indent + 2, out)?;
}
out.write_bytes(b"\n")?;
}
if let Some(length) = length_value {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Length ")?;
unparse_child_qdf(length, indent + 2, out)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn unparse_stream_dict_entries_qdf_with_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
) -> Result<()> {
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<\n")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_qdf_with_ref_map(value, indent + 2, out, map, removed_refs)?;
}
out.write_bytes(b"\n")?;
}
if let Some(length_ref) = length_ref {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Length ")?;
write_object_ref(out, length_ref)?;
out.write_bytes(b"\n")?;
} else if let Some(length) = length_value {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Length ")?;
unparse_child_qdf_with_ref_map(length, indent + 2, out, map, removed_refs)?;
out.write_bytes(b"\n")?;
}
if options.add_flate_filter {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Filter /FlateDecode\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn unparse_stream_dict_entries_qdf_with_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_ref: Option<ObjectRef>,
options: StreamDictionaryOptions,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<\n")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if try_write_sig_contents_hex_string(value, force_hex_string, out)? {
out.write_bytes(b"\n")?;
continue;
}
unparse_child_qdf_with_ref_map_and_string_writer(
value,
indent + 2,
out,
map,
removed_refs,
write_string,
)?; out.write_bytes(b"\n")?;
}
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Length ")?;
if let Some(length_ref) = length_ref {
write_object_ref(out, length_ref)?;
} else if let Some(length) = length_value {
unparse_child_qdf_with_ref_map_and_string_writer(
length,
indent + 2,
out,
map,
removed_refs,
write_string,
)?; } else {
out.write_bytes(b"null")?;
}
out.write_bytes(b"\n")?;
if options.add_flate_filter {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Filter /FlateDecode\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
#[cfg(test)]
fn unparse_stream_dict_entries_with_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
refiltered: bool,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let entries = prepare_stream_dict_entries(
entries,
StreamDictionaryOptions::from_refiltered(refiltered),
)?; out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if try_write_sig_contents_with_string_writer(value, force_hex_string, out)? {
continue;
}
unparse_child_with_string_writer(value, out, write_string)?;
}
if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child_with_string_writer(length, out, write_string)?;
}
if refiltered {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
#[cfg(test)]
fn unparse_stream_dict_entries_qdf_with_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
out.write_bytes(b"<<\n")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(entries)? {
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if try_write_sig_contents_with_string_writer(value, force_hex_string, out)? {
out.write_bytes(b"\n")?;
continue;
}
unparse_child_qdf_with_string_writer(value, indent + 2, out, write_string)?;
out.write_bytes(b"\n")?;
}
if let Some(length) = length_value {
push_spaces(out, indent + 2)?;
out.write_bytes(b"/Length ")?;
unparse_child_qdf_with_string_writer(length, indent + 2, out, write_string)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
fn unparse_stream_dict_entries_with_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_stream_dict_entries_with_ref_map_and_length(
entries,
options,
out,
map,
removed_refs,
None,
)
}
fn unparse_stream_dict_entries_with_ref_map_and_length(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
length_override: Option<usize>,
) -> Result<()> {
let entries_without_length;
let entries = if length_override.is_some() {
entries_without_length = entries
.iter()
.filter(|(key, _)| key.as_slice() != b"/Length")
.cloned()
.collect::<Vec<_>>();
entries_without_length.as_slice()
} else {
entries
};
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_ref_map(value, out, map, removed_refs)?;
}
}
if let Some(length) = length_override {
out.write_bytes(b" /Length ")?;
write_decimal_u64(out, length as u64)?;
} else if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child_with_ref_map(length, out, map, removed_refs)?;
}
if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
fn unparse_stream_dictionary_live_with_qpdf_obj_gen_map_and_removed_and_length(
dictionary: &ObjectHandle,
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
length: usize,
) -> Result<()> {
let skip_empty_decode_parms = match dictionary_entry_handle(dictionary, b"/DecodeParms") {
Some(value) => value.try_array_len()?.is_some_and(|value| value == 0),
None => false,
};
if !options.remove_filter_parameters {
let has_snapshot_sensitive_filter =
if let Some(filter) = dictionary_entry_handle(dictionary, b"/Filter") {
filter.try_dereference()?;
filter.with_value(|value| matches!(value, Some(ObjectValue::Array(_))))
|| filter.try_is_name_and_equals(b"Crypt")?
} else {
false
};
if has_snapshot_sensitive_filter {
let entries = stream_dictionary_entries_for_emission(dictionary)?;
return unparse_stream_dict_entries_with_ref_map_and_length(
&entries,
options,
out,
map,
removed_refs,
Some(length),
);
}
}
out.write_bytes(b"<<")?;
let mut current_key = LiveDictionaryKeyBuffer::default();
let mut next_key = LiveDictionaryKeyBuffer::default();
let mut first_entry = true;
while let Some(value) = dictionary.next_dictionary_entry_for_live_walk(
(!first_entry).then_some(current_key.as_slice()),
&mut next_key,
) {
std::mem::swap(&mut current_key, &mut next_key);
let key = current_key.as_slice();
if key == b"/Length"
|| (options.remove_filter_parameters && matches!(key, b"/Filter" | b"/DecodeParms"))
|| (key == b"/DecodeParms" && skip_empty_decode_parms)
{
first_entry = false;
continue;
}
if value.try_is_null()?
|| value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
first_entry = false;
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
if key == b"/Contents" {
let force_hex_contents = dict_is_sig_with_byte_range_handle(dictionary)?;
if try_write_sig_contents_hex_string(&value, force_hex_contents, out)? {
first_entry = false;
continue;
}
}
unparse_child_with_ref_map(&value, out, map, removed_refs)?;
first_entry = false;
}
out.write_bytes(b" /Length ")?;
write_decimal_u64(out, length as u64)?;
if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
fn unparse_stream_dict_entries_with_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if try_write_sig_contents_hex_string(value, force_hex_string, out)? {
continue;
}
unparse_child_with_ref_map_and_string_writer(value, out, map, removed_refs, write_string)?;
}
if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child_with_ref_map_and_string_writer(length, out, map, removed_refs, write_string)?;
}
if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
pub(crate) fn unparse_child(handle: &ObjectHandle, out: &mut OutputSink<'_>) -> Result<()> {
if let Some(object_gen) = handle
.qpdf_obj_gen()
.filter(|object_gen| object_gen.is_indirect())
{
write_qpdf_object_gen(out, object_gen)?;
return Ok(());
}
if !handle.is_initialized() {
handle.try_dereference()?;
}
if write_direct_child(handle, out)? {
return Ok(());
}
unparse_object_walk(handle, out)
}
fn write_direct_child(handle: &ObjectHandle, out: &mut OutputSink<'_>) -> Result<bool> {
handle.with_value(|value| match value {
Some(ObjectValue::Array(_) | ObjectValue::Dictionary(_) | ObjectValue::Stream(_)) => {
Ok(false)
}
Some(value) => {
unparse_object_value(value, out)?;
Ok(true)
}
None => {
out.write_bytes(b"null")?;
Ok(true)
}
})
}
pub(crate) fn visible_dict_entries(
entries: &[(Vec<u8>, ObjectHandle)],
) -> Result<Vec<(&Vec<u8>, &ObjectHandle)>> {
let mut visible = Vec::with_capacity(entries.len());
for (key, value) in entries {
if !value.try_is_null()? {
visible.push((key, value));
}
}
Ok(visible)
}
fn is_removed_reference(handle: &ObjectHandle, removed_refs: &BTreeSet<ObjectRef>) -> bool {
handle
.object_ref()
.is_some_and(|object_ref| removed_refs.contains(&object_ref))
}
fn root_output_copy_with_adbe(
source: &ObjectHandle,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
) -> Result<ObjectHandle> {
let root = source.unsafe_shallow_copy()?;
if !apply_adbe_reconciliation {
return Ok(root);
}
let mut extensions = if root.try_has_key(b"/Extensions")?
&& root.try_get_key(b"/Extensions")?.try_is_dictionary()?
{
Some(root.try_get_key(b"/Extensions")?)
} else {
None
};
let (have_adbe, have_other) = if let Some(extensions) = &extensions {
let mut keys = extensions.try_get_keys()?;
let have_adbe = keys.remove(b"/ADBE".as_slice());
(have_adbe, !keys.is_empty())
} else {
(false, false)
};
let need_adbe = final_extension_level > 0;
if need_adbe {
if !(have_other || have_adbe) {
let created = ObjectHandle::dictionary(Vec::new());
root.replace_key(b"/Extensions", created.clone())?;
extensions = Some(created);
}
} else if !have_other && have_adbe {
root.remove_key(b"/Extensions");
extensions = None;
}
if let Some(extensions) = extensions {
let adbe = extensions.try_get_key(b"/ADBE")?;
let preserves_existing = adbe.try_is_dictionary()?
&& adbe
.try_get_key(b"/BaseVersion")?
.try_is_name_and_equals(final_pdf_version.as_bytes())?
&& adbe.try_get_key(b"/ExtensionLevel")?.try_as_integer()?
== Some(final_extension_level);
if !preserves_existing {
if need_adbe {
let replacement = ObjectHandle::dictionary(vec![
(
b"/BaseVersion".to_vec(),
ObjectHandle::name(final_pdf_version.as_bytes().to_vec()),
),
(
b"/ExtensionLevel".to_vec(),
ObjectHandle::integer(final_extension_level),
),
]);
extensions.replace_key(b"/ADBE", replacement)?;
} else {
extensions.remove_key(b"/ADBE");
}
}
}
Ok(root)
}
enum UnparseContainer {
Array(Vec<ObjectHandle>),
Dictionary(Vec<(Vec<u8>, ObjectHandle)>),
Stream(ObjectHandle),
}
fn snapshot_unparse_container(value: &ObjectValue) -> Option<UnparseContainer> {
match value {
ObjectValue::Array(children) => Some(UnparseContainer::Array(children.clone())),
ObjectValue::Dictionary(entries) => Some(UnparseContainer::Dictionary(
entries
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
)),
ObjectValue::Stream(stream) => Some(UnparseContainer::Stream(stream.stream_dict.clone())),
_ => None,
}
}
fn is_direct_scalar_value(value: &ObjectValue) -> bool {
matches!(
value,
ObjectValue::Null
| ObjectValue::Boolean(_)
| ObjectValue::Integer(_)
| ObjectValue::Real(_)
| ObjectValue::RealLiteral { .. }
| ObjectValue::Name(_)
| ObjectValue::String(_)
| ObjectValue::Operator(_)
| ObjectValue::InlineImage(_)
)
}
fn is_direct_scalar_handle(handle: &ObjectHandle) -> bool {
handle.qpdf_obj_gen().is_none()
&& handle.with_value(|value| value.is_some_and(is_direct_scalar_value))
}
fn write_direct_scalar_with_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
handle.with_value(|value| match value {
Some(ObjectValue::String(bytes)) => write_string(out, bytes),
Some(value) => unparse_object_value(value, out),
None => out.write_bytes(b"null"), })
}
fn try_write_direct_scalar_container_with_string_writer<F>(
value: &ObjectValue,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<bool>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
match value {
ObjectValue::Array(children) if children.iter().all(is_direct_scalar_handle) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
write_direct_scalar_with_string_writer(child, out, write_string)?;
}
out.write_bytes(b" ]")?;
Ok(true)
}
ObjectValue::Dictionary(entries)
if entries
.iter()
.all(|(_, child)| is_direct_scalar_handle(child)) =>
{
let is_signature = entries
.iter()
.find(|(key, _)| key.as_slice() == b"/Type")
.is_some_and(|(_, value)| value.as_name().as_deref() == Some(b"Sig"));
let has_byte_range = is_signature
&& entries
.iter()
.find(|(key, _)| key.as_slice() == b"/ByteRange")
.is_some_and(|(_, value)| !value.is_null());
let force_hex_contents = is_signature && has_byte_range;
out.write_bytes(b"<<")?;
for (key, child) in entries {
if child.is_null() {
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
if force_hex_contents
&& key.as_slice() == b"/Contents"
&& child.with_value(|value| -> Result<bool> {
if let Some(ObjectValue::String(bytes)) = value {
crate::pdf_syntax::write_hex_string(out, bytes)?;
Ok(true)
} else {
Ok(false)
}
})?
{
continue;
}
write_direct_scalar_with_string_writer(child, out, write_string)?;
}
out.write_bytes(b" >>")?;
Ok(true)
}
_ => Ok(false),
}
}
fn unparse_container(container: UnparseContainer, out: &mut OutputSink<'_>) -> Result<()> {
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child(&child, out)?;
}
out.write_bytes(b" ]")?;
}
UnparseContainer::Dictionary(entries) => unparse_dict_entries(&entries, out)?,
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk(&stream_dict, out)?;
}
}
Ok(())
}
fn unparse_object_walk(handle: &ObjectHandle, out: &mut OutputSink<'_>) -> Result<()> {
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value(value, out).map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => unparse_container(container, out),
None => Ok(()),
}
})
}
pub(crate) fn unparse_object_value(value: &ObjectValue, out: &mut OutputSink<'_>) -> Result<()> {
match value {
ObjectValue::Null => out.write_bytes(b"null")?,
ObjectValue::Unresolved => return Err(unresolved_unparse_error()),
ObjectValue::Reserved => return Err(reserved_unparse_error()),
ObjectValue::Destroyed => return Err(destroyed_unparse_error()),
ObjectValue::Boolean(v) => out.write_bytes(if *v { b"true" } else { b"false" })?,
ObjectValue::Integer(v) => write_decimal_i64(out, *v)?,
ObjectValue::Real(v) => out.write_bytes(v.to_string().as_bytes())?,
ObjectValue::RealLiteral { value, literal } => {
if crate::pdf_syntax::real_literal_is_safe(literal, *value) {
out.write_bytes(literal)?;
} else {
out.write_bytes(value.to_string().as_bytes())?;
}
}
ObjectValue::Name(name) => {
out.write_bytes(b"/")?;
crate::pdf_syntax::write_name_escaped(out, name)?;
}
ObjectValue::String(value) => crate::pdf_syntax::write_string_value(out, value)?,
ObjectValue::Operator(value) | ObjectValue::InlineImage(value) => {
out.write_bytes(value)?;
}
ObjectValue::Array(children) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child(child, out)?;
}
out.write_bytes(b" ]")?;
}
ObjectValue::Dictionary(entries) => {
let entries: Vec<(Vec<u8>, ObjectHandle)> = entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
unparse_dict_entries(&entries, out)?;
}
ObjectValue::Stream(stream) => {
unparse_object_walk(&stream.stream_dict, out)?;
}
}
Ok(())
}
type QpdfObjGenMap<'a> = dyn Fn(QpdfObjGen) -> Result<ObjectRef> + 'a;
pub(crate) fn qpdf_obj_gen_map_from_object_ref_map<'a>(
map: &'a dyn Fn(ObjectRef) -> Result<ObjectRef>,
) -> impl Fn(QpdfObjGen) -> Result<ObjectRef> + 'a {
move |object_gen| {
let object_ref = object_gen.to_object_ref().ok_or_else(|| {
Error::Unsupported(format!(
"qpdf raw object identity {} {} cannot be used by an ObjectRef map",
object_gen.get_obj(),
object_gen.get_gen()
))
})?;
map(object_ref)
}
}
pub(crate) fn qpdf_obj_gen_set_from_object_ref_set(
object_refs: &BTreeSet<ObjectRef>,
) -> Result<BTreeSet<QpdfObjGen>> {
object_refs
.iter()
.copied()
.map(QpdfObjGen::try_from_object_ref)
.collect()
}
pub(crate) fn unparse_child_with_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect() || removed_refs.contains(&object_gen) {
out.write_bytes(b"null")?;
return Ok(());
}
let mapped = map(object_gen)?;
write_object_ref(out, mapped)?;
return Ok(());
}
if !handle.is_initialized() {
handle.try_dereference()?;
}
if write_direct_child_with_ref_map(handle, out, map, removed_refs)? {
return Ok(());
}
unparse_object_walk_with_ref_map(handle, out, map, removed_refs)
}
fn write_direct_child_with_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<bool> {
handle.with_value(|value| match value {
Some(ObjectValue::Array(_) | ObjectValue::Dictionary(_) | ObjectValue::Stream(_)) => {
Ok(false)
}
Some(value) => {
unparse_object_value_with_ref_map(value, out, map, removed_refs)?;
Ok(true)
}
None => {
out.write_bytes(b"null")?;
Ok(true)
}
})
}
fn unparse_object_walk_with_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| -> Result<RefMapContainer> {
match value {
Some(ObjectValue::Array(_)) => Ok(RefMapContainer::Array),
Some(ObjectValue::Dictionary(_)) => Ok(RefMapContainer::Dictionary),
Some(ObjectValue::Stream(stream)) => {
Ok(RefMapContainer::Stream(stream.stream_dict.clone()))
}
Some(value) => {
unparse_object_value_with_ref_map(value, out, map, removed_refs)?;
Ok(RefMapContainer::Written)
}
None => {
out.write_bytes(b"null")?;
Ok(RefMapContainer::Written)
}
}
})?;
match container {
RefMapContainer::Array => unparse_array_with_ref_map(handle, out, map, removed_refs),
RefMapContainer::Dictionary => {
unparse_dictionary_with_ref_map(handle, out, map, removed_refs)
}
RefMapContainer::Stream(stream_dict) => {
unparse_object_walk_with_ref_map(&stream_dict, out, map, removed_refs)
}
RefMapContainer::Written => Ok(()),
}
})
}
enum RefMapContainer {
Array,
Dictionary,
Stream(ObjectHandle),
Written,
}
fn unparse_array_with_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
out.write_bytes(b"[")?;
let items = handle.try_array_items()?;
let mut cursor = items.begin();
while !cursor.is_end() {
out.write_bytes(b" ")?;
let child = cursor.current();
unparse_child_with_ref_map(&child, out, map, removed_refs)?;
cursor.next();
}
out.write_bytes(b" ]")?;
Ok(())
}
fn unparse_dictionary_with_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
out.write_bytes(b"<<")?;
let mut current_key = LiveDictionaryKeyBuffer::default();
let mut next_key = LiveDictionaryKeyBuffer::default();
let mut first_entry = true;
while let Some(value) = handle.next_dictionary_entry_for_live_walk(
(!first_entry).then_some(current_key.as_slice()),
&mut next_key,
) {
std::mem::swap(&mut current_key, &mut next_key);
let is_null = value.try_is_null()?;
if is_null
|| value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
first_entry = false;
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, current_key.as_slice())?;
out.write_bytes(b" ")?;
let force_hex_string =
current_key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range_handle(handle)?;
if !try_write_sig_contents_hex_string(&value, force_hex_string, out)? {
unparse_child_with_ref_map(&value, out, map, removed_refs)?;
}
first_entry = false;
}
out.write_bytes(b" >>")?;
Ok(())
}
fn unparse_object_value_with_ref_map(
value: &ObjectValue,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
match value {
ObjectValue::Array(children) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child_with_ref_map(child, out, map, removed_refs)?;
}
out.write_bytes(b" ]")?;
}
ObjectValue::Dictionary(entries) => {
let entries: Vec<(Vec<u8>, ObjectHandle)> = entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
unparse_dict_entries_with_ref_map(&entries, out, map, removed_refs)?;
}
ObjectValue::Stream(stream) => {
unparse_object_walk_with_ref_map(&stream.stream_dict, out, map, removed_refs)?;
}
_ => unparse_object_value(value, out)?,
}
Ok(())
}
fn unparse_dict_entries_with_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_ref_map(value, out, map, removed_refs)?; }
}
out.write_bytes(b" >>")?;
Ok(())
}
pub(crate) type DynamicObjectRefMap<'a> = dyn FnMut(&ObjectHandle) -> Result<ObjectRef> + 'a;
pub(crate) trait DynamicDirectStreamWriter {
#[allow(clippy::type_complexity)]
fn write_direct_stream(
&mut self,
stream: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut dyn FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
) -> Result<()>;
}
pub(crate) struct DefaultDynamicDirectStreamWriter {
pub(crate) newline_before_endstream: Option<crate::writer::NewlineBeforeEndstream>,
pub(crate) qdf_mode: bool,
}
impl DynamicDirectStreamWriter for DefaultDynamicDirectStreamWriter {
fn write_direct_stream(
&mut self,
stream: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut dyn FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
) -> Result<()> {
stream.try_dereference()?;
let dict = stream.as_stream_dict().ok_or_else(|| {
Error::Internal("direct stream disappeared during emission".to_string())
})?; let data = stream.get_raw_stream_data()?;
let dict = dict.unsafe_shallow_copy()?;
dict.replace_key(
b"/Length",
ObjectHandle::integer(i64::try_from(data.len()).map_err(|_| {
Error::Unsupported("direct stream /Length does not fit in i64".to_string())
})?), )?; let entries = stream_dictionary_entries_for_emission(&dict)?;
unparse_stream_dict_entries_with_dynamic_ref_map_and_string_writer(
&entries,
StreamDictionaryOptions::preserve(),
out,
map,
removed_refs,
write_string,
self,
)?; out.write_bytes(b"\nstream\n")?;
out.write_bytes(data.as_ref())?;
if self.qdf_mode {
if crate::writer::serialize::framing_adds_newline_with_qdf(
data.as_ref(),
self.newline_before_endstream
.unwrap_or(crate::writer::NewlineBeforeEndstream::Never),
true,
) {
out.write_bytes(b"\n")?;
} } else if self
.newline_before_endstream
.is_some_and(|policy| matches!(policy, crate::writer::NewlineBeforeEndstream::Yes))
{
out.write_bytes(b"\n")?;
}
out.write_bytes(b"endstream")
}
}
#[allow(clippy::type_complexity)]
pub(crate) fn unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
unparse_object_walk_with_dynamic_ref_map_and_string_writer(
handle,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn unparse_root_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer<
F,
>(
source: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
final_pdf_version: &str,
final_extension_level: i64,
apply_adbe_reconciliation: bool,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
let root = root_output_copy_with_adbe(
source,
final_pdf_version,
final_extension_level,
apply_adbe_reconciliation,
)?; unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&root,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)
}
pub(crate) fn unparse_object_with_ref_map_and_direct_streams(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
qdf: bool,
) -> Result<()> {
let mut dynamic_map = |child: &ObjectHandle| {
child
.object_ref()
.ok_or_else(|| Error::Internal("direct root map received a direct child".into()))
.and_then(map)
};
let mut write_string =
|out: &mut OutputSink<'_>, value: &[u8]| crate::pdf_syntax::write_string_value(out, value);
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: Some(crate::writer::NewlineBeforeEndstream::Never),
qdf_mode: qdf,
};
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
handle,
out,
&mut dynamic_map,
removed_refs,
&mut write_string,
&mut direct_stream_writer,
)
}
fn unparse_child_with_dynamic_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect()
|| object_gen
.to_object_ref()
.is_some_and(|object_ref| removed_refs.contains(&object_ref))
{
out.write_bytes(b"null")?;
return Ok(());
}
write_object_ref(out, map(handle)?)?;
return Ok(());
}
if !handle.is_initialized() {
handle.try_dereference()?;
}
match write_direct_child_with_dynamic_ref_map_and_string_writer(handle, out, write_string)? {
DynamicDirectChildKind::Scalar => return Ok(()),
DynamicDirectChildKind::Stream => {
let mut write_string_wrapper =
|out: &mut OutputSink<'_>, value: &[u8]| write_string(out, value);
return direct_stream_writer.write_direct_stream(
handle,
out,
map,
removed_refs,
&mut write_string_wrapper,
);
}
DynamicDirectChildKind::Container => {}
}
unparse_object_walk_with_dynamic_ref_map_and_string_writer(
handle,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)
}
enum DynamicDirectChildKind {
Scalar,
Container,
Stream,
}
fn write_direct_child_with_dynamic_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<DynamicDirectChildKind>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
handle.with_value(|value| match value {
Some(ObjectValue::Array(_) | ObjectValue::Dictionary(_)) => {
Ok(DynamicDirectChildKind::Container)
}
Some(ObjectValue::Stream(_)) => Ok(DynamicDirectChildKind::Stream),
Some(value) => {
unparse_object_value_with_dynamic_ref_map_and_string_writer(value, out, write_string)?;
Ok(DynamicDirectChildKind::Scalar)
}
None => {
out.write_bytes(b"null")?;
Ok(DynamicDirectChildKind::Scalar)
}
})
}
fn unparse_object_walk_with_dynamic_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if try_write_direct_scalar_container_with_string_writer(value, out, write_string)? {
Ok(None)
} else if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_with_dynamic_ref_map_and_string_writer(
value,
out,
write_string,
)
.map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(UnparseContainer::Array(children)) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child_with_dynamic_ref_map_and_string_writer(
&child,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)?; }
out.write_bytes(b" ]")?;
}
Some(UnparseContainer::Dictionary(entries)) => {
unparse_dict_entries_with_dynamic_ref_map_and_string_writer(
&entries,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)?; }
Some(UnparseContainer::Stream(stream_dict)) => {
unparse_object_walk_with_dynamic_ref_map_and_string_writer(
&stream_dict,
out,
map,
removed_refs,
write_string,
direct_stream_writer,
)?;
}
None => {}
}
Ok(())
})
}
fn unparse_object_value_with_dynamic_ref_map_and_string_writer<F>(
value: &ObjectValue,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
match value {
ObjectValue::String(bytes) => write_string(out, bytes),
_ => unparse_object_value(value, out),
}
}
fn unparse_dict_entries_with_dynamic_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
if is_removed_reference(value, removed_refs) {
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_dynamic_ref_map_and_string_writer(
value,
out,
map,
removed_refs,
write_string,
direct_stream_writer, )?; }
}
out.write_bytes(b" >>")
}
fn unparse_stream_dict_entries_with_dynamic_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
write_string: &mut F,
direct_stream_writer: &mut dyn DynamicDirectStreamWriter,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()> + ?Sized,
{
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if is_removed_reference(value, removed_refs) {
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_dynamic_ref_map_and_string_writer(
value,
out,
map,
removed_refs,
write_string,
direct_stream_writer, )?; } }
if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child_with_dynamic_ref_map_and_string_writer(
length,
out,
map,
removed_refs,
write_string,
direct_stream_writer, )?; } if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")
}
fn unparse_child_with_dynamic_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect()
|| object_gen
.to_object_ref()
.is_some_and(|object_ref| removed_refs.contains(&object_ref))
{
out.write_bytes(b"null")?;
return Ok(());
}
let mapped = map(handle)?;
write_object_ref(out, mapped)?;
return Ok(());
}
if !handle.is_initialized() {
handle.try_dereference()?;
}
if write_direct_child_with_dynamic_ref_map(handle, out, map, removed_refs)? {
return Ok(());
}
unparse_object_walk_with_dynamic_ref_map(handle, out, map, removed_refs)
}
fn write_direct_child_with_dynamic_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<bool> {
handle.with_value(|value| match value {
Some(ObjectValue::Array(_) | ObjectValue::Dictionary(_) | ObjectValue::Stream(_)) => {
Ok(false)
}
Some(value) => {
unparse_object_value_with_dynamic_ref_map(value, out, map, removed_refs)?;
Ok(true)
}
None => {
out.write_bytes(b"null")?;
Ok(true)
}
})
}
fn unparse_object_walk_with_dynamic_ref_map(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_with_dynamic_ref_map(value, out, map, removed_refs)
.map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(UnparseContainer::Array(children)) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child_with_dynamic_ref_map(&child, out, map, removed_refs)?;
}
out.write_bytes(b" ]")?;
}
Some(UnparseContainer::Dictionary(entries)) => {
unparse_dict_entries_with_dynamic_ref_map(&entries, out, map, removed_refs)?;
}
Some(UnparseContainer::Stream(stream_dict)) => {
unparse_object_walk_with_dynamic_ref_map(&stream_dict, out, map, removed_refs)?;
}
None => {}
}
Ok(())
})
}
fn unparse_object_value_with_dynamic_ref_map(
value: &ObjectValue,
out: &mut OutputSink<'_>,
_map: &mut DynamicObjectRefMap<'_>,
_removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
unparse_object_value(value, out)
}
fn unparse_dict_entries_with_dynamic_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
if is_removed_reference(value, removed_refs) {
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_dynamic_ref_map(value, out, map, removed_refs)?; } }
out.write_bytes(b" >>")?;
Ok(())
}
fn unparse_stream_dict_entries_with_dynamic_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
options: StreamDictionaryOptions,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<ObjectRef>,
) -> Result<()> {
let entries = prepare_stream_dict_entries(entries, options)?;
out.write_bytes(b"<<")?;
let mut length_value: Option<&ObjectHandle> = None;
for (key, value) in visible_dict_entries(&entries)? {
if is_removed_reference(value, removed_refs) {
continue;
}
if key.as_slice() == b"/Length" {
length_value = Some(value);
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(&entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_with_dynamic_ref_map(value, out, map, removed_refs)?; } }
if let Some(length) = length_value {
out.write_bytes(b" /Length ")?;
unparse_child_with_dynamic_ref_map(length, out, map, removed_refs)?; } if options.add_flate_filter {
out.write_bytes(b" /Filter /FlateDecode")?;
}
out.write_bytes(b" >>")?;
Ok(())
}
pub(crate) fn dict_is_sig_with_byte_range(entries: &[(Vec<u8>, ObjectHandle)]) -> Result<bool> {
let Some((_, type_value)) = entries.iter().find(|entry| entry.0.as_slice() == b"/Type") else {
return Ok(false);
};
type_value.try_dereference()?;
let is_sig = type_value.with_value(
|value| matches!(value, Some(ObjectValue::Name(name)) if name.as_slice() == b"Sig"),
);
if !is_sig {
return Ok(false);
}
let Some((_, byte_range_value)) = entries
.iter()
.find(|entry| entry.0.as_slice() == b"/ByteRange")
else {
return Ok(false);
};
Ok(!byte_range_value.try_is_null()?)
}
fn try_write_sig_contents_hex_string(
handle: &ObjectHandle,
force_hex_string: bool,
out: &mut OutputSink<'_>,
) -> Result<bool> {
if !force_hex_string
|| handle
.qpdf_obj_gen()
.is_some_and(|object_gen| object_gen.is_indirect())
{
return Ok(false);
}
handle.try_dereference()?;
handle.with_value(|value| {
if let Some(ObjectValue::String(bytes)) = value {
crate::pdf_syntax::write_hex_string(out, bytes)?;
Ok(true)
} else {
Ok(false)
}
})
}
fn unparse_dict_entries(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
) -> Result<()> {
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child(value, out)?;
}
}
out.write_bytes(b" >>")?;
Ok(())
}
const SPACE_BLOCK: [u8; 64] = [b' '; 64];
fn push_spaces(out: &mut OutputSink<'_>, mut n: usize) -> Result<()> {
while n >= SPACE_BLOCK.len() {
out.write_bytes(&SPACE_BLOCK)?;
n -= SPACE_BLOCK.len();
}
if n > 0 {
out.write_bytes(&SPACE_BLOCK[..n])?;
}
Ok(())
}
fn unparse_child_qdf(handle: &ObjectHandle, indent: usize, out: &mut OutputSink<'_>) -> Result<()> {
if let Some(object_gen) = handle
.qpdf_obj_gen()
.filter(|object_gen| object_gen.is_indirect())
{
write_qpdf_object_gen(out, object_gen)?;
return Ok(());
}
unparse_object_walk_qdf(handle, indent, out)
}
fn unparse_object_walk_qdf(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
) -> Result<()> {
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_qdf(value, indent, out).map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => unparse_container_qdf(container, indent, out),
None => Ok(()),
}
})
}
fn unparse_container_qdf(
container: UnparseContainer,
indent: usize,
out: &mut OutputSink<'_>,
) -> Result<()> {
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
out.write_bytes(b"\n")?;
for child in children {
push_spaces(out, indent + 2)?;
unparse_child_qdf(&child, indent + 2, out)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b"]")?;
}
UnparseContainer::Dictionary(entries) => {
unparse_dict_entries_qdf(&entries, indent, out)?;
}
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk_qdf(&stream_dict, indent, out)?;
}
}
Ok(())
}
fn unparse_object_value_qdf(
value: &ObjectValue,
indent: usize,
out: &mut OutputSink<'_>,
) -> Result<()> {
match value {
ObjectValue::Array(children) => {
out.write_bytes(b"[")?;
out.write_bytes(b"\n")?;
for child in children {
push_spaces(out, indent + 2)?;
unparse_child_qdf(child, indent + 2, out)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b"]")?;
}
ObjectValue::Dictionary(entries) => {
let entries: Vec<(Vec<u8>, ObjectHandle)> = entries
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
unparse_dict_entries_qdf(&entries, indent, out)?;
}
ObjectValue::Stream(stream) => {
unparse_object_walk_qdf(&stream.stream_dict, indent, out)?;
}
ObjectValue::Null
| ObjectValue::Unresolved
| ObjectValue::Reserved
| ObjectValue::Destroyed
| ObjectValue::Boolean(_)
| ObjectValue::Integer(_)
| ObjectValue::Real(_)
| ObjectValue::RealLiteral { .. }
| ObjectValue::Name(_)
| ObjectValue::String(_)
| ObjectValue::Operator(_)
| ObjectValue::InlineImage(_) => unparse_object_value(value, out)?,
}
Ok(())
}
fn unparse_dict_entries_qdf(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
) -> Result<()> {
out.write_bytes(b"<<\n")?;
for (key, value) in visible_dict_entries(entries)? {
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if !try_write_sig_contents_hex_string(value, force_hex_string, out)? {
unparse_child_qdf(value, indent + 2, out)?;
}
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
fn unparse_child_qdf_with_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect() || removed_refs.contains(&object_gen) {
out.write_bytes(b"null")?;
} else {
write_object_ref(out, map(object_gen)?)?;
}
return Ok(());
}
unparse_object_walk_qdf_with_ref_map(handle, indent, out, map, removed_refs)
}
fn unparse_object_walk_qdf_with_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
if handle.try_is_array()? {
return unparse_array_qdf_with_ref_map(handle, indent, out, map, removed_refs);
}
if handle.try_is_dictionary()? {
return unparse_dictionary_qdf_with_ref_map(handle, indent, out, map, removed_refs);
}
if let Some(stream_dict) = handle.as_stream_dict() {
return unparse_object_walk_qdf_with_ref_map(
&stream_dict,
indent,
out,
map,
removed_refs,
);
}
handle.with_value(|value| match value {
Some(value) => {
unparse_object_value_qdf_with_ref_map(value, indent, out, map, removed_refs)
}
None => {
out.write_bytes(b"null")
}
})
})
}
fn unparse_array_qdf_with_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
out.write_bytes(b"[")?;
out.write_bytes(b"\n")?;
let items = handle.try_array_items()?;
let mut cursor = items.begin();
while !cursor.is_end() {
push_spaces(out, indent + 2)?;
let child = cursor.current();
unparse_child_qdf_with_ref_map(&child, indent + 2, out, map, removed_refs)?;
out.write_bytes(b"\n")?;
cursor.next();
}
push_spaces(out, indent)?;
out.write_bytes(b"]")
}
fn unparse_dictionary_qdf_with_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
out.write_bytes(b"<<\n")?;
let mut current_key = LiveDictionaryKeyBuffer::default();
let mut next_key = LiveDictionaryKeyBuffer::default();
let mut first_entry = true;
while let Some(value) = handle.next_dictionary_entry_for_live_walk(
(!first_entry).then_some(current_key.as_slice()),
&mut next_key,
) {
std::mem::swap(&mut current_key, &mut next_key);
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
|| value.try_is_null()?
{
first_entry = false;
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, current_key.as_slice())?;
out.write_bytes(b" ")?;
let force_hex_string =
current_key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range_handle(handle)?;
if !try_write_sig_contents_hex_string(&value, force_hex_string, out)? {
unparse_child_qdf_with_ref_map(&value, indent + 2, out, map, removed_refs)?;
}
out.write_bytes(b"\n")?;
first_entry = false;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")
}
pub(crate) fn unparse_object_qdf_with_dynamic_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_qdf_with_dynamic_ref_map(handle, indent, out, map, removed_refs)
}
enum QdfDynamicContainer {
Array,
Dictionary,
Stream(ObjectHandle),
Written,
}
fn unparse_object_walk_qdf_with_dynamic_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_walk_hub(|| {
handle.try_dereference()?;
let container = handle.with_value(|value| -> Result<QdfDynamicContainer> {
match value {
Some(ObjectValue::Array(_)) => Ok(QdfDynamicContainer::Array),
Some(ObjectValue::Dictionary(_)) => Ok(QdfDynamicContainer::Dictionary),
Some(ObjectValue::Stream(stream)) => {
Ok(QdfDynamicContainer::Stream(stream.stream_dict.clone()))
}
Some(value) => {
unparse_object_value_qdf(value, indent, out)?;
Ok(QdfDynamicContainer::Written)
}
None => {
out.write_bytes(b"null")?;
Ok(QdfDynamicContainer::Written) }
}
})?;
match container {
QdfDynamicContainer::Array => {
out.write_bytes(b"[\n")?;
let items = handle.try_array_items()?;
let mut cursor = items.begin();
while !cursor.is_end() {
push_spaces(out, indent + 2)?;
let child = cursor.current();
unparse_child_qdf_with_dynamic_ref_map(
&child,
indent + 2,
out,
map,
removed_refs,
)?; out.write_bytes(b"\n")?;
cursor.next();
}
push_spaces(out, indent)?;
out.write_bytes(b"]")?;
}
QdfDynamicContainer::Dictionary => {
out.write_bytes(b"<<\n")?;
let mut current_key = LiveDictionaryKeyBuffer::default();
let mut next_key = LiveDictionaryKeyBuffer::default();
let mut first_entry = true;
while let Some(value) = handle.next_dictionary_entry_for_live_walk(
(!first_entry).then_some(current_key.as_slice()),
&mut next_key,
) {
std::mem::swap(&mut current_key, &mut next_key);
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
|| value.try_is_null()?
{
first_entry = false;
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, current_key.as_slice())?;
out.write_bytes(b" ")?;
let force_hex_string = current_key.as_slice() == b"/Contents"
&& dict_is_sig_with_byte_range_handle(handle)?;
if !try_write_sig_contents_hex_string(&value, force_hex_string, out)? {
unparse_child_qdf_with_dynamic_ref_map(
&value,
indent + 2,
out,
map,
removed_refs,
)?; }
out.write_bytes(b"\n")?;
first_entry = false;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
}
QdfDynamicContainer::Stream(stream_dict) => {
unparse_object_walk_qdf_with_dynamic_ref_map(
&stream_dict,
indent,
out,
map,
removed_refs,
)?; }
QdfDynamicContainer::Written => {}
}
Ok(())
})
}
fn unparse_child_qdf_with_dynamic_ref_map(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &mut DynamicObjectRefMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect() || removed_refs.contains(&object_gen) {
out.write_bytes(b"null")?;
} else {
write_object_ref(out, map(handle)?)?;
}
return Ok(());
}
let direct_value = handle.with_value(|value| -> Result<Option<QdfDynamicContainer>> {
match value {
Some(ObjectValue::Array(_))
| Some(ObjectValue::Dictionary(_))
| Some(ObjectValue::Stream(_)) => Ok(None),
Some(value) => {
unparse_object_value_qdf(value, indent, out)?;
Ok(Some(QdfDynamicContainer::Written))
}
None => {
out.write_bytes(b"null")?;
Ok(Some(QdfDynamicContainer::Written)) }
}
})?;
if direct_value.is_some() {
return Ok(());
}
unparse_object_walk_qdf_with_dynamic_ref_map(handle, indent, out, map, removed_refs)
}
fn dict_is_sig_with_byte_range_handle(handle: &ObjectHandle) -> Result<bool> {
let type_value = handle.try_get_key(b"/Type")?;
if !type_value.try_is_name_and_equals(b"Sig")? {
return Ok(false);
}
let byte_range = handle.try_get_key(b"/ByteRange")?;
Ok(!byte_range.try_is_null()?)
}
fn unparse_object_value_qdf_with_ref_map(
value: &ObjectValue,
_indent: usize,
out: &mut OutputSink<'_>,
_map: &QpdfObjGenMap<'_>,
_removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
unparse_object_value(value, out)
}
fn unparse_child_with_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect() || removed_refs.contains(&object_gen) {
out.write_bytes(b"null")?;
} else {
write_object_ref(out, map(object_gen)?)?;
}
return Ok(());
}
unparse_object_walk_with_ref_map_and_string_writer(handle, out, map, removed_refs, write_string)
}
fn unparse_object_walk_with_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_with_ref_map_and_string_writer(
value,
out,
map,
removed_refs,
write_string,
)
.map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => unparse_container_with_ref_map_and_string_writer(
container,
out,
map,
removed_refs,
write_string,
),
None => Ok(()),
}
})
}
fn unparse_container_with_ref_map_and_string_writer<F>(
container: UnparseContainer,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child_with_ref_map_and_string_writer(
&child,
out,
map,
removed_refs,
write_string,
)?; }
out.write_bytes(b" ]")?;
}
UnparseContainer::Dictionary(entries) => {
unparse_dict_entries_with_ref_map_and_string_writer(
&entries,
out,
map,
removed_refs,
write_string,
)?; }
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk_with_ref_map_and_string_writer(
&stream_dict,
out,
map,
removed_refs,
write_string,
)?; }
}
Ok(())
}
fn unparse_object_value_with_ref_map_and_string_writer<F>(
value: &ObjectValue,
out: &mut OutputSink<'_>,
_map: &QpdfObjGenMap<'_>,
_removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match value {
ObjectValue::String(bytes) => write_string(out, bytes),
_ => unparse_object_value(value, out),
}
}
fn unparse_dict_entries_with_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if try_write_sig_contents_hex_string(value, force_hex_string, out)? {
continue;
}
unparse_child_with_ref_map_and_string_writer(value, out, map, removed_refs, write_string)?;
}
out.write_bytes(b" >>")?;
Ok(())
}
fn unparse_child_qdf_with_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if let Some(object_gen) = handle.qpdf_obj_gen() {
if !object_gen.is_indirect() || removed_refs.contains(&object_gen) {
out.write_bytes(b"null")?;
} else {
write_object_ref(out, map(object_gen)?)?;
}
return Ok(());
}
unparse_object_walk_qdf_with_ref_map_and_string_writer(
handle,
indent,
out,
map,
removed_refs,
write_string,
)
}
fn unparse_object_walk_qdf_with_ref_map_and_string_writer<F>(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_qdf_with_ref_map_and_string_writer(
value,
indent,
out,
map,
removed_refs,
write_string,
)
.map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => unparse_container_qdf_with_ref_map_and_string_writer(
container,
indent,
out,
map,
removed_refs,
write_string,
),
None => Ok(()),
}
})
}
fn unparse_container_qdf_with_ref_map_and_string_writer<F>(
container: UnparseContainer,
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
out.write_bytes(b"\n")?;
for child in children {
push_spaces(out, indent + 2)?;
unparse_child_qdf_with_ref_map_and_string_writer(
&child,
indent + 2,
out,
map,
removed_refs,
write_string,
)?; out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b"]")?;
}
UnparseContainer::Dictionary(entries) => {
unparse_dict_entries_qdf_with_ref_map_and_string_writer(
&entries,
indent,
out,
map,
removed_refs,
write_string,
)?; }
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk_qdf_with_ref_map_and_string_writer(
&stream_dict,
indent,
out,
map,
removed_refs,
write_string,
)?; }
}
Ok(())
}
fn unparse_object_value_qdf_with_ref_map_and_string_writer<F>(
value: &ObjectValue,
_indent: usize,
out: &mut OutputSink<'_>,
_map: &QpdfObjGenMap<'_>,
_removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match value {
ObjectValue::String(bytes) => write_string(out, bytes),
_ => unparse_object_value(value, out),
}
}
fn unparse_dict_entries_qdf_with_ref_map_and_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
out.write_bytes(b"<<\n")?;
for (key, value) in visible_dict_entries(entries)? {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| removed_refs.contains(&object_gen))
{
continue;
}
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if try_write_sig_contents_hex_string(value, force_hex_string, out)? {
out.write_bytes(b"\n")?;
continue;
}
unparse_child_qdf_with_ref_map_and_string_writer(
value,
indent + 2,
out,
map,
removed_refs,
write_string,
)?; out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
#[cfg(test)]
fn unparse_child_with_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if let Some(object_ref) = handle.object_ref() {
write_object_ref(out, object_ref)?;
return Ok(());
}
unparse_object_walk_with_string_writer(handle, out, write_string)
}
#[cfg(test)]
fn unparse_container_with_string_writer<F>(
container: UnparseContainer,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
for child in children {
out.write_bytes(b" ")?;
unparse_child_with_string_writer(&child, out, write_string)?;
}
out.write_bytes(b" ]")?;
}
UnparseContainer::Dictionary(entries) => {
unparse_dict_entries_with_string_writer(&entries, out, write_string)?;
}
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk_with_string_writer(&stream_dict, out, write_string)?;
}
}
Ok(())
}
#[cfg(test)]
fn unparse_object_walk_with_string_writer<F>(
handle: &ObjectHandle,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_with_string_writer(value, out, write_string).map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => unparse_container_with_string_writer(container, out, write_string),
None => Ok(()),
}
})
}
#[cfg(test)]
fn unparse_object_value_with_string_writer<F>(
value: &ObjectValue,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match value {
ObjectValue::String(bytes) => write_string(out, bytes),
_ => unparse_object_value(value, out),
}
}
#[cfg(test)]
fn try_write_sig_contents_with_string_writer(
handle: &ObjectHandle,
force_hex_string: bool,
out: &mut OutputSink<'_>,
) -> Result<bool> {
if !force_hex_string || handle.object_ref().is_some() {
return Ok(false);
}
handle.try_dereference()?;
let bytes = handle.with_value(|value| match value {
Some(ObjectValue::String(bytes)) => Some(bytes.clone()),
_ => None,
});
let Some(bytes) = bytes else {
return Ok(false);
};
crate::pdf_syntax::write_hex_string(out, &bytes)?;
Ok(true)
}
#[cfg(test)]
fn unparse_dict_entries_with_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
out.write_bytes(b"<<")?;
for (key, value) in visible_dict_entries(entries)? {
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if try_write_sig_contents_with_string_writer(value, force_hex_string, out)? {
continue;
}
unparse_child_with_string_writer(value, out, write_string)?;
}
out.write_bytes(b" >>")?;
Ok(())
}
#[cfg(test)]
fn unparse_child_qdf_with_string_writer<F>(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
if let Some(object_ref) = handle.object_ref() {
write_object_ref(out, object_ref)?;
return Ok(());
}
unparse_object_walk_qdf_with_string_writer(handle, indent, out, write_string)
}
#[cfg(test)]
fn unparse_container_qdf_with_string_writer<F>(
container: UnparseContainer,
indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match container {
UnparseContainer::Array(children) => {
out.write_bytes(b"[")?;
out.write_bytes(b"\n")?;
for child in children {
push_spaces(out, indent + 2)?;
unparse_child_qdf_with_string_writer(&child, indent + 2, out, write_string)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b"]")?;
}
UnparseContainer::Dictionary(entries) => {
unparse_dict_entries_qdf_with_string_writer(&entries, indent, out, write_string)?;
}
UnparseContainer::Stream(stream_dict) => {
unparse_object_walk_qdf_with_string_writer(&stream_dict, indent, out, write_string)?;
}
}
Ok(())
}
#[cfg(test)]
fn unparse_object_walk_qdf_with_string_writer<F>(
handle: &ObjectHandle,
indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
unparse_object_walk_hub(|| {
if handle.is_reserved() {
return Err(reserved_unparse_error());
}
handle.try_dereference()?;
let container = handle.with_value(|value| match value {
Some(value) => {
if let Some(container) = snapshot_unparse_container(value) {
Ok(Some(container))
} else {
unparse_object_value_qdf_with_string_writer(value, indent, out, write_string)
.map(|()| None)
}
}
None => {
out.write_bytes(b"null")?;
Ok(None)
}
})?;
match container {
Some(container) => {
unparse_container_qdf_with_string_writer(container, indent, out, write_string)
}
None => Ok(()),
}
})
}
#[cfg(test)]
fn unparse_object_value_qdf_with_string_writer<F>(
value: &ObjectValue,
_indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
match value {
ObjectValue::String(bytes) => write_string(out, bytes),
_ => unparse_object_value(value, out),
}
}
#[cfg(test)]
fn unparse_dict_entries_qdf_with_string_writer<F>(
entries: &[(Vec<u8>, ObjectHandle)],
indent: usize,
out: &mut OutputSink<'_>,
write_string: &mut F,
) -> Result<()>
where
F: FnMut(&mut OutputSink<'_>, &[u8]) -> Result<()>,
{
out.write_bytes(b"<<\n")?;
for (key, value) in visible_dict_entries(entries)? {
push_spaces(out, indent + 2)?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
let force_hex_string =
key.as_slice() == b"/Contents" && dict_is_sig_with_byte_range(entries)?;
if try_write_sig_contents_with_string_writer(value, force_hex_string, out)? {
out.write_bytes(b"\n")?;
continue;
}
unparse_child_qdf_with_string_writer(value, indent + 2, out, write_string)?;
out.write_bytes(b"\n")?;
}
push_spaces(out, indent)?;
out.write_bytes(b">>")?;
Ok(())
}
#[cfg(test)]
fn unparse_trailer_entries(
entries: &[(Vec<u8>, ObjectHandle)],
xref_stream: bool,
mut id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
out: &mut OutputSink<'_>,
) -> Result<()> {
if !xref_stream {
out.write_bytes(b"trailer <<")?;
}
let mut id_value: Option<&ObjectHandle> = None;
let mut encrypt_value: Option<&ObjectHandle> = None;
for (key, value) in entries {
match key.as_slice() {
b"/ID" => {
id_value = Some(value);
continue;
}
b"/Encrypt" => {
encrypt_value = Some(value);
continue;
}
_ => {}
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
unparse_child(value, out)?;
}
if let Some(value) = id_value {
out.write_bytes(b" /ID ")?;
match id_writer.as_mut() {
Some(write_id) => write_id(out)?,
None => write_id_style_value_handle(value, out)?,
}
}
if let Some(value) = encrypt_value {
out.write_bytes(b" /Encrypt ")?;
unparse_child(value, out)?;
}
out.write_bytes(b" >>")?;
Ok(())
}
#[allow(clippy::too_many_arguments)] fn unparse_trailer_entries_with_ref_map(
entries: &[(Vec<u8>, ObjectHandle)],
xref_stream: bool,
qdf: bool,
mut id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
out: &mut OutputSink<'_>,
) -> Result<()> {
let qpdf_map = qpdf_obj_gen_map_from_object_ref_map(map);
let qpdf_removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
if qdf {
out.write_bytes(b"trailer <<\n")?;
} else if !xref_stream {
out.write_bytes(b"trailer <<")?;
}
let mut id_value: Option<&ObjectHandle> = None;
let mut encrypt_value: Option<&ObjectHandle> = None;
for (key, value) in entries {
match key.as_slice() {
b"/ID" => {
id_value = Some(value);
continue;
}
b"/Encrypt" => {
encrypt_value = Some(value);
continue;
}
_ => {}
}
let writer_owned_root = key.as_slice() == b"/Root";
if !writer_owned_root && suppress_null_values && value.try_is_null()? {
continue;
}
if !writer_owned_root && is_removed_reference(value, removed_refs) {
continue;
}
if qdf {
out.write_bytes(b" ")?;
} else {
out.write_bytes(b" ")?;
}
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
if key.as_slice() == b"/Root" && value.object_ref().is_none() {
if qdf {
unparse_child_qdf_with_ref_map(value, 2, out, &qpdf_map, &qpdf_removed_refs)?;
} else {
unparse_child_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?;
}
} else if matches!(key.as_slice(), b"/Root" | b"/Encrypt") {
if qdf {
unparse_child_qdf(value, 2, out)?; } else {
unparse_child(value, out)?;
}
} else if qdf {
unparse_child_qdf_with_ref_map(value, 2, out, &qpdf_map, &qpdf_removed_refs)?;
} else {
unparse_child_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?;
}
if qdf {
out.write_bytes(b"\n")?;
}
}
if let Some(value) = id_value {
if qdf {
out.write_bytes(b" /ID ")?;
} else {
out.write_bytes(b" /ID ")?;
}
match id_writer.as_mut() {
Some(write_id) => write_id(out)?,
None => {
write_id_style_value_handle_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?
}
}
}
if let Some(value) = encrypt_value {
out.write_bytes(b" /Encrypt ")?;
unparse_child(value, out)?;
}
if qdf {
if id_value.is_some() || encrypt_value.is_some() {
out.write_bytes(b"\n")?;
}
out.write_bytes(b">>\n")?;
} else {
out.write_bytes(b" >>")?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn unparse_trailer_entries_with_ref_map_and_kind(
entries: &[(Vec<u8>, ObjectHandle)],
kind: TrailerKind,
xref_stream: bool,
qdf: bool,
mut id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
direct_root: Option<&ObjectHandle>,
out: &mut OutputSink<'_>,
) -> Result<()> {
let qpdf_map = qpdf_obj_gen_map_from_object_ref_map(map);
let qpdf_removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
let (size, prev, second_half) = match kind {
TrailerKind::Normal { size } => (size, None, false),
TrailerKind::LinearizedFirst { size, prev } => (size, Some(prev), false),
TrailerKind::LinearizedSecond { size } => (size, None, true),
};
if !xref_stream {
out.write_bytes(b"trailer <<")?;
}
if qdf {
out.write_bytes(b"\n")?;
}
if second_half {
if qdf {
out.write_bytes(b" /Size ")?;
} else {
out.write_bytes(b" /Size ")?;
}
write_decimal_i64(out, size)?;
if qdf {
out.write_bytes(b"\n")?;
}
}
let mut id_value: Option<&ObjectHandle> = None;
let mut encrypt_value: Option<&ObjectHandle> = None;
for (key, value) in entries {
match key.as_slice() {
b"/ID" => {
id_value = Some(value);
continue;
}
b"/Encrypt" => {
if !second_half {
encrypt_value = Some(value);
}
continue;
}
b"/Prev" => continue,
_ if second_half && key.as_slice() == b"/Size" => continue,
_ if second_half && key.as_slice() != b"/Size" => continue,
_ => {}
}
if key.as_slice() == b"/Size" {
if suppress_null_values && value.try_is_null()? {
continue;
}
if qdf {
out.write_bytes(b" ")?;
} else {
out.write_bytes(b" ")?;
}
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
write_decimal_i64(out, size)?;
if let Some(prev) = prev {
out.write_bytes(b" /Prev ")?;
write_decimal_u64(out, prev)?;
let padding = 21usize.saturating_sub(decimal_u64_len(prev));
push_spaces(out, padding)?;
}
if qdf {
out.write_bytes(b"\n")?;
}
continue;
}
let writer_owned_root = key.as_slice() == b"/Root";
if !writer_owned_root && suppress_null_values && value.try_is_null()? {
continue;
}
if !writer_owned_root && is_removed_reference(value, removed_refs) {
continue;
}
if qdf {
out.write_bytes(b" ")?;
} else {
out.write_bytes(b" ")?;
}
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
if key.as_slice() == b"/Root" && value.object_ref().is_none() {
if qdf {
unparse_child_qdf_with_ref_map(value, 2, out, &qpdf_map, &qpdf_removed_refs)?;
} else if let Some(direct_root) = direct_root {
unparse_object_with_ref_map_and_direct_streams(
direct_root,
out,
map,
removed_refs,
false,
)?; } else {
unparse_child_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?;
}
} else if key.as_slice() == b"/Root" {
if qdf {
unparse_child_qdf(value, 2, out)?;
} else {
unparse_child(value, out)?;
}
} else if qdf {
unparse_child_qdf_with_ref_map(value, 2, out, &qpdf_map, &qpdf_removed_refs)?;
} else {
unparse_child_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?;
}
if qdf {
out.write_bytes(b"\n")?;
}
}
if let Some(value) = id_value {
if qdf {
out.write_bytes(b" /ID ")?;
} else {
out.write_bytes(b" /ID ")?;
}
match id_writer.as_mut() {
Some(write_id) => write_id(out)?,
None => {
write_id_style_value_handle_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?
}
}
}
if let Some(value) = encrypt_value {
out.write_bytes(b" /Encrypt ")?;
unparse_child(value, out)?;
}
if qdf {
if id_value.is_some() || encrypt_value.is_some() {
out.write_bytes(b"\n")?;
}
out.write_bytes(b">>\n")?;
} else {
out.write_bytes(b" >>")?;
}
Ok(())
}
#[cfg(test)]
fn unparse_dictionary_entries_with_ref_map_and_id_writer(
entries: &[(Vec<u8>, ObjectHandle)],
mut id_writer: Option<crate::pdf_syntax::TrailerIdWriter>,
map: &dyn Fn(ObjectRef) -> Result<ObjectRef>,
removed_refs: &BTreeSet<ObjectRef>,
suppress_null_values: bool,
out: &mut OutputSink<'_>,
) -> Result<()> {
let qpdf_map = qpdf_obj_gen_map_from_object_ref_map(map);
let qpdf_removed_refs = qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
out.write_bytes(b"<<")?;
for (key, value) in entries {
let writer_owned_root = key.as_slice() == b"/Root";
if !writer_owned_root && suppress_null_values && value.try_is_null()? {
continue;
}
if !writer_owned_root && is_removed_reference(value, removed_refs) {
continue;
}
out.write_bytes(b" ")?;
write_dictionary_key(out, key)?;
out.write_bytes(b" ")?;
if key.as_slice() == b"/ID" {
match id_writer.as_mut() {
Some(write_id) => write_id(out)?,
None => write_id_style_value_handle_with_ref_map(
value,
out,
&qpdf_map,
&qpdf_removed_refs,
)?, }
} else if matches!(key.as_slice(), b"/Root" | b"/Encrypt") {
unparse_child(value, out)?; } else {
unparse_child_with_ref_map(value, out, &qpdf_map, &qpdf_removed_refs)?;
}
}
out.write_bytes(b" >>")?;
Ok(())
}
#[cfg(test)]
fn write_id_style_value_handle(value: &ObjectHandle, out: &mut OutputSink<'_>) -> Result<()> {
if value.object_ref().is_some() {
return unparse_child(value, out);
}
let compact: Option<(Vec<u8>, Vec<u8>)> = value.with_value(|v| match v {
Some(ObjectValue::Array(items)) if items.len() == 2 => {
let string_bytes = |item: &ObjectHandle| {
item.with_value(|iv| match iv {
Some(ObjectValue::String(s)) => Some(s.clone()),
_ => None,
})
};
match (string_bytes(&items[0]), string_bytes(&items[1])) {
(Some(b0), Some(b1)) => Some((b0, b1)),
_ => None,
}
}
_ => None,
});
match compact {
Some((b0, b1)) => {
out.write_bytes(b"[")?;
crate::pdf_syntax::write_hex_string(out, &b0)?;
crate::pdf_syntax::write_hex_string(out, &b1)?;
out.write_bytes(b"]")?;
Ok(())
}
None => unparse_child(value, out),
}
}
fn write_id_style_value_handle_with_ref_map(
value: &ObjectHandle,
out: &mut OutputSink<'_>,
map: &QpdfObjGenMap<'_>,
removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<()> {
if value
.qpdf_obj_gen()
.is_some_and(|object_gen| object_gen.is_indirect())
{
return unparse_child_with_ref_map(value, out, map, removed_refs);
}
let compact: Option<(Vec<u8>, Vec<u8>)> = value.with_value(|v| match v {
Some(ObjectValue::Array(items)) if items.len() == 2 => {
let string_bytes = |item: &ObjectHandle| {
item.with_value(|iv| match iv {
Some(ObjectValue::String(s)) => Some(s.clone()),
_ => None,
})
};
match (string_bytes(&items[0]), string_bytes(&items[1])) {
(Some(b0), Some(b1)) => Some((b0, b1)),
_ => None,
}
}
_ => None,
});
match compact {
Some((b0, b1)) => {
out.write_bytes(b"[")?;
crate::pdf_syntax::write_hex_string(out, &b0)?;
crate::pdf_syntax::write_hex_string(out, &b1)?;
out.write_bytes(b"]")?;
Ok(())
}
None => unparse_object_walk_with_ref_map(value, out, map, removed_refs),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Pdf;
use std::rc::Rc;
#[test]
fn scalar_writer_uses_stack_decimal_emission() {
let source = include_str!("object.rs").replace("\r\n", "\n");
let start = source
.find("pub(crate) fn unparse_object_value")
.expect("scalar writer");
let body = &source[start
..source[start..]
.find("\n\ntype QpdfObjGenMap")
.expect("scalar writer end")
+ start];
assert!(
body.contains("ObjectValue::Integer(v) => write_decimal_i64"),
"writer scalar integers must use the stack decimal helper"
);
assert!(
!body.contains("ObjectValue::Integer(v) => out.write_bytes(v.to_string().as_bytes())"),
"writer scalar integers must not allocate a temporary String"
);
}
#[test]
fn qdf_mapped_serializer_does_not_snapshot_container_edges() {
let source = include_str!("object.rs");
let start = source
.find("fn unparse_object_walk_qdf_with_ref_map")
.expect("qdf mapped serializer");
let body = &source[start
..source[start..]
.find("\nfn unparse_array_qdf_with_ref_map")
.expect("qdf mapped serializer end")
+ start];
assert!(
body.contains("unparse_array_qdf_with_ref_map"),
"qdf mapped serializer must walk live arrays"
);
assert!(
body.contains("unparse_dictionary_qdf_with_ref_map"),
"qdf mapped serializer must walk live dictionaries"
);
assert!(
!body.contains("snapshot_unparse_container"),
"qdf mapped serializer must not clone a second container snapshot"
);
}
#[test]
fn compact_mapped_serializer_does_not_snapshot_container_edges() {
let source = include_str!("object.rs").replace("\r\n", "\n");
let start = source
.find("fn unparse_object_walk_with_ref_map")
.expect("compact mapped serializer");
let body = &source[start
..source[start..]
.find("\n\nenum RefMapContainer")
.expect("compact mapped serializer end")
+ start];
assert!(
body.contains("unparse_array_with_ref_map"),
"compact mapped serializer must walk live arrays"
);
assert!(
body.contains("unparse_dictionary_with_ref_map"),
"compact mapped serializer must walk live dictionaries"
);
assert!(
!body.contains("snapshot_unparse_container"),
"compact mapped serializer must not clone a second container snapshot"
);
}
#[test]
fn qdf_indentation_batches_space_runs() {
let source = include_str!("object.rs").replace("\r\n", "\n");
let start = source
.find("fn push_spaces")
.expect("qdf indentation helper");
let body = &source[start
..source[start..]
.find("\n\n// QDF-mode sibling")
.expect("qdf indentation helper end")
+ start];
assert!(
body.contains("SPACE_BLOCK") || body.contains("SPACES"),
"qdf indentation must write static space blocks"
);
assert!(
!body.contains("for _ in 0..n"),
"qdf indentation must not issue one output call per space"
);
}
#[test]
fn qdf_indentation_writes_large_space_runs_in_blocks() -> Result<()> {
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| push_spaces(out, 128))?;
assert_eq!(output, vec![b' '; 128]);
Ok(())
}
#[test]
fn child_walkers_reject_uninitialized_handles_at_their_boundaries() {
let handle = ObjectHandle::uninitialized();
let map = |_: QpdfObjGen| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let removed = BTreeSet::new();
let mut ordinary = Vec::new();
assert!(
super::super::output::with_buffer_sink(&mut ordinary, |out| {
unparse_child(&handle, out)
})
.is_err()
);
let mut mapped = Vec::new();
assert!(super::super::output::with_buffer_sink(&mut mapped, |out| {
unparse_child_with_ref_map(&handle, out, &map, &removed)
})
.is_err());
let mut dynamic_map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let mut dynamic = Vec::new();
assert!(super::super::output::with_buffer_sink(&mut dynamic, |out| {
unparse_child_with_dynamic_ref_map(&handle, out, &mut dynamic_map, &BTreeSet::new())
})
.is_err());
let mut string_map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: None,
qdf_mode: false,
};
let mut string_probe = Vec::new();
super::super::output::with_buffer_sink(&mut string_probe, |out| strings(out, b"probe"))
.expect("dynamic string callback should write direct strings");
assert_eq!(string_probe, b"(probe)");
let mut dynamic_strings = Vec::new();
assert!(
super::super::output::with_buffer_sink(&mut dynamic_strings, |out| {
unparse_child_with_dynamic_ref_map_and_string_writer(
&handle,
out,
&mut string_map,
&BTreeSet::new(),
&mut strings,
&mut direct_stream_writer,
)
})
.is_err()
);
}
#[test]
fn object_zero_child_serializes_as_null_through_the_scalar_container_route() -> Result<()> {
let zero = ObjectHandle::new_indirect_unresolved(ObjectRef::new(0, 0), -1);
zero.set_resolved(ObjectValue::Integer(42));
assert!(zero.is_direct(), "qpdf reports object zero as non-indirect");
assert!(
zero.qpdf_obj_gen().is_some(),
"the raw identity survives that predicate"
);
let array = ObjectHandle::array(vec![
zero,
ObjectHandle::integer(7),
ObjectHandle::string(b"s".to_vec()),
]);
let mut map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: None,
qdf_mode: false,
};
let mut bytes = Vec::new();
super::super::output::with_buffer_sink(&mut bytes, |out| {
unparse_child_with_dynamic_ref_map_and_string_writer(
&array,
out,
&mut map,
&BTreeSet::new(),
&mut strings,
&mut direct_stream_writer,
)
})?;
assert_eq!(bytes, b"[ null 7 (s) ]");
Ok(())
}
#[test]
fn qdf_dynamic_writer_walks_direct_streams_and_skips_null_or_removed_children() -> Result<()> {
let removed = ObjectHandle::new_indirect_unresolved(ObjectRef::new(9, 0), -1);
let stream = ObjectHandle::stream(
ObjectHandle::dictionary(vec![
(b"/Null".to_vec(), ObjectHandle::null()),
(b"/Removed".to_vec(), removed.clone()),
(
b"/Array".to_vec(),
ObjectHandle::array(vec![removed.clone()]),
),
(b"/Keep".to_vec(), ObjectHandle::integer(2)),
]),
Rc::new(b"payload".to_vec()),
);
let removed_refs = BTreeSet::from([QpdfObjGen::new(9, 0)]);
let mut map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(9, 0));
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
unparse_object_qdf_with_dynamic_ref_map(&stream, 0, out, &mut map, &removed_refs)
})?;
let text = String::from_utf8_lossy(&output);
assert!(text.contains("/Keep"));
assert!(text.contains("/Array"));
assert!(!text.contains("/Null"));
assert!(!text.contains("/Removed"));
assert!(text.contains("null"));
let mut scalar_output = Vec::new();
let mut scalar_map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
super::super::output::with_buffer_sink(&mut scalar_output, |out| {
unparse_object_qdf_with_dynamic_ref_map(
&ObjectHandle::integer(3),
0,
out,
&mut scalar_map,
&BTreeSet::new(),
)
})?;
assert_eq!(scalar_output, b"3");
Ok(())
}
#[test]
fn dictionary_key_writer_preserves_qpdfs_first_byte() {
let mut out = Vec::new();
super::super::output::with_buffer_sink(&mut out, |out| {
write_dictionary_key(out, b"/Canonical")?;
out.write_bytes(b" ")?;
write_dictionary_key(out, b"Raw")
})
.unwrap();
assert_eq!(out, b"/Canonical Raw");
}
#[test]
fn object_ref_map_adapter_rejects_an_unprojectable_raw_identity() {
let map = |object_ref: ObjectRef| Ok::<ObjectRef, Error>(object_ref);
let raw_map = super::qpdf_obj_gen_map_from_object_ref_map(&map);
let error = raw_map(QpdfObjGen::new(5, 65_536))
.expect_err("an ObjectRef adapter must reject an out-of-range generation");
assert!(error
.to_string()
.contains("cannot be used by an ObjectRef map"));
}
#[test]
fn raw_object_writer_keeps_array_null_and_drops_removed_dictionary_key() -> Result<()> {
let mut pdf = Pdf::empty()?;
let kept = pdf.get_object_handle_by_raw_identity(6, 65_536);
kept.set_resolved(ObjectValue::Integer(7));
let removed = pdf.get_object_handle_by_raw_identity(5, 65_536);
let value = ObjectHandle::dictionary(vec![
(
b"/Array".to_vec(),
ObjectHandle::array(vec![removed.clone()]),
),
(b"/Kept".to_vec(), kept.clone()),
(b"/Removed".to_vec(), removed.clone()),
]);
let removed_refs = BTreeSet::from([QpdfObjGen::new(5, 65_536)]);
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
ObjectWriterEmission::unparse_object_with_qpdf_obj_gen_map_and_removed(
&value,
out,
&|object_gen| {
assert_eq!(object_gen, QpdfObjGen::new(6, 65_536));
Ok(ObjectRef::new(7, 0))
},
&removed_refs,
)
})?;
assert_eq!(output, b"<< /Array [ null ] /Kept 7 0 R >>");
Ok(())
}
#[test]
fn compact_stream_ref_map_rejects_a_reserved_object() {
let reserved = ObjectHandle::new_reserved_direct();
let error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
ObjectWriterEmission::unparse_stream_body_with_ref_map_and_removed_with_options(
&reserved,
out,
StreamDictionaryOptions::preserve(),
&|_| Ok(ObjectRef::new(1, 0)), &BTreeSet::new(),
)
})
.expect_err("reserved stream objects must be rejected");
assert!(error.to_string().contains("reserved object"));
}
#[test]
fn writer_name_emission_uses_canonical_keys_without_the_legacy_bridge() {
let source = include_str!("object.rs");
let legacy_name = ["legacy", "dictionary_key"].join("_");
assert!(
!source.contains(&legacy_name),
"writer name emission must consume canonical slash-prefixed keys directly"
);
}
#[test]
fn dictionary_ref_map_writer_accepts_a_trailer_id_callback() -> Result<()> {
let dictionary = ObjectHandle::dictionary(vec![
(
b"/ID".to_vec(),
ObjectHandle::array(vec![
ObjectHandle::string(b"old-a".to_vec()),
ObjectHandle::string(b"old-b".to_vec()),
]),
),
(b"/Keep".to_vec(), ObjectHandle::integer(1)),
]);
let mut output = Vec::new();
let mut write_id = |out: &mut OutputSink<'_>| out.write_bytes(b"[<01><02>]");
let map = |object_ref: ObjectRef| Ok(object_ref);
super::super::output::with_buffer_sink(&mut output, |out| {
dictionary.write_dictionary_with_ref_map_and_id_writer(
out,
Some(&mut write_id),
&map,
&BTreeSet::new(),
false,
)
})?; assert_eq!(output, b"<< /ID [<01><02>] /Keep 1 >>");
Ok(())
}
#[test]
fn mapped_stream_writer_overrides_length_and_suppresses_null_children() -> Result<()> {
let stream = ObjectHandle::stream(
ObjectHandle::dictionary(vec![
(b"/Length".to_vec(), ObjectHandle::integer(99)),
(b"/Null".to_vec(), ObjectHandle::null()),
(b"/Keep".to_vec(), ObjectHandle::integer(1)),
]),
Rc::new(b"abc".to_vec()),
);
let mut output = Vec::new();
let removed = BTreeSet::new();
let map = |object_ref: ObjectRef| Ok(object_ref);
super::super::output::with_buffer_sink(&mut output, |out| {
stream.unparse_stream_body_with_ref_map_and_removed_and_length(
out, false, &map, &removed, 3,
)
})?;
assert_eq!(output, b"<< /Keep 1 /Length 3 >>");
let dictionary =
ObjectHandle::dictionary(vec![(b"/Keep".to_vec(), ObjectHandle::integer(1))]);
let mut dictionary_output = Vec::new();
super::super::output::with_buffer_sink(&mut dictionary_output, |out| {
dictionary.unparse_stream_body_with_ref_map_and_removed_and_length(
out, false, &map, &removed, 2,
)
})?; assert_eq!(dictionary_output, b"<< /Keep 1 /Length 2 >>");
let scalar = ObjectHandle::integer(1);
let mut scalar_output = Vec::new();
super::super::output::with_buffer_sink(&mut scalar_output, |out| {
scalar.unparse_stream_body_with_ref_map_and_removed_and_length(
out, false, &map, &removed, 1,
)
})?; assert_eq!(scalar_output, b"<< /Length 1 >>");
let malformed_stream =
ObjectHandle::stream(ObjectHandle::integer(1), Rc::new(b"x".to_vec()));
let mut malformed_output = Vec::new();
super::super::output::with_buffer_sink(&mut malformed_output, |out| {
malformed_stream.unparse_stream_body_with_ref_map_and_removed_and_length(
out, false, &map, &removed, 1,
)
})?; assert_eq!(malformed_output, b"<< /Length 1 >>");
let reserved = ObjectHandle::new_reserved_direct();
let error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
reserved.unparse_stream_body_with_ref_map_and_removed_and_length(
out, false, &map, &removed, 0,
)
})
.expect_err("reserved stream emission must be rejected");
assert!(error.to_string().contains("reserved object"));
Ok(())
}
#[test]
fn live_mapped_stream_writer_overrides_length_without_rebuilding_dictionary() -> Result<()> {
let mut pdf = Pdf::empty()?;
let mapped = pdf.get_object_handle_by_raw_identity(7, 0);
mapped.set_resolved(ObjectValue::Integer(2));
let dictionary = ObjectHandle::dictionary(vec![
(b"/Length".to_vec(), ObjectHandle::integer(99)),
(b"/Null".to_vec(), ObjectHandle::null()),
(b"/Keep".to_vec(), ObjectHandle::integer(1)),
(b"/Ref".to_vec(), mapped),
]);
let map = |object_gen: QpdfObjGen| {
Ok::<ObjectRef, Error>(object_gen.to_object_ref().expect("test identity maps"))
};
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&dictionary,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
3,
)
})?;
assert_eq!(output, b"<< /Keep 1 /Ref 7 0 R /Length 3 >>");
let scalar = ObjectHandle::integer(5);
assert!(dictionary_entry_handle(&scalar, b"/Missing").is_none());
let mut scalar_output = Vec::new();
super::super::output::with_buffer_sink(&mut scalar_output, |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&scalar,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
1,
)
})?;
assert_eq!(scalar_output, b"<< /Length 1 >>");
let signature = ObjectHandle::dictionary(vec![
(
b"/ByteRange".to_vec(),
ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(1)]),
),
(
b"/Contents".to_vec(),
ObjectHandle::string(vec![0x01, 0xab]),
),
(b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
]);
let mut signature_output = Vec::new();
super::super::output::with_buffer_sink(&mut signature_output, |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&signature,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
2,
)
})?;
assert_eq!(
signature_output,
b"<< /ByteRange [ 0 1 ] /Contents <01ab> /Type /Sig /Length 2 >>"
);
let non_string_signature = ObjectHandle::dictionary(vec![
(
b"/ByteRange".to_vec(),
ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(1)]),
),
(b"/Contents".to_vec(), ObjectHandle::integer(7)),
(b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
]);
let mut non_string_signature_output = Vec::new();
super::super::output::with_buffer_sink(&mut non_string_signature_output, |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&non_string_signature,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
1,
)
})?;
assert_eq!(
non_string_signature_output,
b"<< /ByteRange [ 0 1 ] /Contents 7 /Type /Sig /Length 1 >>"
);
let reserved = ObjectHandle::new_reserved_direct();
let reserved_error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&reserved,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
0,
)
})
.expect_err("reserved live stream dictionaries must be rejected");
assert!(reserved_error.to_string().contains("reserved object"));
Ok(())
}
#[test]
fn length_override_snapshot_fallback_drops_source_length_before_null_probe() -> Result<()> {
let mut pdf = Pdf::empty()?;
let mapped = pdf.get_object_handle_by_raw_identity(7, 0);
mapped.set_resolved(ObjectValue::Integer(2));
let dangling_length = ObjectHandle::new_indirect_unresolved(ObjectRef::new(91, 0), -1);
let dictionary = ObjectHandle::dictionary(vec![
(
b"/Filter".to_vec(),
ObjectHandle::array(vec![
ObjectHandle::name(b"FlateDecode".to_vec()),
ObjectHandle::name(b"ASCIIHexDecode".to_vec()),
]),
),
(b"/Length".to_vec(), dangling_length),
(b"/Ref".to_vec(), mapped),
]);
let map = |object_gen: QpdfObjGen| {
Ok::<ObjectRef, Error>(object_gen.to_object_ref().expect("test identity maps"))
};
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
ObjectWriterEmission::unparse_stream_body_with_qpdf_obj_gen_map_and_removed_with_options_and_length(
&dictionary,
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
3,
)
})?;
assert_eq!(
output,
b"<< /Filter [ /FlateDecode /ASCIIHexDecode ] /Ref 7 0 R /Length 3 >>"
);
Ok(())
}
#[test]
fn stream_dictionary_owner_handles_missing_crypt_parameters_and_qdf_filter_append() -> Result<()>
{
let pdf = Pdf::empty()?;
let stream = pdf.new_stream_with_data(Rc::new(b"abc".to_vec()))?;
stream.as_stream_dict().unwrap().replace_key(
b"/Filter",
ObjectHandle::array(vec![
ObjectHandle::name(b"Crypt".to_vec()),
ObjectHandle::name(b"ASCIIHexDecode".to_vec()),
]),
)?; let map = |object_ref: ObjectRef| Ok(object_ref);
let missing_decode_error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
stream.unparse_stream_body_with_ref_map_and_removed_with_options(
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
)
})
.expect_err("qpdf propagates a missing DecodeParms erase warning");
assert_eq!(
missing_decode_error.to_string(),
" -> dictionary key /DecodeParms: operation for array attempted on object of type null: ignoring attempt to erase item"
);
stream
.as_stream_dict()
.unwrap()
.replace_key(b"/DecodeParms", ObjectHandle::array(Vec::new()))?;
let mut compact = Vec::new();
super::super::output::with_buffer_sink(&mut compact, |out| {
stream.unparse_stream_body_with_ref_map_and_removed_with_options(
out,
StreamDictionaryOptions::preserve(),
&map,
&BTreeSet::new(),
)
})?; assert!(String::from_utf8_lossy(&compact).contains("/Filter [ /ASCIIHexDecode ]"));
let policy = StreamDictionaryOptions::new(true, true);
let mut qdf = Vec::new();
super::super::output::with_buffer_sink(&mut qdf, |out| {
stream.unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_options(
out,
0,
&map,
&BTreeSet::new(),
None,
policy,
)
})?; let qdf_text = String::from_utf8(qdf).unwrap();
assert!(qdf_text.contains("/Filter /FlateDecode"));
assert!(!qdf_text.contains("ASCIIHexDecode"));
let mut qdf_string = Vec::new();
let mut callback = |out: &mut OutputSink<'_>, value: &[u8]| out.write_bytes(value);
super::super::output::with_buffer_sink(&mut qdf_string, |out| {
stream.unparse_stream_body_qdf_with_ref_map_and_removed_and_length_with_string_writer_with_options(
out,
0,
&map,
&BTreeSet::new(),
None,
policy,
&mut callback,
)
})?; assert!(String::from_utf8(qdf_string)
.unwrap()
.contains("/Filter /FlateDecode"));
Ok(())
}
#[test]
fn dynamic_ref_map_emits_arrays_and_stream_dictionary_children() -> Result<()> {
let mut pdf = Pdf::empty()?;
let child = pdf.make_indirect_object_handle(ObjectHandle::integer(42))?;
let removed_child = pdf.make_indirect_object_handle(ObjectHandle::integer(9))?;
let zero_ref = ObjectHandle::new_indirect_unresolved(ObjectRef::new(0, 0), -1);
let array = ObjectHandle::array(vec![
child.clone(),
removed_child.clone(),
zero_ref,
ObjectHandle::integer(7),
ObjectHandle::string(b"dynamic-string".to_vec()),
]);
let mut mapped = Vec::new();
let mut map = |handle: &ObjectHandle| {
let object_ref = handle.object_ref().expect("dynamic child is indirect");
mapped.push(object_ref);
Ok(object_ref)
};
let mut output = Vec::new();
let removed = [removed_child.object_ref().unwrap()].into_iter().collect();
super::super::output::with_buffer_sink(&mut output, |out| {
array.unparse_object_with_dynamic_ref_map(out, &mut map, &removed)
})?;
assert_eq!(mapped, vec![child.object_ref().unwrap()]);
assert!(String::from_utf8_lossy(&output).contains(&child.object_ref().unwrap().to_string()));
assert!(String::from_utf8_lossy(&output).contains("null"));
let mut string_output = Vec::new();
let mut string_map = |handle: &ObjectHandle| {
Ok::<ObjectRef, Error>(
handle
.object_ref()
.expect("dynamic string child is indirect"),
)
};
let mut write_string = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: Some(crate::writer::NewlineBeforeEndstream::Never),
qdf_mode: false,
};
super::super::output::with_buffer_sink(&mut string_output, |out| {
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&array,
out,
&mut string_map,
&removed,
&mut write_string,
&mut direct_stream_writer,
)
})?;
assert!(String::from_utf8_lossy(&string_output).contains("null"));
let reserved = ObjectHandle::new_reserved_direct();
let error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
reserved.unparse_object_with_dynamic_ref_map(
out,
&mut |_| Ok(ObjectRef::new(1, 0)),
&BTreeSet::new(),
)
})
.expect_err("reserved dynamic object must be rejected");
assert!(error.to_string().contains("reserved object"));
let dictionary = ObjectHandle::dictionary(vec![
(b"/Removed".to_vec(), removed_child.clone()),
(b"/Mapped".to_vec(), child.clone()),
]);
let mut dictionary_output = Vec::new();
let mut dictionary_map =
|handle: &ObjectHandle| Ok(handle.object_ref().expect("dictionary child is indirect"));
super::super::output::with_buffer_sink(&mut dictionary_output, |out| {
dictionary.unparse_object_with_dynamic_ref_map(out, &mut dictionary_map, &removed)
})?; let dictionary_text = String::from_utf8_lossy(&dictionary_output);
assert!(dictionary_text.contains("/Mapped"));
assert!(!dictionary_text.contains("/Removed"));
let mut string_dictionary_output = Vec::new();
super::super::output::with_buffer_sink(&mut string_dictionary_output, |out| {
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&dictionary,
out,
&mut string_map,
&removed,
&mut write_string,
&mut direct_stream_writer,
)
})?;
assert!(!String::from_utf8_lossy(&string_dictionary_output).contains("/Removed"));
let stream_length = pdf.make_indirect_object_handle(ObjectHandle::integer(4))?;
let stream_child = pdf.make_indirect_object_handle(ObjectHandle::integer(8))?;
let stream = ObjectHandle::stream(
ObjectHandle::dictionary(vec![
(b"/Length".to_vec(), stream_length),
(b"/Child".to_vec(), stream_child),
]),
Rc::new(b"body".to_vec()),
);
let mut stream_object_output = Vec::new();
let mut stream_object_map =
|handle: &ObjectHandle| Ok(handle.object_ref().expect("stream child is indirect"));
super::super::output::with_buffer_sink(&mut stream_object_output, |out| {
stream.unparse_object_with_dynamic_ref_map(
out,
&mut stream_object_map,
&BTreeSet::new(),
)
})?; assert!(String::from_utf8_lossy(&stream_object_output).contains("/Child"));
let stream = pdf.new_stream_with_data(Rc::new(b"body".to_vec()))?;
let stream_ref_child = pdf.make_indirect_object_handle(ObjectHandle::integer(11))?;
stream
.as_stream_dict()
.unwrap()
.replace_key(b"/Length", stream_ref_child.clone())?;
stream
.as_stream_dict()
.unwrap()
.replace_key(b"/Child", child.clone())?;
stream
.as_stream_dict()
.unwrap()
.replace_key(b"/Label", ObjectHandle::string(b"dynamic-label".to_vec()))?;
stream
.as_stream_dict()
.unwrap()
.replace_key(b"/Removed", removed_child.clone())?;
let mut stream_output = Vec::new();
let mut stream_map =
|handle: &ObjectHandle| Ok(handle.object_ref().expect("dynamic child is indirect"));
super::super::output::with_buffer_sink(&mut stream_output, |out| {
stream
.as_stream_dict()
.unwrap()
.unparse_stream_body_with_dynamic_ref_map(
out,
StreamDictionaryOptions::new(false, true),
&mut stream_map,
&removed,
)
})?; assert!(String::from_utf8_lossy(&stream_output).contains("/Length"));
assert!(String::from_utf8_lossy(&stream_output).contains("/Filter /FlateDecode"));
let mut dynamic_string_output = Vec::new();
let mut dynamic_string_map =
|handle: &ObjectHandle| Ok(handle.object_ref().expect("dynamic length is indirect"));
let mut dynamic_string_writer = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
super::super::output::with_buffer_sink(&mut dynamic_string_output, |out| {
stream
.as_stream_dict()
.unwrap()
.unparse_stream_body_with_dynamic_ref_map_and_string_writer(
out,
StreamDictionaryOptions::new(false, true),
&mut dynamic_string_map,
&removed,
&mut dynamic_string_writer,
&mut direct_stream_writer,
)
})?;
let dynamic_string_text = String::from_utf8_lossy(&dynamic_string_output);
assert!(dynamic_string_text.contains("/Length"));
assert!(dynamic_string_text.contains("/Filter /FlateDecode"));
Ok(())
}
#[test]
fn default_dynamic_direct_stream_writer_obeys_qdf_and_newline_policies() -> Result<()> {
let mut pdf = Pdf::empty()?;
let child = pdf.make_indirect_object_handle(ObjectHandle::integer(7))?;
let child_ref = child.object_ref().expect("direct stream child identity");
let inner = ObjectHandle::stream(
ObjectHandle::dictionary(vec![
(b"/Length".to_vec(), ObjectHandle::integer(99)),
(
b"/Label".to_vec(),
ObjectHandle::string(b"direct-label".to_vec()),
),
(b"/Child".to_vec(), child),
]),
Rc::new(b"direct-payload".to_vec()),
);
let stream = ObjectHandle::stream(
ObjectHandle::dictionary(vec![(
b"/Nested".to_vec(),
ObjectHandle::array(vec![inner]),
)]),
Rc::new(b"outer-payload".to_vec()),
);
for (qdf_mode, newline_before_endstream) in [
(false, crate::writer::NewlineBeforeEndstream::Yes),
(true, crate::writer::NewlineBeforeEndstream::Never),
] {
let value = ObjectHandle::array(vec![stream.clone()]);
let mut output = Vec::new();
let mut map = |handle: &ObjectHandle| {
Ok::<ObjectRef, Error>(handle.object_ref().expect("direct stream child identity"))
};
let mut write_string = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: Some(newline_before_endstream),
qdf_mode,
};
super::super::output::with_buffer_sink(&mut output, |out| {
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&value,
out,
&mut map,
&BTreeSet::new(),
&mut write_string,
&mut direct_stream_writer,
)
})?;
let text = String::from_utf8_lossy(&output);
assert!(text.contains("/Label (direct-label)"));
assert!(text.contains(&format!("/Child {child_ref}")));
assert!(text.contains("direct-payload\nendstream"));
}
Ok(())
}
#[test]
fn array_writers_cover_compact_qdf_mapping_and_removed_reference_shapes() -> Result<()> {
let mut pdf = Pdf::empty()?;
let kept = pdf.make_indirect_object_handle(ObjectHandle::integer(1))?;
let removed = pdf.make_indirect_object_handle(ObjectHandle::integer(2))?;
let removed_refs = [removed.object_ref().unwrap()].into_iter().collect();
let array = ObjectHandle::array(vec![
ObjectHandle::integer(7),
kept.clone(),
removed.clone(),
]);
let mut compact = Vec::new();
super::super::output::with_buffer_sink(&mut compact, |out| {
ObjectWriterEmission::unparse_object(&array, out)
})?;
assert!(String::from_utf8_lossy(&compact).contains("[ 7"));
let map = |object_ref: ObjectRef| {
assert_eq!(object_ref, kept.object_ref().unwrap());
Ok(ObjectRef::new(21, 0))
};
let mut mapped = Vec::new();
super::super::output::with_buffer_sink(&mut mapped, |out| {
ObjectWriterEmission::unparse_object_with_ref_map_and_removed(
&array,
out,
&map,
&removed_refs,
)
})?;
assert_eq!(mapped, b"[ 7 21 0 R null ]");
let mut qdf = Vec::new();
super::super::output::with_buffer_sink(&mut qdf, |out| {
array.unparse_object_qdf_with_ref_map_and_removed(out, 2, &map, &removed_refs)
})?;
assert_eq!(qdf, b"[\n 7\n 21 0 R\n null\n ]");
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
out.write_bytes(b"<string:")?;
out.write_bytes(value)?;
out.write_bytes(b">")
};
let string_array =
ObjectHandle::array(vec![ObjectHandle::string(b"value".to_vec()), removed]);
let mut qdf_strings = Vec::new();
super::super::output::with_buffer_sink(&mut qdf_strings, |out| {
string_array.unparse_object_qdf_with_ref_map_and_removed_with_string_writer(
out,
0,
&map,
&removed_refs,
&mut strings,
)
})?;
assert!(String::from_utf8_lossy(&qdf_strings).contains("<string:value>"));
assert!(String::from_utf8_lossy(&qdf_strings).contains("null"));
let mut plain_qdf_strings = Vec::new();
let mut plain_qdf_callback = |out: &mut OutputSink<'_>, value: &[u8]| {
out.write_bytes(b"<string:")?;
out.write_bytes(value)?;
out.write_bytes(b">")
};
super::super::output::with_buffer_sink(&mut plain_qdf_strings, |out| {
ObjectWriterEmission::unparse_object_qdf_with_string_writer(
&string_array,
out,
0,
&mut plain_qdf_callback,
)
})?;
assert!(String::from_utf8_lossy(&plain_qdf_strings).contains("<string:value>"));
assert!(String::from_utf8_lossy(&plain_qdf_strings).contains("[\n"));
Ok(())
}
#[test]
fn compact_string_writer_emits_removed_array_reference_as_null() -> Result<()> {
let mut pdf = Pdf::empty()?;
let kept = pdf.make_indirect_object_handle(ObjectHandle::integer(1))?;
let kept_ref = kept.object_ref().unwrap();
let removed = pdf.make_indirect_object_handle(ObjectHandle::integer(2))?;
let removed_refs = [removed.object_ref().unwrap()].into_iter().collect();
let array =
ObjectHandle::array(vec![kept, removed, ObjectHandle::string(b"value".to_vec())]);
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
out.write_bytes(b"<string:")?;
out.write_bytes(value)?;
out.write_bytes(b">")
};
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
array.unparse_object_with_ref_map_and_removed_with_string_writer(
out,
&|object_ref| {
assert_eq!(object_ref, kept_ref);
Ok(ObjectRef::new(12, 0))
},
&removed_refs,
&mut strings,
)
})?;
assert_eq!(output, b"[ 12 0 R null <string:value> ]");
Ok(())
}
#[test]
fn qdf_string_writer_keeps_signature_contents_hex_and_formats_arrays() -> Result<()> {
let mut pdf = Pdf::empty()?;
let mapped = pdf.make_indirect_object_handle(ObjectHandle::integer(9))?;
let signature = ObjectHandle::dictionary(vec![
(b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
(
b"/ByteRange".to_vec(),
ObjectHandle::array(vec![ObjectHandle::integer(0), ObjectHandle::integer(1)]),
),
(b"/Contents".to_vec(), ObjectHandle::string(vec![0, 0xff])),
(b"/Label".to_vec(), ObjectHandle::string(b"label".to_vec())),
(b"/Mapped".to_vec(), mapped),
]);
let mut output = Vec::new();
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
super::super::output::with_buffer_sink(&mut output, |out| {
signature.unparse_object_qdf_with_ref_map_and_removed_with_string_writer(
out,
0,
&|object_ref| Ok(object_ref),
&BTreeSet::new(),
&mut strings,
)
})?;
let text = String::from_utf8_lossy(&output);
assert!(text.contains("/ByteRange [\n"));
assert!(text.contains("/Contents <00ff>"));
assert!(text.contains("/Label (label)"));
Ok(())
}
#[test]
fn dynamic_string_writer_fast_path_keeps_signature_hex_and_drops_nulls() -> Result<()> {
let signature = ObjectHandle::dictionary(vec![
(b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
(b"/ByteRange".to_vec(), ObjectHandle::integer(0)),
(b"/Contents".to_vec(), ObjectHandle::string(vec![0, 0xff])),
(b"/Label".to_vec(), ObjectHandle::string(b"label".to_vec())),
(b"/Null".to_vec(), ObjectHandle::null()),
]);
let mut output = Vec::new();
let mut map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let mut direct_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: None,
qdf_mode: false,
};
super::super::output::with_buffer_sink(&mut output, |out| {
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&signature,
out,
&mut map,
&BTreeSet::new(),
&mut strings,
&mut direct_stream_writer,
)
})?;
let text = String::from_utf8(output).expect("signature output is ASCII");
assert!(text.contains("/Contents <00ff>"));
assert!(text.contains("/Label (label)"));
assert!(!text.contains("/Null"));
let non_string_contents = ObjectHandle::dictionary(vec![
(b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
(b"/ByteRange".to_vec(), ObjectHandle::integer(0)),
(b"/Contents".to_vec(), ObjectHandle::integer(7)),
]);
let mut fallback_output = Vec::new();
let mut fallback_map = |_: &ObjectHandle| Ok::<ObjectRef, Error>(ObjectRef::new(1, 0));
let mut fallback_stream_writer = DefaultDynamicDirectStreamWriter {
newline_before_endstream: None,
qdf_mode: false,
};
super::super::output::with_buffer_sink(&mut fallback_output, |out| {
unparse_object_with_dynamic_ref_map_and_string_writer_and_direct_stream_writer(
&non_string_contents,
out,
&mut fallback_map,
&BTreeSet::new(),
&mut strings,
&mut fallback_stream_writer,
)
})?;
assert!(String::from_utf8_lossy(&fallback_output).contains("/Contents 7"));
Ok(())
}
#[test]
fn mapped_id_writer_falls_back_to_general_object_emission() -> Result<()> {
let value = ObjectHandle::integer(7);
let mut output = Vec::new();
let map = |object_gen: QpdfObjGen| {
Ok::<ObjectRef, Error>(object_gen.to_object_ref().expect("valid test identity"))
};
assert_eq!(map(QpdfObjGen::new(1, 0))?, ObjectRef::new(1, 0));
super::super::output::with_buffer_sink(&mut output, |out| {
super::write_id_style_value_handle_with_ref_map(&value, out, &map, &BTreeSet::new())
})?;
assert_eq!(output, b"7");
Ok(())
}
#[test]
fn encrypted_string_ref_map_rejects_a_reserved_object() {
let reserved = ObjectHandle::new_reserved_direct();
let mut strings = |out: &mut OutputSink<'_>, value: &[u8]| {
crate::pdf_syntax::write_string_value(out, value)
};
let error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
reserved.unparse_object_with_ref_map_and_removed_with_string_writer(
out,
&|object_ref| Ok(object_ref), &BTreeSet::new(),
&mut strings,
)
})
.expect_err("reserved encrypted-string object must be rejected");
assert!(error.to_string().contains("reserved object"));
}
#[test]
fn trailer_id_serializer_uses_the_ref_map_fallback() -> Result<()> {
let entries = vec![(
b"/ID".to_vec(),
ObjectHandle::array(vec![
ObjectHandle::string(b"left".to_vec()),
ObjectHandle::string(b"right".to_vec()),
]),
)];
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
super::unparse_dictionary_entries_with_ref_map_and_id_writer(
&entries,
None,
&|object_ref| Ok(object_ref), &BTreeSet::new(),
false,
out,
)
})?;
assert_eq!(output, b"<< /ID [<6c656674><7269676874>] >>");
Ok(())
}
#[test]
fn mapped_id_serializer_handles_indirect_and_malformed_values() -> Result<()> {
let indirect = ObjectHandle::new_indirect_unresolved(ObjectRef::new(9, 0), -1);
let mut indirect_output = Vec::new();
super::super::output::with_buffer_sink(&mut indirect_output, |out| {
super::write_id_style_value_handle_with_ref_map(
&indirect,
out,
&|object_gen| {
Ok(ObjectRef::new(
u32::try_from(object_gen.get_obj()).unwrap() + 1,
0,
))
},
&BTreeSet::new(),
)
})?;
assert_eq!(indirect_output, b"10 0 R");
let malformed = ObjectHandle::array(vec![
ObjectHandle::integer(1),
ObjectHandle::string(b"value".to_vec()),
]);
let mut malformed_output = Vec::new();
super::super::output::with_buffer_sink(&mut malformed_output, |out| {
super::write_id_style_value_handle_with_ref_map(
&malformed,
out,
&|_: QpdfObjGen| Ok(ObjectRef::new(1, 0)), &BTreeSet::new(),
)
})?;
assert_eq!(malformed_output, b"[ 1 (value) ]");
Ok(())
}
#[test]
fn compact_trailer_adapter_skips_a_removed_reference() -> Result<()> {
let removed = ObjectHandle::new_indirect_unresolved(ObjectRef::new(9, 0), -1);
let entries = vec![(b"/Removed".to_vec(), removed)];
let removed_refs = [ObjectRef::new(9, 0)].into_iter().collect();
let map = |object_ref| Ok::<ObjectRef, Error>(object_ref);
assert_eq!(map(ObjectRef::new(1, 0))?, ObjectRef::new(1, 0));
let mut output = Vec::new();
super::super::output::with_buffer_sink(&mut output, |out| {
super::unparse_dictionary_entries_with_ref_map_and_id_writer(
&entries,
None,
&map,
&removed_refs,
false,
out,
)
})?;
assert_eq!(output, b"<< >>");
let null_entries = vec![(b"/Null".to_vec(), ObjectHandle::null())];
let mut null_output = Vec::new();
super::super::output::with_buffer_sink(&mut null_output, |out| {
super::unparse_dictionary_entries_with_ref_map_and_id_writer(
&null_entries,
None,
&map,
&BTreeSet::new(),
true,
out,
)
})?;
assert_eq!(null_output, b"<< >>");
Ok(())
}
#[test]
fn qdf_trailer_with_ref_map_emits_direct_root_id_encrypt_and_custom_values() -> Result<()> {
let root = ObjectHandle::dictionary(vec![(
b"/Type".to_vec(),
ObjectHandle::name(b"Catalog".to_vec()),
)]);
let trailer = ObjectHandle::dictionary(vec![
(b"/Root".to_vec(), root),
(b"/Custom".to_vec(), ObjectHandle::integer(9)),
(
b"/Removed".to_vec(),
ObjectHandle::new_indirect_unresolved(ObjectRef::new(10, 0), -1),
),
(
b"/ID".to_vec(),
ObjectHandle::array(vec![
ObjectHandle::string(b"a".to_vec()),
ObjectHandle::string(b"b".to_vec()),
]),
),
(
b"/Encrypt".to_vec(),
ObjectHandle::new_indirect_unresolved(ObjectRef::new(8, 0), -1),
),
]);
let mut output = Vec::new();
let map = |object_ref| Ok(object_ref);
let removed_refs = [ObjectRef::new(10, 0)].into_iter().collect();
super::super::output::with_buffer_sink(&mut output, |out| {
trailer.write_trailer_with_ref_map(out, false, true, None, &map, &removed_refs, false)
})?;
let text = String::from_utf8(output).unwrap();
assert!(text.starts_with("trailer <<\n"));
assert!(text.contains(" /Root <<\n"));
assert!(text.contains(" /Custom 9\n"));
assert!(text.contains(" /ID [<61><62>] /Encrypt 8 0 R\n"));
assert!(text.contains(" /Encrypt 8 0 R\n>>\n"));
assert!(!text.contains("/Removed"));
Ok(())
}
#[test]
fn classic_trailer_with_ref_map_emits_direct_root_id_encrypt_and_custom_values() -> Result<()> {
let root = ObjectHandle::dictionary(vec![(
b"/Type".to_vec(),
ObjectHandle::name(b"Catalog".to_vec()),
)]);
let trailer = ObjectHandle::dictionary(vec![
(b"/Root".to_vec(), root),
(b"/Custom".to_vec(), ObjectHandle::integer(9)),
(
b"/Removed".to_vec(),
ObjectHandle::new_indirect_unresolved(ObjectRef::new(10, 0), -1),
),
(
b"/ID".to_vec(),
ObjectHandle::array(vec![
ObjectHandle::string(b"a".to_vec()),
ObjectHandle::string(b"b".to_vec()),
]),
),
(
b"/Encrypt".to_vec(),
ObjectHandle::new_indirect_unresolved(ObjectRef::new(8, 0), -1),
),
]);
let mut output = Vec::new();
let map = |object_ref| Ok(object_ref);
let removed_refs = [ObjectRef::new(10, 0)].into_iter().collect();
super::super::output::with_buffer_sink(&mut output, |out| {
trailer.write_trailer_with_ref_map(out, false, false, None, &map, &removed_refs, false)
})?;
let text = String::from_utf8(output).unwrap();
assert!(text.starts_with("trailer <<"));
assert!(!text.starts_with("trailer <<\n"));
assert!(text.contains(" /Root <<"));
assert!(text.contains(" /Custom 9"));
assert!(text.contains(" /ID [<61><62>] /Encrypt 8 0 R"));
assert!(text.ends_with(" >>"));
assert!(!text.contains("\n"));
assert!(!text.contains("/Removed"));
Ok(())
}
#[test]
fn classic_trailer_with_ref_map_emits_an_indirect_root_by_reference() -> Result<()> {
let trailer = ObjectHandle::dictionary(vec![(
b"/Root".to_vec(),
ObjectHandle::new_indirect_unresolved(ObjectRef::new(1, 0), -1),
)]);
let mut output = Vec::new();
let map = |object_ref| Ok(object_ref);
let removed_refs = BTreeSet::new();
super::super::output::with_buffer_sink(&mut output, |out| {
trailer.write_trailer_with_ref_map(out, false, false, None, &map, &removed_refs, false)
})?;
let text = String::from_utf8(output).unwrap();
assert_eq!(text, "trailer << /Root 1 0 R >>");
Ok(())
}
fn reciprocal_direct_dictionary_cycle() -> Result<ObjectHandle> {
let a = ObjectHandle::dictionary(vec![]);
let b = ObjectHandle::dictionary(vec![]);
a.replace_key(b"/B", b.clone())?;
b.replace_key(b"/A", a.clone())?;
assert!(
a.try_get_key(b"/B")?
.try_get_key(b"/A")?
.is_same_object_as(&a),
"the reciprocal replace_key pair must close into a direct cycle"
);
Ok(a)
}
fn nested_direct_dictionaries(n: usize) -> ObjectHandle {
let mut handle = ObjectHandle::integer(1);
for _ in 0..n {
handle = ObjectHandle::dictionary(vec![(b"/K".to_vec(), handle)]);
}
handle
}
#[test]
fn direct_dictionary_cycle_is_rejected_by_the_unparse_hub_family() -> Result<()> {
let cycle = reciprocal_direct_dictionary_cycle()?;
let plain = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
ObjectWriterEmission::unparse_object(&cycle, out)
})
.expect_err("a direct cycle must not be walked by the plain hub");
assert!(
matches!(plain, Error::Unsupported(_)),
"unexpected error kind: {plain:?}"
);
assert!(
plain
.to_string()
.contains("direct object nesting exceeds maximum of"),
"unexpected message: {plain}"
);
let qdf = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
ObjectWriterEmission::unparse_object_qdf(&cycle, out, 0)
})
.expect_err("a direct cycle must not be walked by the qdf hub");
assert!(matches!(qdf, Error::Unsupported(_)));
assert!(
qdf.to_string()
.contains("direct object nesting exceeds maximum of"),
"unexpected message: {qdf}"
);
let mut map = |_: &ObjectHandle| Ok(ObjectRef::new(1, 0));
let dynamic = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
cycle.unparse_object_with_dynamic_ref_map(out, &mut map, &BTreeSet::new())
})
.expect_err("a direct cycle must not be walked by the dynamic ref-map hub");
assert!(matches!(dynamic, Error::Unsupported(_)));
assert!(
dynamic
.to_string()
.contains("direct object nesting exceeds maximum of"),
"unexpected message: {dynamic}"
);
let mut mapped = Vec::new();
let indirect_child = ObjectHandle::array(vec![ObjectHandle::new_indirect_unresolved(
ObjectRef::new(4, 0),
-1,
)]);
super::super::output::with_buffer_sink(&mut mapped, |out| {
indirect_child.unparse_object_with_dynamic_ref_map(out, &mut map, &BTreeSet::new())
})?;
assert_eq!(mapped, b"[ 1 0 R ]");
assert_eq!(UNPARSE_WALK_DEPTH.with(std::cell::Cell::get), 0);
let mut output = Vec::new();
let deep = nested_direct_dictionaries(crate::parser::MAX_PARSE_DEPTH + 1);
super::super::output::with_buffer_sink(&mut output, |out| {
ObjectWriterEmission::unparse_object(&deep, out)
})?;
assert_eq!(
String::from_utf8_lossy(&output).matches("/K").count(),
crate::parser::MAX_PARSE_DEPTH + 1
);
Ok(())
}
#[test]
fn acyclic_direct_nesting_is_bounded_at_the_parser_limit() -> Result<()> {
let bound = crate::parser::MAX_PARSE_DEPTH;
let mut output = Vec::new();
let within_bound = nested_direct_dictionaries(bound + 1);
super::super::output::with_buffer_sink(&mut output, |out| {
ObjectWriterEmission::unparse_object(&within_bound, out)
})?;
assert_eq!(
String::from_utf8_lossy(&output).matches("/K").count(),
bound + 1,
"every level within the bound must still be written"
);
let past_bound = nested_direct_dictionaries(bound + 2);
let error = super::super::output::with_buffer_sink(&mut Vec::new(), |out| {
ObjectWriterEmission::unparse_object(&past_bound, out)
})
.expect_err("nesting past the bound must be reported");
assert!(matches!(error, Error::Unsupported(_)));
assert_eq!(
error.to_string(),
format!(
"unsupported PDF feature: writer: direct object nesting exceeds maximum of {bound}"
)
);
Ok(())
}
}