use laminapdf_cos::{ObjRef, Object, ObjectLocation, Result};
use crate::document::{Document, tolerant};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ObjectKind {
Null,
Boolean,
Integer,
Real,
String,
Name,
Array,
Dictionary,
Stream,
Reference,
}
impl ObjectKind {
pub const ALL: [Self; 10] = [
Self::Null,
Self::Boolean,
Self::Integer,
Self::Real,
Self::String,
Self::Name,
Self::Array,
Self::Dictionary,
Self::Stream,
Self::Reference,
];
#[must_use]
pub const fn of(object: &Object) -> Self {
match object {
Object::Null => Self::Null,
Object::Bool(_) => Self::Boolean,
Object::Integer(_) => Self::Integer,
Object::Real(_) => Self::Real,
Object::String(_) => Self::String,
Object::Name(_) => Self::Name,
Object::Array(_) => Self::Array,
Object::Dict(_) => Self::Dictionary,
Object::Stream(_) => Self::Stream,
Object::Ref(_) => Self::Reference,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Null => "null",
Self::Boolean => "boolean",
Self::Integer => "integer",
Self::Real => "real",
Self::String => "string",
Self::Name => "name",
Self::Array => "array",
Self::Dictionary => "dictionary",
Self::Stream => "stream",
Self::Reference => "reference",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ObjectEntry {
pub id: ObjRef,
pub kind: ObjectKind,
pub type_name: Option<String>,
pub subtype: Option<String>,
pub location: ObjectLocation,
pub stream_length: Option<u64>,
}
impl Document {
pub fn objects(&self) -> impl Iterator<Item = Result<ObjectEntry>> + '_ {
self.each_object()
.map(|item| item.map(|(id, object)| self.entry_of(id, object.as_deref())))
}
pub fn object_entry(&self, num: u32) -> Result<Option<ObjectEntry>> {
let Some(id) = self.object_id(num) else {
return Ok(None);
};
let object = tolerant(self.object(num))?;
Ok(Some(self.entry_of(id, object.as_deref())))
}
#[must_use]
pub fn entry_of_number(&self, num: u32, object: Option<&Object>) -> Option<ObjectEntry> {
Some(self.entry_of(self.object_id(num)?, object))
}
fn entry_of(&self, id: ObjRef, object: Option<&Object>) -> ObjectEntry {
let object = object.unwrap_or(&Object::Null);
let dict = match object {
Object::Dict(d) => Some(d),
Object::Stream(s) => Some(&s.dict),
_ => None,
};
let name_of = |key: &str| {
dict.and_then(|d| d.get_name(key))
.map(|n| String::from_utf8_lossy(n).into_owned())
};
ObjectEntry {
id,
kind: ObjectKind::of(object),
type_name: name_of("Type"),
subtype: name_of("Subtype").or_else(|| name_of("S")),
location: self.object_location(id.num).unwrap_or(ObjectLocation::Created),
stream_length: match object {
Object::Stream(s) => Some(u64::try_from(s.data.len()).unwrap_or(u64::MAX)),
_ => None,
},
}
}
}