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 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'/');
out.extend_from_slice(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())
}
}
}
}
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'))
}
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" >>");
}
}
#[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 }
}
}