use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ObjectRef {
pub number: u32,
pub generation: u16,
}
impl ObjectRef {
pub fn new(number: u32, generation: u16) -> Self {
Self { number, generation }
}
pub fn parse(input: &str) -> std::result::Result<Self, ParseObjectRefError> {
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() != 2 && parts.len() != 3 {
return Err(ParseObjectRefError::new(format!(
"invalid object ref '{input}'"
)));
}
if parts.len() == 3 && parts[2] != "R" {
return Err(ParseObjectRefError::new(format!(
"invalid object ref '{input}'"
)));
}
let number = parts[0]
.parse::<u32>()
.map_err(|_| ParseObjectRefError::new(format!("invalid object number in '{input}'")))?;
let generation = parts[1].parse::<u16>().map_err(|_| {
ParseObjectRefError::new(format!("invalid object generation in '{input}'"))
})?;
Ok(Self::new(number, generation))
}
}
impl fmt::Display for ObjectRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {} R", self.number, self.generation)
}
}
impl FromStr for ObjectRef {
type Err = ParseObjectRefError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Self::parse(s)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseObjectRefError {
message: String,
}
impl ParseObjectRefError {
fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ParseObjectRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ParseObjectRefError {}
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
Null,
Boolean(bool),
Integer(i64),
Real(f64),
Name(Vec<u8>),
String(Vec<u8>),
Array(Vec<Object>),
Dictionary(Dictionary),
Stream(Stream),
Reference(ObjectRef),
}
impl Object {
pub fn reference(object_ref: ObjectRef) -> Self {
Self::Reference(object_ref)
}
pub fn as_dict(&self) -> Option<&Dictionary> {
match self {
Object::Dictionary(dict) => Some(dict),
_ => None,
}
}
pub fn as_dict_mut(&mut self) -> Option<&mut Dictionary> {
match self {
Object::Dictionary(dict) => Some(dict),
_ => None,
}
}
pub fn as_stream(&self) -> Option<&Stream> {
match self {
Object::Stream(stream) => Some(stream),
_ => None,
}
}
pub fn as_stream_mut(&mut self) -> Option<&mut Stream> {
match self {
Object::Stream(stream) => Some(stream),
_ => None,
}
}
pub fn as_array(&self) -> Option<&[Object]> {
match self {
Object::Array(values) => Some(values),
_ => None,
}
}
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Object>> {
match self {
Object::Array(values) => Some(values),
_ => None,
}
}
pub fn as_name(&self) -> Option<&[u8]> {
match self {
Object::Name(name) => Some(name),
_ => None,
}
}
pub fn as_string(&self) -> Option<&[u8]> {
match self {
Object::String(value) => Some(value),
_ => None,
}
}
pub fn as_integer(&self) -> Option<i64> {
match self {
Object::Integer(value) => Some(*value),
_ => None,
}
}
pub fn as_real(&self) -> Option<f64> {
match self {
Object::Real(value) => Some(*value),
_ => None,
}
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Object::Boolean(value) => Some(*value),
_ => None,
}
}
pub fn as_ref_id(&self) -> Option<ObjectRef> {
match self {
Object::Reference(object_ref) => Some(*object_ref),
_ => None,
}
}
pub fn into_dict(self) -> Option<Dictionary> {
match self {
Object::Dictionary(dict) => Some(dict),
_ => None,
}
}
pub fn into_stream(self) -> Option<Stream> {
match self {
Object::Stream(stream) => Some(stream),
_ => None,
}
}
pub fn into_array(self) -> Option<Vec<Object>> {
match self {
Object::Array(values) => Some(values),
_ => None,
}
}
pub fn into_name(self) -> Option<Vec<u8>> {
match self {
Object::Name(name) => Some(name),
_ => None,
}
}
pub fn into_string(self) -> Option<Vec<u8>> {
match self {
Object::String(value) => Some(value),
_ => None,
}
}
pub fn is_null(&self) -> bool {
matches!(self, Object::Null)
}
pub fn write_pdf(&self, out: &mut Vec<u8>) {
match self {
Object::Null => out.extend_from_slice(b"null"),
Object::Boolean(value) => {
out.extend_from_slice(if *value { b"true" } else { b"false" })
}
Object::Integer(value) => out.extend_from_slice(value.to_string().as_bytes()),
Object::Real(value) => out.extend_from_slice(value.to_string().as_bytes()),
Object::Name(name) => {
out.push(b'/');
write_name_escaped(out, name);
}
Object::String(value) => {
if is_printable_string(value) {
write_literal_string(out, value);
} else {
write_hex_string(out, value);
}
}
Object::Array(values) => {
if values.is_empty() {
out.extend_from_slice(b"[ ]");
return;
}
out.push(b'[');
let mut prev_ends_with_delim = true; for value in values.iter() {
if !(prev_ends_with_delim && starts_with_delim(value)) {
out.push(b' ');
}
value.write_pdf(out);
prev_ends_with_delim = ends_with_delim(value);
}
if !prev_ends_with_delim {
out.push(b' ');
}
out.push(b']');
}
Object::Dictionary(dict) => dict.write_pdf(out),
Object::Stream(stream) => {
stream.dict.write_pdf(out);
out.extend_from_slice(b"\nstream\n");
out.extend_from_slice(&stream.data);
out.extend_from_slice(b"\nendstream");
}
Object::Reference(object_ref) => {
out.extend_from_slice(object_ref.to_string().as_bytes())
}
}
}
pub(crate) fn write_pdf_qdf(&self, out: &mut Vec<u8>, indent: usize) {
match self {
Object::Array(values) => {
out.push(b'[');
out.push(b'\n');
for value in values.iter() {
push_spaces(out, indent + 2);
value.write_pdf_qdf(out, indent + 2);
out.push(b'\n');
}
push_spaces(out, indent);
out.push(b']');
}
Object::Dictionary(dict) => dict.write_pdf_qdf(out, indent),
Object::Stream(stream) => {
stream.dict.write_pdf_qdf(out, indent);
out.extend_from_slice(b"\nstream\n");
out.extend_from_slice(&stream.data);
out.extend_from_slice(b"\nendstream");
}
_ => self.write_pdf(out),
}
}
}
fn push_spaces(out: &mut Vec<u8>, n: usize) {
out.resize(out.len() + n, b' ');
}
pub(crate) fn write_name_escaped(out: &mut Vec<u8>, raw: &[u8]) {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
for &b in raw {
let needs_escape = !(0x21..=0x7E).contains(&b)
|| matches!(
b,
b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#'
);
if needs_escape {
out.push(b'#');
out.push(HEX[(b >> 4) as usize]);
out.push(HEX[(b & 0x0F) as usize]);
} else {
out.push(b);
}
}
}
fn starts_with_delim(o: &Object) -> bool {
matches!(
o,
Object::String(_) | Object::Array(_) | Object::Dictionary(_) | Object::Stream(_)
)
}
fn ends_with_delim(o: &Object) -> bool {
matches!(
o,
Object::String(_) | Object::Array(_) | Object::Dictionary(_)
)
}
fn is_printable_string(value: &[u8]) -> bool {
value
.iter()
.all(|byte| (0x20..=0x7e).contains(byte) && !matches!(*byte, b'\r' | b'\n'))
}
pub(crate) fn write_literal_string(out: &mut Vec<u8>, value: &[u8]) {
out.push(b'(');
for byte in value {
match byte {
b'\\' | b'(' | b')' => {
out.push(b'\\');
out.push(*byte);
}
_ => out.push(*byte),
}
}
out.push(b')');
}
fn write_hex_string(out: &mut Vec<u8>, value: &[u8]) {
const HEX: &[u8; 16] = b"0123456789abcdef";
out.push(b'<');
for byte in value {
out.push(HEX[(byte >> 4) as usize]);
out.push(HEX[(byte & 0x0f) as usize]);
}
out.push(b'>');
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Dictionary {
entries: BTreeMap<Vec<u8>, Object>,
}
impl Dictionary {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, key: impl AsRef<[u8]>, value: Object) {
self.entries.insert(key.as_ref().to_vec(), value);
}
pub fn get(&self, key: impl AsRef<[u8]>) -> Option<&Object> {
self.entries.get(key.as_ref())
}
pub fn get_ref(&self, key: impl AsRef<[u8]>) -> Option<ObjectRef> {
match self.get(key) {
Some(Object::Reference(object_ref)) => Some(*object_ref),
_ => None,
}
}
pub fn remove(&mut self, key: impl AsRef<[u8]>) -> Option<Object> {
self.entries.remove(key.as_ref())
}
pub fn iter(&self) -> impl Iterator<Item = (&[u8], &Object)> {
self.entries
.iter()
.map(|(key, value)| (key.as_slice(), value))
}
pub(crate) fn values_mut(&mut self) -> impl Iterator<Item = &mut Object> {
self.entries.values_mut()
}
pub(crate) fn write_pdf(&self, out: &mut Vec<u8>) {
out.extend_from_slice(b"<<");
for (key, value) in self.iter() {
out.extend_from_slice(b" /");
out.extend_from_slice(key);
out.push(b' ');
value.write_pdf(out);
}
out.extend_from_slice(b" >>");
}
pub(crate) fn write_pdf_qdf(&self, out: &mut Vec<u8>, indent: usize) {
out.extend_from_slice(b"<<\n");
for (key, value) in self.iter() {
push_spaces(out, indent + 2);
out.push(b'/');
write_name_escaped(out, key);
out.push(b' ');
value.write_pdf_qdf(out, indent + 2);
out.push(b'\n');
}
push_spaces(out, indent);
out.extend_from_slice(b">>");
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stream {
pub dict: Dictionary,
pub data: Vec<u8>,
}
impl Stream {
pub fn new(dict: Dictionary, data: Vec<u8>) -> Self {
Self { dict, data }
}
}
#[cfg(test)]
mod qdf_key_escape_tests {
use super::*;
#[test]
fn qdf_dict_key_is_name_escaped() {
let mut d = Dictionary::new();
d.insert(b"A B#C/D\x80E", Object::Integer(1));
let mut out = Vec::new();
d.write_pdf_qdf(&mut out, 0);
let s = String::from_utf8(out).unwrap();
assert!(
s.contains("/A#20B#23C#2FD#80E 1"),
"key not escaped in QDF output: {s:?}"
);
assert!(!s.contains("/A B"), "raw space leaked: {s:?}");
}
#[test]
fn qdf_dict_plain_key_unescaped() {
let mut d = Dictionary::new();
d.insert(b"Type", Object::Name(b"Catalog".to_vec()));
let mut out = Vec::new();
d.write_pdf_qdf(&mut out, 0);
assert_eq!(out, b"<<\n /Type /Catalog\n>>");
}
}