use laminapdf_cos::{Dict, ObjRef, Object, Result, tolerant};
use laminapdf_syntax::text::decode_text_string;
use crate::document::Document;
pub(crate) fn text_of(obj: &Object) -> Option<String> {
match obj {
Object::String(s) => Some(decode_text_string(&s.bytes)),
_ => None,
}
}
pub(crate) fn read_name(doc: &Document, value: Option<&Object>) -> Result<Option<Vec<u8>>> {
let Some(value) = value else { return Ok(None) };
Ok(match doc.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
_ => None,
})
}
pub(crate) fn file_spec_name(doc: &Document, spec: &Dict) -> Result<Option<String>> {
for key in ["UF", "F"] {
if let Some(v) = spec.get(key)
&& let Some(name) = doc
.read(v)?
.as_deref()
.and_then(|o| text_of(o).or_else(|| name_text(o)))
{
return Ok(Some(name));
}
}
Ok(None)
}
fn name_text(obj: &Object) -> Option<String> {
match obj {
Object::Name(n) => Some(name_bytes_text(n.as_bytes())),
_ => None,
}
}
pub(crate) fn name_bytes_text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
pub(crate) fn dict_at(doc: &Document, r: ObjRef) -> Result<Option<Dict>> {
Ok(tolerant(doc.deref(&Object::Ref(r)))?.and_then(|o| o.as_dict().cloned()))
}
pub(crate) fn array_items(doc: &Document, value: Option<&Object>) -> Result<Vec<Object>> {
let Some(value) = value else { return Ok(Vec::new()) };
Ok(tolerant(doc.deref(value))?
.and_then(|o| o.as_array().map(<[Object]>::to_vec))
.unwrap_or_default())
}
pub(crate) fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}