mod canonical;
mod custom;
mod extension;
mod mapping;
mod rdf;
mod tree;
mod value;
mod write;
use std::collections::BTreeMap;
pub use custom::PropertyError;
pub use extension::{ExtensionProperty, PDFA_EXTENSION, PDFA_PROPERTY, PDFA_SCHEMA, is_predefined_in_pdfa};
pub use mapping::{
ADOBE_META, DC, MAPPINGS, MappedField, Mapping, PDF, PDFA_ID, PDFUA_ID, RDF, STANDARD_PREFIXES, ValueKind, XML,
XMP, XMP_MM,
};
pub use rdf::{ArrayItem, ArrayKind, RdfProperty, RdfValue};
pub use value::{LangText, ValueError, XmpReal, XmpValue};
pub use write::{escape, is_xml_char, property_element};
use crate::date::PdfDate;
use rdf::Rdf;
use tree::Node;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Value {
Text(String),
List(Vec<String>),
Date(PdfDate),
}
impl Value {
const fn fits(&self, kind: ValueKind) -> bool {
matches!(
(kind, self),
(ValueKind::LangAlt | ValueKind::Text, Self::Text(_))
| (ValueKind::Seq, Self::List(_))
| (ValueKind::Date, Self::Date(_))
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseError {
#[error("the packet is neither UTF-8 nor UTF-16")]
Encoding,
#[error("the packet declares a DTD at byte {offset}")]
Dtd {
offset: u64,
},
#[error("the packet refers to an undefined entity at byte {offset}")]
UndefinedEntity {
offset: u64,
},
#[error("the packet uses an undeclared prefix at byte {offset}")]
UnboundPrefix {
offset: u64,
},
#[error("the packet nests elements too deeply at byte {offset}")]
TooDeep {
offset: u64,
},
#[error("the packet declares too many attributes or namespaces at byte {offset}")]
TooLarge {
offset: u64,
},
#[error("the packet is not well-formed XML near byte {offset}")]
Syntax {
offset: u64,
},
#[error("the packet has no rdf:RDF element")]
NoRdf,
}
impl ParseError {
#[must_use]
pub const fn offset(&self) -> Option<u64> {
match *self {
Self::Dtd { offset }
| Self::UndefinedEntity { offset }
| Self::UnboundPrefix { offset }
| Self::TooDeep { offset }
| Self::TooLarge { offset }
| Self::Syntax { offset } => Some(offset),
Self::Encoding | Self::NoRdf => None,
}
}
fn map_offset(self, f: impl Fn(u64) -> u64) -> Self {
match self {
Self::Dtd { offset } => Self::Dtd { offset: f(offset) },
Self::UndefinedEntity { offset } => Self::UndefinedEntity { offset: f(offset) },
Self::UnboundPrefix { offset } => Self::UnboundPrefix { offset: f(offset) },
Self::TooDeep { offset } => Self::TooDeep { offset: f(offset) },
Self::TooLarge { offset } => Self::TooLarge { offset: f(offset) },
Self::Syntax { offset } => Self::Syntax { offset: f(offset) },
other @ (Self::Encoding | Self::NoRdf) => other,
}
}
#[must_use]
pub const fn reason(&self) -> &'static str {
match self {
Self::Encoding => "encoding",
Self::Dtd { .. } => "dtd",
Self::UndefinedEntity { .. } => "entity",
Self::UnboundPrefix { .. } => "prefix",
Self::TooDeep { .. } => "depth",
Self::TooLarge { .. } => "limit",
Self::Syntax { .. } => "syntax",
Self::NoRdf => "no-rdf",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the value's shape doesn't match the field's")]
#[non_exhaustive]
pub struct KindMismatch {
pub field: MappedField,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PacketState {
Absent,
Parsed(Packet),
Malformed {
bytes: Vec<u8>,
error: ParseError,
},
}
impl PacketState {
#[must_use]
pub const fn packet(&self) -> Option<&Packet> {
match self {
Self::Parsed(p) => Some(p),
Self::Absent | Self::Malformed { .. } => None,
}
}
#[must_use]
pub const fn is_malformed(&self) -> bool {
matches!(self, Self::Malformed { .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Written {
pub bytes: Vec<u8>,
pub canonical: bool,
pub declared: Vec<ExtensionProperty>,
}
#[derive(Debug, Clone)]
pub struct Packet {
original: Vec<u8>,
text: String,
utf16: bool,
top: Vec<Node>,
rdf: Rdf,
edits: Box<Edits>,
repairs: Repairs,
}
#[derive(Debug, Clone, Default)]
struct Edits {
changes: BTreeMap<MappedField, Option<Value>>,
custom: BTreeMap<(String, String), custom::Custom>,
declare_all: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Repairs {
pub header_encoding: bool,
pub undeclared_prefix: bool,
}
impl Packet {
pub fn parse(bytes: &[u8]) -> Result<Self, ParseError> {
let utf16 = utf16(bytes)?;
let (text, header_encoding) = match &utf16 {
Some(decoded) => (decoded.clone(), false),
None => utf8(bytes)?,
};
let back = |offset: u64| match utf16 {
Some(_) => utf16_offset(bytes, &text, offset),
None => offset,
};
let (top, undeclared_prefix) = tree::parse(&text).map_err(|e| e.map_offset(back))?;
let rdf = rdf::read(&text, &top).map_err(|e| e.map_offset(back))?;
Ok(Self {
original: bytes.to_vec(),
text,
utf16: utf16.is_some(),
top,
rdf,
edits: Box::default(),
repairs: Repairs {
header_encoding,
undeclared_prefix,
},
})
}
#[must_use]
pub fn new_minimal() -> Self {
let text = write::minimal();
Self::parse(text.as_bytes()).unwrap_or_else(|_| Self {
original: text.clone().into_bytes(),
text,
utf16: false,
top: Vec::new(),
rdf: Rdf::default(),
edits: Box::default(),
repairs: Repairs::default(),
})
}
#[must_use]
pub const fn repairs(&self) -> Repairs {
self.repairs
}
#[must_use]
pub fn original(&self) -> &[u8] {
&self.original
}
#[must_use]
pub fn xml(&self) -> &str {
&self.text
}
#[must_use]
pub fn is_changed(&self) -> bool {
!self.edits.changes.is_empty() || !self.edits.custom.is_empty() || self.edits.declare_all
}
pub fn properties(&self) -> impl Iterator<Item = &RdfProperty> {
self.rdf.properties.iter().map(|p| &p.property)
}
#[must_use]
pub fn property(&self, namespace: &str, name: &str) -> Option<&RdfValue> {
self.properties()
.find(|p| p.namespace == namespace && p.name == name)
.map(|p| &p.value)
}
#[must_use]
pub fn get(&self, field: MappedField) -> Option<Value> {
match self.edits.changes.get(&field) {
Some(changed) => changed.clone(),
None => self.parsed(field),
}
}
fn parsed(&self, field: MappedField) -> Option<Value> {
let mapping = field.mapping();
let value = self.property(mapping.namespace, mapping.name)?;
match mapping.kind {
ValueKind::LangAlt | ValueKind::Text => text_of(value).map(Value::Text),
ValueKind::Seq => {
let items: Vec<String> = match value {
RdfValue::Text(s) => vec![s.clone()],
RdfValue::Array { items, .. } => items
.iter()
.filter_map(|i| match &i.value {
RdfValue::Text(s) => Some(s.clone()),
_ => None,
})
.collect(),
RdfValue::Other(_) => Vec::new(),
};
(!items.is_empty()).then_some(Value::List(items))
}
ValueKind::Date => text_of(value)
.and_then(|s| PdfDate::from_iso8601(&s).ok())
.map(Value::Date),
}
}
pub fn set(&mut self, field: MappedField, value: Option<Value>) -> Result<(), KindMismatch> {
if value.as_ref().is_some_and(|v| !v.fits(field.mapping().kind)) {
return Err(KindMismatch { field });
}
self.store(field, value);
Ok(())
}
fn store(&mut self, field: MappedField, value: Option<Value>) {
let value = match value {
Some(Value::List(items)) if items.is_empty() => None,
other => other,
};
if value == self.parsed(field) {
self.edits.changes.remove(&field);
} else {
self.edits.changes.insert(field, value);
}
}
#[must_use]
pub fn write(&self) -> Written {
if !self.is_changed() {
return Written {
bytes: self.original.clone(),
canonical: false,
declared: Vec::new(),
};
}
let mapped = self.edits.changes.iter().map(|(field, value)| {
let m = field.mapping();
write::Change {
namespace: m.namespace,
name: m.name,
prefix: m.prefix,
value: value.as_ref().map(|v| write::Body::Mapped(m, v)),
}
});
let custom = self.edits.custom.iter().map(|((namespace, name), c)| write::Change {
namespace,
name,
prefix: &c.prefix,
value: c.value.as_ref().map(write::Body::Custom),
});
let changes: Vec<write::Change<'_>> = mapped.chain(custom).collect();
let declare = match (self.pdfa_part(), self.edits.declare_all) {
(None, _) => write::Declare::Nothing,
(Some(_), false) => write::Declare::Changed,
(Some(_), true) => write::Declare::All,
};
if !self.utf16
&& let Some((text, declared)) = write::in_place(&self.text, &self.top, &self.rdf, &changes, declare)
{
return Written {
bytes: text.into_bytes(),
canonical: false,
declared,
};
}
let (text, declared) = canonical::canonical(&self.text, &self.rdf, &changes, declare);
Written {
bytes: text.into_bytes(),
canonical: true,
declared,
}
}
fn text(&self, field: MappedField) -> Option<String> {
match self.get(field)? {
Value::Text(s) => Some(s),
Value::List(_) | Value::Date(_) => None,
}
}
fn date(&self, field: MappedField) -> Option<PdfDate> {
match self.get(field)? {
Value::Date(d) => Some(d),
Value::Text(_) | Value::List(_) => None,
}
}
#[must_use]
pub fn title(&self) -> Option<String> {
self.text(MappedField::Title)
}
pub fn set_title(&mut self, title: Option<&str>) {
self.store(MappedField::Title, title.map(|s| Value::Text(s.to_owned())));
}
#[must_use]
pub fn authors(&self) -> Vec<String> {
match self.get(MappedField::Authors) {
Some(Value::List(items)) => items,
_ => Vec::new(),
}
}
pub fn set_authors<S: AsRef<str>>(&mut self, authors: &[S]) {
let items = authors.iter().map(|a| a.as_ref().to_owned()).collect();
self.store(MappedField::Authors, Some(Value::List(items)));
}
#[must_use]
pub fn subject(&self) -> Option<String> {
self.text(MappedField::Subject)
}
pub fn set_subject(&mut self, subject: Option<&str>) {
self.store(MappedField::Subject, subject.map(|s| Value::Text(s.to_owned())));
}
#[must_use]
pub fn keywords(&self) -> Option<String> {
self.text(MappedField::Keywords)
}
pub fn set_keywords(&mut self, keywords: Option<&str>) {
self.store(MappedField::Keywords, keywords.map(|s| Value::Text(s.to_owned())));
}
#[must_use]
pub fn creator_tool(&self) -> Option<String> {
self.text(MappedField::Creator)
}
pub fn set_creator_tool(&mut self, tool: Option<&str>) {
self.store(MappedField::Creator, tool.map(|s| Value::Text(s.to_owned())));
}
#[must_use]
pub fn producer(&self) -> Option<String> {
self.text(MappedField::Producer)
}
pub fn set_producer(&mut self, producer: Option<&str>) {
self.store(MappedField::Producer, producer.map(|s| Value::Text(s.to_owned())));
}
#[must_use]
pub fn create_date(&self) -> Option<PdfDate> {
self.date(MappedField::Created)
}
pub fn set_create_date(&mut self, date: Option<PdfDate>) {
self.store(MappedField::Created, date.map(Value::Date));
}
#[must_use]
pub fn modify_date(&self) -> Option<PdfDate> {
self.date(MappedField::Modified)
}
pub fn set_modify_date(&mut self, date: Option<PdfDate>) {
self.store(MappedField::Modified, date.map(Value::Date));
}
#[must_use]
pub fn metadata_date(&self) -> Option<PdfDate> {
self.date(MappedField::MetadataDate)
}
pub fn set_metadata_date(&mut self, date: Option<PdfDate>) {
self.store(MappedField::MetadataDate, date.map(Value::Date));
}
#[must_use]
pub fn document_id(&self) -> Option<String> {
self.text(MappedField::DocumentId)
}
#[must_use]
pub fn instance_id(&self) -> Option<String> {
self.text(MappedField::InstanceId)
}
#[must_use]
pub fn pdfa_part(&self) -> Option<u8> {
self.simple(PDFA_ID, "part")?.trim().parse().ok()
}
#[must_use]
pub fn pdfa_conformance(&self) -> Option<String> {
self.simple(PDFA_ID, "conformance").map(|s| s.trim().to_owned())
}
#[must_use]
pub fn pdfua_part(&self) -> Option<u8> {
self.simple(PDFUA_ID, "part")?.trim().parse().ok()
}
fn simple(&self, namespace: &str, name: &str) -> Option<String> {
text_of(self.property(namespace, name)?)
}
}
fn text_of(value: &RdfValue) -> Option<String> {
match value {
RdfValue::Text(s) => Some(s.clone()),
RdfValue::Array { items, .. } => {
let default = items
.iter()
.find(|i| i.lang.as_deref().is_some_and(|l| l.eq_ignore_ascii_case("x-default")));
match &default.or_else(|| items.first())?.value {
RdfValue::Text(s) => Some(s.clone()),
_ => None,
}
}
RdfValue::Other(_) => None,
}
}
fn utf8(bytes: &[u8]) -> Result<(String, bool), ParseError> {
if let Ok(text) = std::str::from_utf8(bytes) {
return Ok((text.to_owned(), false));
}
let header_end = bytes
.starts_with(b"<?xpacket")
.then(|| bytes.windows(2).position(|w| w == b"?>"))
.flatten()
.ok_or(ParseError::Encoding)?;
let (header, rest) = bytes.split_at(header_end);
let rest = std::str::from_utf8(rest).map_err(|_| ParseError::Encoding)?;
let mut header = header.to_vec();
while let Err(e) = std::str::from_utf8(&header) {
let bad = e.error_len().unwrap_or(header.len() - e.valid_up_to());
for b in header.iter_mut().skip(e.valid_up_to()).take(bad) {
*b = b'?';
}
}
let header = String::from_utf8(header).map_err(|_| ParseError::Encoding)?;
Ok((format!("{header}{rest}"), true))
}
fn utf16(bytes: &[u8]) -> Result<Option<String>, ParseError> {
let (big_endian, body) = match bytes {
[0xFE, 0xFF, rest @ ..] => (true, rest),
[0xFF, 0xFE, rest @ ..] => (false, rest),
[0, b'<', ..] => (true, bytes),
[b'<', 0, ..] => (false, bytes),
_ => return Ok(None),
};
let (pairs, rest) = body.as_chunks::<2>();
if !rest.is_empty() {
return Err(ParseError::Encoding);
}
let units = pairs.iter().map(|&pair| {
if big_endian {
u16::from_be_bytes(pair)
} else {
u16::from_le_bytes(pair)
}
});
char::decode_utf16(units)
.collect::<Result<String, _>>()
.map(Some)
.map_err(|_| ParseError::Encoding)
}
fn utf16_offset(bytes: &[u8], text: &str, offset: u64) -> u64 {
let bom = if matches!(bytes, [0xFE, 0xFF, ..] | [0xFF, 0xFE, ..]) {
2
} else {
0
};
let end = usize::try_from(offset).unwrap_or(usize::MAX).min(text.len());
let units: usize = text
.char_indices()
.take_while(|(i, _)| *i < end)
.map(|(_, c)| c.len_utf16())
.sum();
bom + 2 * units as u64
}
#[cfg(test)]
mod tests;