use std::collections::{BTreeMap, BTreeSet};
use std::num::NonZeroUsize;
use crate::ObjectHandle;
use crate::ObjectRef;
pub(crate) struct EligibilityContext {
pub encryption_ref: Option<ObjectRef>,
}
pub(crate) fn is_eligible_for_objstm_handle(
object_ref: ObjectRef,
object: &ObjectHandle,
ctx: &EligibilityContext,
) -> crate::Result<bool> {
if object_ref.generation != 0 {
return Ok(false);
}
object.try_dereference()?;
if object.as_stream_dict().is_some() {
return Ok(false);
}
if object.try_is_dictionary_of_type(b"ObjStm", b"")?
|| object.try_is_dictionary_of_type(b"XRef", b"")?
{
return Ok(false);
}
if Some(object_ref) == ctx.encryption_ref {
return Ok(false);
}
Ok(true)
}
pub(crate) fn eligibility_context<R: std::io::Read + std::io::Seek>(
pdf: &mut crate::Pdf<R>,
) -> crate::Result<EligibilityContext> {
Ok(EligibilityContext {
encryption_ref: pdf.encryption_ref(),
})
}
pub(crate) fn get_compressible_objgens<R: std::io::Read + std::io::Seek>(
pdf: &mut crate::Pdf<R>,
) -> crate::Result<Vec<ObjectRef>> {
Ok(compressible_objgens_qpdf_plan(pdf)?.eligible)
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct CompressiblePlan {
pub eligible: Vec<ObjectRef>,
pub removed_refs: BTreeSet<ObjectRef>,
}
pub(crate) fn compressible_objgens_qpdf_plan<R: std::io::Read + std::io::Seek>(
pdf: &mut crate::Pdf<R>,
) -> crate::Result<CompressiblePlan> {
let mut visited: BTreeSet<u32> = BTreeSet::new();
let mut result: Vec<ObjectRef> = Vec::new();
let mut removed_refs = BTreeSet::new();
let mut highest_live_generation: BTreeMap<u32, u16> = BTreeMap::new();
for object_ref in pdf.live_object_refs() {
highest_live_generation
.entry(object_ref.number)
.and_modify(|generation| *generation = (*generation).max(object_ref.generation))
.or_insert(object_ref.generation);
}
let trailer_handle = pdf.trailer();
let encrypt_ref = trailer_handle.try_get_key(b"/Encrypt")?.object_ref();
let mut stack: Vec<ObjectHandle> = vec![trailer_handle];
while let Some(object) = stack.pop() {
let Some(object_ref) = object.object_ref() else {
push_handle_children(&object, &mut stack)?;
continue;
};
if object_ref.number == 0 {
continue;
}
if highest_live_generation
.get(&object_ref.number)
.is_some_and(|generation| *generation > object_ref.generation)
{
removed_refs.insert(object_ref);
continue;
}
if !visited.insert(object_ref.number) {
continue;
}
object.try_dereference()?;
let is_stream = object.as_stream_dict().is_some();
let is_signature = !is_stream && is_qpdf_signature_dict(pdf, &object)?;
if !is_stream && !is_signature && Some(object_ref) != encrypt_ref {
result.push(object_ref);
}
push_handle_children(&object, &mut stack)?;
}
Ok(CompressiblePlan {
eligible: result,
removed_refs,
})
}
pub(crate) fn even_split_into_streams(eligible: &[ObjectRef]) -> Vec<Vec<ObjectRef>> {
even_split_into_streams_with_cap(
eligible,
NonZeroUsize::new(100).expect("qpdf's ObjStm cap is non-zero"),
)
}
pub(crate) fn even_split_into_streams_with_cap(
eligible: &[ObjectRef],
cap: NonZeroUsize,
) -> Vec<Vec<ObjectRef>> {
let n = eligible.len();
if n == 0 {
return Vec::new();
}
let n_streams = n.div_ceil(cap.get());
let n_per = n.div_ceil(n_streams);
eligible.chunks(n_per).map(|chunk| chunk.to_vec()).collect()
}
pub(crate) fn is_qpdf_signature_dict<R: std::io::Read + std::io::Seek>(
pdf: &mut crate::Pdf<R>,
object: &ObjectHandle,
) -> crate::Result<bool> {
if !object.try_is_dictionary_of_type(b"", b"")? {
return Ok(false);
}
let type_value = object.try_get_key(b"/Type")?;
let type_value = pdf.resolve_handle(&type_value)?;
if !type_value.try_is_name_and_equals(b"Sig")? {
return Ok(false);
}
Ok(object.try_has_key(b"/ByteRange")? && object.try_has_key(b"/Contents")?)
}
fn push_handle_children(object: &ObjectHandle, stack: &mut Vec<ObjectHandle>) -> crate::Result<()> {
object.try_dereference()?;
if let Some(dict) = object.as_stream_dict() {
return push_handle_dict_children(&dict, stack, true);
}
if object.try_is_dictionary_of_type(b"", b"")? {
return push_handle_dict_children(object, stack, false);
}
if let Some(items) = object.try_as_array()? {
for item in items.into_iter().rev() {
stack.push(item);
}
}
Ok(())
}
fn push_handle_dict_children(
dict: &ObjectHandle,
stack: &mut Vec<ObjectHandle>,
is_stream: bool,
) -> crate::Result<()> {
let keys = dict.try_get_keys()?;
for key in keys.into_iter().rev() {
if is_stream && key.as_slice() == b"/Length" {
continue;
}
stack.push(dict.try_get_key(&key)?);
}
Ok(())
}
pub(crate) fn collect_indirect_objstm_length_refs<R: std::io::Read + std::io::Seek>(
pdf: &mut crate::Pdf<R>,
) -> crate::Result<BTreeSet<ObjectRef>> {
let mut excluded = BTreeSet::new();
let refs: Vec<ObjectRef> = pdf.object_refs();
for r in refs {
let object = pdf.get_object_handle(r);
object.try_dereference()?;
let Some(dict) = object.as_stream_dict() else {
continue;
};
if !dict
.try_get_key(b"/Type")
.and_then(|type_value| type_value.try_is_name_and_equals(b"ObjStm"))?
{
continue;
}
let length = dict.try_get_key(b"/Length")?;
if let Some(length_ref) = length.object_ref() {
excluded.insert(length_ref);
}
}
Ok(excluded)
}