use crate::vector::{VectorError, trimmed};
#[derive(Clone, Debug, PartialEq)]
pub enum Obj {
Null,
Bool(bool),
Int(i64),
Real(f64),
Name(String),
Str(Vec<u8>),
Array(Vec<Obj>),
Dict(Vec<(String, Obj)>),
Ref(u32),
Seq(Vec<Obj>),
Raw(Vec<u8>),
}
impl Obj {
pub fn name(name: impl Into<String>) -> Self {
Self::Name(name.into())
}
pub fn op(op: &str) -> Self {
Self::Raw(op.as_bytes().to_vec())
}
pub(super) fn dict<const N: usize>(entries: [(&str, Obj); N]) -> Self {
Self::Dict(
entries
.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect(),
)
}
pub(super) fn reals(values: impl IntoIterator<Item = f64>) -> Self {
Self::Array(values.into_iter().map(Self::Real).collect())
}
pub fn repr(&self) -> Result<Vec<u8>, VectorError> {
Ok(match self {
Self::Null => b"null".to_vec(),
Self::Bool(b) => {
if *b {
b"true".to_vec()
} else {
b"false".to_vec()
}
}
Self::Int(i) => i.to_string().into_bytes(),
Self::Real(r) => {
if !r.is_finite() {
return Err(VectorError::NonFinite("number in a PDF"));
}
trimmed(*r, 10).into_bytes()
}
Self::Name(name) => name_repr(name),
Self::Str(bytes) => string_repr(bytes),
Self::Array(items) => {
let mut parts = vec![b"[".to_vec()];
for item in items {
parts.push(item.repr()?);
}
parts.push(b"]".to_vec());
fill(&parts)
}
Self::Dict(entries) => {
let mut parts = vec![b"<<".to_vec()];
for (key, value) in entries {
let mut part = name_repr(key);
part.push(b' ');
part.extend(value.repr()?);
parts.push(part);
}
parts.push(b">>".to_vec());
fill(&parts)
}
Self::Ref(id) => format!("{id} 0 R").into_bytes(),
Self::Seq(items) => fill(&items.iter().map(Obj::repr).collect::<Result<Vec<_>, _>>()?),
Self::Raw(bytes) => bytes.clone(),
})
}
}
fn name_repr(name: &str) -> Vec<u8> {
let mut out = vec![b'/'];
for c in name.chars() {
match u32::from(c) {
0x21..=0x7e => out.push(c as u8),
code => out.extend(format!("#{:02x}", code & 0xff).into_bytes()),
}
}
out
}
fn string_repr(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len() + 2);
out.push(b'(');
for &b in bytes {
match b {
b'\\' => out.extend_from_slice(b"\\\\"),
b'(' => out.extend_from_slice(b"\\("),
b')' => out.extend_from_slice(b"\\)"),
b'\n' => out.extend_from_slice(b"\\n"),
b'\r' => out.extend_from_slice(b"\\r"),
_ => out.push(b),
}
}
out.push(b')');
out
}
pub fn text_string(text: &str) -> Obj {
if text.is_ascii() {
Obj::Str(text.as_bytes().to_vec())
} else {
let mut bytes = vec![0xfe, 0xff];
for unit in text.encode_utf16() {
bytes.extend_from_slice(&unit.to_be_bytes());
}
Obj::Str(bytes)
}
}
pub fn line(objects: &[Obj]) -> Result<Vec<u8>, VectorError> {
let parts = objects
.iter()
.map(Obj::repr)
.collect::<Result<Vec<_>, _>>()?;
let mut line = fill(&parts);
line.push(b'\n');
Ok(line)
}
pub(super) fn fill(parts: &[Vec<u8>]) -> Vec<u8> {
const LINE: usize = 75;
let mut lines: Vec<Vec<u8>> = Vec::new();
let (mut position, mut start) = (0, 0);
for (i, part) in parts.iter().enumerate() {
if position + part.len() < LINE {
position += part.len() + 1;
} else {
lines.push(parts[start..i].join(&b' '));
start = i;
position = part.len();
}
}
lines.push(parts[start..].join(&b' '));
lines.join(&b'\n')
}
#[cfg(test)]
mod tests {
use super::*;
fn text(obj: &Obj) -> String {
String::from_utf8(obj.repr().unwrap()).unwrap()
}
#[test]
fn scalars() {
assert_eq!(text(&Obj::Real(31.0 / 255.0)), "0.1215686275");
assert_eq!(text(&Obj::Real(-0.0)), "-0");
assert_eq!(text(&Obj::Real(460.8)), "460.8");
assert_eq!(text(&Obj::Int(42)), "42");
assert_eq!(text(&Obj::name("A b#")), "/A#20b#");
assert_eq!(text(&Obj::Str(b"a(b)\\\n".to_vec())), "(a\\(b\\)\\\\\\n)");
assert_eq!(text(&Obj::Ref(3)), "3 0 R");
assert!(Obj::Real(f64::NAN).repr().is_err());
assert_eq!(text_string("é"), Obj::Str(vec![0xfe, 0xff, 0, 0xe9]));
}
#[test]
fn containers_fill_lines() {
let dict = Obj::dict([
("Type", Obj::name("Page")),
("MediaBox", Obj::reals([0.0, 0.0, 460.8, 345.6])),
]);
assert_eq!(
text(&dict),
"<< /Type /Page /MediaBox [ 0 0 460.8 345.6 ] >>"
);
let long = vec![b"x".repeat(80)];
assert_eq!(fill(&long), [b"\n".to_vec(), b"x".repeat(80)].concat());
let words: Vec<Vec<u8>> = (0..30).map(|i| format!("w{i:02}").into_bytes()).collect();
let filled = String::from_utf8(fill(&words)).unwrap();
assert!(filled.lines().all(|line| line.len() < 75));
assert_eq!(filled.lines().count(), 2);
}
}