1use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct ObjRef {
10 pub num: u32,
12 pub gen_nr: u16,
14}
15
16impl ObjRef {
17 #[must_use]
21 pub const fn new(num: u32, gen_nr: u16) -> Self {
22 Self { num, gen_nr }
23 }
24}
25
26impl fmt::Display for ObjRef {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 write!(f, "{} {} R", self.num, self.gen_nr)
29 }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum StringFormat {
37 #[default]
39 Literal,
40 Hex,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub struct PdfString {
49 pub bytes: Vec<u8>,
51 pub format: StringFormat,
53}
54
55impl PdfString {
56 #[must_use]
60 pub fn literal(bytes: impl Into<Vec<u8>>) -> Self {
61 Self {
62 bytes: bytes.into(),
63 format: StringFormat::Literal,
64 }
65 }
66
67 #[must_use]
71 pub fn hex(bytes: impl Into<Vec<u8>>) -> Self {
72 Self {
73 bytes: bytes.into(),
74 format: StringFormat::Hex,
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
83pub struct Name(pub Vec<u8>);
84
85impl Name {
86 #[must_use]
90 pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
91 Self(bytes.into())
92 }
93
94 #[must_use]
98 pub fn as_bytes(&self) -> &[u8] {
99 &self.0
100 }
101}
102
103impl From<&str> for Name {
104 fn from(s: &str) -> Self {
105 Self(s.as_bytes().to_vec())
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Default)]
114pub struct Dict {
115 entries: Vec<(Name, Object)>,
116}
117
118impl Dict {
119 #[must_use]
123 pub fn new() -> Self {
124 Self::default()
125 }
126
127 #[must_use]
131 pub fn get(&self, key: &str) -> Option<&Object> {
132 self.entries.iter().find(|(k, _)| k.0 == key.as_bytes()).map(|(_, v)| v)
133 }
134
135 pub fn get_mut(&mut self, key: &str) -> Option<&mut Object> {
139 self.entries
140 .iter_mut()
141 .find(|(k, _)| k.0 == key.as_bytes())
142 .map(|(_, v)| v)
143 }
144
145 #[must_use]
149 pub fn contains_key(&self, key: &str) -> bool {
150 self.get(key).is_some()
151 }
152
153 pub fn insert(&mut self, key: impl Into<Name>, value: impl Into<Object>) {
157 let key = key.into();
158 let value = value.into();
159 match self.entries.iter_mut().find(|(k, _)| *k == key) {
160 Some(slot) => slot.1 = value,
161 None => self.entries.push((key, value)),
162 }
163 }
164
165 pub fn remove(&mut self, key: &str) -> Option<Object> {
169 let pos = self.entries.iter().position(|(k, _)| k.0 == key.as_bytes())?;
170 Some(self.entries.remove(pos).1)
171 }
172
173 pub fn iter(&self) -> impl Iterator<Item = (&Name, &Object)> {
177 self.entries.iter().map(|(k, v)| (k, v))
178 }
179
180 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Name, &mut Object)> {
184 self.entries.iter_mut().map(|(k, v)| (&*k, v))
185 }
186
187 #[must_use]
191 pub fn len(&self) -> usize {
192 self.entries.len()
193 }
194
195 #[must_use]
199 pub fn is_empty(&self) -> bool {
200 self.entries.is_empty()
201 }
202
203 #[must_use]
207 pub fn get_name(&self, key: &str) -> Option<&[u8]> {
208 match self.get(key) {
209 Some(Object::Name(n)) => Some(n.as_bytes()),
210 _ => None,
211 }
212 }
213
214 #[must_use]
218 pub fn get_int(&self, key: &str) -> Option<i64> {
219 self.get(key).and_then(Object::as_int)
220 }
221}
222
223impl<K: Into<Name>, V: Into<Object>> FromIterator<(K, V)> for Dict {
224 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
225 let mut dict = Self::new();
226 for (k, v) in iter {
227 dict.insert(k, v);
228 }
229 dict
230 }
231}
232
233#[derive(Debug, Clone, PartialEq, Default)]
237pub struct Stream {
238 pub dict: Dict,
240 pub data: Vec<u8>,
242}
243
244impl Stream {
245 #[must_use]
249 pub fn new(dict: Dict, data: impl Into<Vec<u8>>) -> Self {
250 Self {
251 dict,
252 data: data.into(),
253 }
254 }
255
256 #[must_use]
261 pub fn flate(mut dict: Dict, decoded: &[u8]) -> Self {
262 dict.insert("Filter", Name::from("FlateDecode"));
263 Self {
264 dict,
265 data: crate::filters::flate_encode(decoded),
266 }
267 }
268}
269
270#[derive(Debug, Clone, PartialEq, Default)]
274pub enum Object {
275 #[default]
277 Null,
278 Bool(bool),
280 Integer(i64),
282 Real(f64),
284 String(PdfString),
286 Name(Name),
288 Array(Vec<Object>),
290 Dict(Dict),
292 Stream(Stream),
294 Ref(ObjRef),
296}
297
298impl Object {
299 #[must_use]
304 pub fn number(v: f64) -> Self {
305 if !v.is_finite() {
306 return Self::Integer(0);
307 }
308 #[expect(
309 clippy::cast_possible_truncation,
310 reason = "only integral values well inside i64 get here"
311 )]
312 if v.fract() == 0.0 && v.abs() < 1e15 {
313 Self::Integer(v as i64)
314 } else {
315 Self::Real(v)
316 }
317 }
318
319 #[must_use]
324 pub fn rounded(v: f64, decimals: u8) -> Self {
325 if v.abs() >= 1e15 {
327 return Self::number(v);
328 }
329 let scale = 10f64.powi(i32::from(decimals.min(15)));
330 Self::number((v * scale).round() / scale)
331 }
332
333 #[must_use]
337 pub fn name(s: &str) -> Self {
338 Self::Name(Name::from(s))
339 }
340
341 #[must_use]
345 pub fn as_int(&self) -> Option<i64> {
346 match self {
347 Self::Integer(i) => Some(*i),
348 _ => None,
349 }
350 }
351
352 #[must_use]
356 #[expect(clippy::cast_precision_loss, reason = "PDF numbers are approximate by definition")]
357 pub fn as_f64(&self) -> Option<f64> {
358 match self {
359 Self::Integer(i) => Some(*i as f64),
360 Self::Real(r) => Some(*r),
361 _ => None,
362 }
363 }
364
365 #[must_use]
369 pub fn as_dict(&self) -> Option<&Dict> {
370 match self {
371 Self::Dict(d) => Some(d),
372 Self::Stream(s) => Some(&s.dict),
373 _ => None,
374 }
375 }
376
377 #[must_use]
381 pub fn as_array(&self) -> Option<&[Object]> {
382 match self {
383 Self::Array(a) => Some(a),
384 _ => None,
385 }
386 }
387
388 #[must_use]
392 pub fn as_ref(&self) -> Option<ObjRef> {
393 match self {
394 Self::Ref(r) => Some(*r),
395 _ => None,
396 }
397 }
398
399 #[must_use]
403 pub fn to_bytes(&self) -> Vec<u8> {
404 let mut out = Vec::new();
405 self.write_to(&mut out);
406 out
407 }
408
409 pub fn write_to(&self, out: &mut Vec<u8>) {
416 match self {
417 Self::Null => out.extend_from_slice(b"null"),
418 Self::Bool(true) => out.extend_from_slice(b"true"),
419 Self::Bool(false) => out.extend_from_slice(b"false"),
420 Self::Integer(i) => out.extend_from_slice(i.to_string().as_bytes()),
421 Self::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()),
422 Self::String(s) => write_string(s, out),
423 Self::Name(n) => write_name(n.as_bytes(), out),
424 Self::Array(items) => {
425 out.push(b'[');
426 for (i, item) in items.iter().enumerate() {
427 if i > 0 {
428 out.push(b' ');
429 }
430 item.write_to(out);
431 }
432 out.push(b']');
433 }
434 Self::Dict(d) => write_dict(d, out),
435 Self::Stream(s) => {
436 let mut dict = s.dict.clone();
437 let len = i64::try_from(s.data.len()).unwrap_or(i64::MAX);
438 dict.insert("Length", len);
439 write_dict(&dict, out);
440 out.extend_from_slice(b"\nstream\n");
441 out.extend_from_slice(&s.data);
442 out.extend_from_slice(b"\nendstream");
443 }
444 Self::Ref(r) => out.extend_from_slice(r.to_string().as_bytes()),
445 }
446 }
447}
448
449macro_rules! impl_from {
450 ($($t:ty => $variant:ident),* $(,)?) => {
451 $(impl From<$t> for Object {
452 fn from(v: $t) -> Self { Self::$variant(v.into()) }
453 })*
454 };
455}
456
457impl_from! {
458 bool => Bool, i64 => Integer, i32 => Integer, u32 => Integer, f64 => Real,
459 PdfString => String, Name => Name, Vec<Object> => Array, Dict => Dict,
460 Stream => Stream, ObjRef => Ref,
461}
462
463#[must_use]
469pub fn format_real(value: f64) -> String {
470 if !value.is_finite() {
471 return "0".to_owned();
472 }
473 let mut s = format!("{value:.6}");
474 if s.contains('.') {
475 let trimmed = s.trim_end_matches('0').trim_end_matches('.').len();
476 s.truncate(trimmed);
477 }
478 if s == "-0" {
479 s.clear();
480 s.push('0');
481 }
482 s
483}
484
485fn name_needs_escape(b: u8) -> bool {
487 !(b'!'..=b'~').contains(&b) || b"#()<>[]{}/%".contains(&b)
488}
489
490const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";
491
492fn push_hex(b: u8, out: &mut Vec<u8>) {
493 let digit = |nibble: u8| HEX_UPPER.get(usize::from(nibble)).copied().unwrap_or(b'0');
494 out.push(digit(b >> 4));
495 out.push(digit(b & 0x0F));
496}
497
498pub(crate) fn write_name(bytes: &[u8], out: &mut Vec<u8>) {
499 out.push(b'/');
500 for &b in bytes {
501 if name_needs_escape(b) {
502 out.push(b'#');
503 push_hex(b, out);
504 } else {
505 out.push(b);
506 }
507 }
508}
509
510pub(crate) fn write_literal_string(bytes: &[u8], out: &mut Vec<u8>) {
511 out.push(b'(');
512 for &b in bytes {
513 match b {
514 b'\\' | b'(' | b')' => {
515 out.push(b'\\');
516 out.push(b);
517 }
518 b'\r' => out.extend_from_slice(b"\\r"),
519 _ => out.push(b),
520 }
521 }
522 out.push(b')');
523}
524
525fn write_string(s: &PdfString, out: &mut Vec<u8>) {
526 match s.format {
527 StringFormat::Literal => write_literal_string(&s.bytes, out),
528 StringFormat::Hex => {
529 out.push(b'<');
530 for &b in &s.bytes {
531 push_hex(b, out);
532 }
533 out.push(b'>');
534 }
535 }
536}
537
538fn write_dict(d: &Dict, out: &mut Vec<u8>) {
539 out.extend_from_slice(b"<<");
540 for (k, v) in d.iter() {
541 out.push(b' ');
542 write_name(k.as_bytes(), out);
543 out.push(b' ');
544 v.write_to(out);
545 }
546 out.extend_from_slice(b" >>");
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552
553 fn ser(o: &Object) -> String {
554 String::from_utf8_lossy(&o.to_bytes()).into_owned()
555 }
556
557 #[test]
558 fn number_writes_integral_values_as_integers() {
559 assert_eq!(
560 (Object::number(612.0), Object::number(0.5), Object::number(-3.0)),
561 (Object::Integer(612), Object::Real(0.5), Object::Integer(-3))
562 );
563 }
564
565 #[test]
566 fn number_writes_a_non_finite_value_as_zero() {
567 assert_eq!(
568 [f64::NAN, f64::INFINITY].map(Object::number),
569 [Object::Integer(0), Object::Integer(0)]
570 );
571 }
572
573 #[test]
574 fn rounded_leaves_a_huge_value_as_it_is() {
575 assert_eq!(Object::rounded(1e300, 15), Object::Real(1e300));
576 }
577
578 #[test]
579 fn rounded_to_no_decimals_is_the_nearest_integer() {
580 assert_eq!(
581 (Object::rounded(95.5, 0), Object::rounded(-292.6, 0)),
582 (Object::Integer(96), Object::Integer(-293))
583 );
584 }
585
586 #[test]
587 fn rounded_rounds_then_writes_a_whole_result_as_an_integer() {
588 assert_eq!(
589 (
590 Object::rounded(-12.004, 2),
591 Object::rounded(-12.345, 2),
592 Object::rounded(600.098, 3)
593 ),
594 (Object::Integer(-12), Object::Real(-12.35), Object::Real(600.098))
595 );
596 }
597
598 #[test]
599 fn format_real_trims_trailing_zeros() {
600 assert_eq!(format_real(0.5), "0.5");
601 }
602
603 #[test]
604 fn format_real_drops_trailing_dot_for_whole_numbers() {
605 assert_eq!(format_real(1.0), "1");
606 }
607
608 #[test]
609 fn format_real_keeps_sign_of_negative_fraction() {
610 assert_eq!(format_real(-0.25), "-0.25");
611 }
612
613 #[test]
614 fn format_real_turns_negative_zero_into_zero() {
615 assert_eq!(format_real(-0.0), "0");
616 }
617
618 #[test]
619 fn format_real_turns_tiny_negative_rounding_to_zero_into_zero() {
620 assert_eq!(format_real(-0.000_000_1), "0");
621 }
622
623 #[test]
624 fn format_real_never_uses_an_exponent() {
625 assert_eq!(format_real(1e20), "100000000000000000000");
626 }
627
628 #[test]
629 fn format_real_rounds_exact_tie_half_to_even() {
630 assert_eq!(format_real(0.007_812_5), "0.007812");
632 }
633
634 #[test]
635 fn format_real_rounds_to_six_digits() {
636 assert_eq!(format_real(1.0 / 3.0), "0.333333");
637 }
638
639 #[test]
640 fn name_escapes_delimiters_space_and_hash() {
641 assert_eq!(
642 ser(&Object::Name(Name::new(&b"a b#(c)/%"[..]))),
643 "/a#20b#23#28c#29#2F#25"
644 );
645 }
646
647 #[test]
648 fn name_escapes_non_ascii_with_uppercase_hex() {
649 assert_eq!(ser(&Object::Name(Name::new(vec![0xE9, b'x']))), "/#E9x");
650 }
651
652 #[test]
653 fn literal_string_escapes_parens_backslash_and_cr() {
654 assert_eq!(
655 ser(&PdfString::literal(&b"a(b)c\\d\re\n"[..]).into()),
656 "(a\\(b\\)c\\\\d\\re\n)"
657 );
658 }
659
660 #[test]
661 fn hex_string_is_uppercase() {
662 assert_eq!(ser(&PdfString::hex(vec![0xAB, 0x01]).into()), "<AB01>");
663 }
664
665 #[test]
666 fn dict_uses_single_spaces() {
667 let d: Dict = [
668 ("K", Object::from(1)),
669 ("K2", Object::Array(vec![Object::Null, true.into()])),
670 ]
671 .into_iter()
672 .collect();
673 assert_eq!(ser(&d.into()), "<< /K 1 /K2 [null true] >>");
674 }
675
676 #[test]
677 fn empty_dict_serializes_as_double_brackets_with_space() {
678 assert_eq!(ser(&Dict::new().into()), "<< >>");
679 }
680
681 #[test]
682 fn stream_appends_length_last_when_absent() {
683 let s = Stream::new([("Type", Object::name("X"))].into_iter().collect(), b"abc".to_vec());
684 assert_eq!(ser(&s.into()), "<< /Type /X /Length 3 >>\nstream\nabc\nendstream");
685 }
686
687 #[test]
688 fn stream_keeps_caller_length_position() {
689 let d: Dict = [("Length", Object::from(99)), ("Filter", Object::name("F"))]
690 .into_iter()
691 .collect();
692 assert_eq!(
693 ser(&Stream::new(d, b"ab".to_vec()).into()),
694 "<< /Length 2 /Filter /F >>\nstream\nab\nendstream"
695 );
696 }
697
698 #[test]
699 fn dict_insert_keeps_existing_key_position() {
700 let mut d: Dict = [("A", 1), ("B", 2)].into_iter().collect();
701 d.insert("A", 3);
702 assert_eq!(ser(&d.into()), "<< /A 3 /B 2 >>");
703 }
704}