Skip to main content

pdfboss_write/
ser.rs

1//! COS object serialization: `Object` values to PDF syntax bytes
2//! (ISO 32000 §7.3). Output is deterministic — dictionary keys are emitted
3//! in sorted order regardless of insertion order.
4//!
5//! Streams are deliberately absent here: a stream is only legal as an
6//! indirect object and its `/Length` bookkeeping belongs to the
7//! [`Writer`](crate::Writer), so a nested `Object::Stream` is an error.
8
9use pdfboss_core::{Dict, Name, Object};
10
11use crate::error::{Error, Result};
12
13/// Serializes any non-stream object into `out`.
14///
15/// Numbers are written without exponents; reals trim trailing zeros and
16/// never produce `-0`. Non-finite reals serialize as `0` (PDF has no
17/// representation for them).
18pub fn serialize_object(obj: &Object, out: &mut Vec<u8>) -> Result<()> {
19    match obj {
20        Object::Null => out.extend_from_slice(b"null"),
21        Object::Bool(true) => out.extend_from_slice(b"true"),
22        Object::Bool(false) => out.extend_from_slice(b"false"),
23        Object::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
24        Object::Real(r) => write_real(*r, out),
25        Object::String(bytes) => write_string(bytes, out),
26        Object::Name(n) => {
27            nul_free(n)?;
28            write_name(&n.0, out);
29        }
30        Object::Array(items) => {
31            out.push(b'[');
32            for (i, item) in items.iter().enumerate() {
33                if i > 0 {
34                    out.push(b' ');
35                }
36                serialize_object(item, out)?;
37            }
38            out.push(b']');
39        }
40        Object::Dict(d) => serialize_dict(d, out)?,
41        Object::Ref(r) => {
42            out.extend_from_slice(r.num.to_string().as_bytes());
43            out.push(b' ');
44            out.extend_from_slice(r.gen.to_string().as_bytes());
45            out.extend_from_slice(b" R");
46        }
47        Object::Stream(_) => return Err(Error::NestedStream),
48    }
49    Ok(())
50}
51
52/// Serializes a dictionary with `<< … >>` delimiters, keys sorted
53/// bytewise for deterministic output.
54pub fn serialize_dict(dict: &Dict, out: &mut Vec<u8>) -> Result<()> {
55    out.extend_from_slice(b"<<");
56    let mut entries: Vec<(&Name, &Object)> = dict.iter().collect();
57    entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
58    for (key, value) in entries {
59        nul_free(key)?;
60        out.push(b' ');
61        write_name(&key.0, out);
62        out.push(b' ');
63        serialize_object(value, out)?;
64    }
65    out.extend_from_slice(b" >>");
66    Ok(())
67}
68
69/// Writes a name object with its leading solidus, escaping every byte
70/// outside the regular range as `#xx` (delimiters, whitespace, `#` itself,
71/// and anything outside `0x21..=0x7E`).
72pub fn write_name(name: &str, out: &mut Vec<u8>) {
73    out.push(b'/');
74    for &byte in name.as_bytes() {
75        if (0x21..=0x7E).contains(&byte) && !b"()<>[]{}/%#".contains(&byte) {
76            out.push(byte);
77            continue;
78        }
79        out.push(b'#');
80        push_hex(byte, out);
81    }
82}
83
84/// Writes a string object. Byte content that is printable ASCII (plus tab,
85/// newline and carriage return) uses the literal form with `\`-escapes;
86/// anything else uses the hex form. The choice is a pure function of the
87/// bytes, keeping output deterministic.
88pub fn write_string(bytes: &[u8], out: &mut Vec<u8>) {
89    let literal = bytes
90        .iter()
91        .all(|&b| (0x20..=0x7E).contains(&b) || matches!(b, b'\n' | b'\r' | b'\t'));
92    if !literal {
93        out.push(b'<');
94        for &byte in bytes {
95            push_hex(byte, out);
96        }
97        out.push(b'>');
98        return;
99    }
100    out.push(b'(');
101    for &byte in bytes {
102        match byte {
103            b'\\' | b'(' | b')' => {
104                out.push(b'\\');
105                out.push(byte);
106            }
107            b'\n' => out.extend_from_slice(b"\\n"),
108            b'\r' => out.extend_from_slice(b"\\r"),
109            b'\t' => out.extend_from_slice(b"\\t"),
110            other => out.push(other),
111        }
112    }
113    out.push(b')');
114}
115
116/// Writes a real number in plain decimal: no exponent, trailing zeros
117/// trimmed, `-0` normalized to `0`, non-finite values written as `0`.
118/// Whole values write as integers (`72` not `72.0`).
119pub fn write_real(value: f64, out: &mut Vec<u8>) {
120    if !value.is_finite() || value == 0.0 {
121        out.push(b'0');
122        return;
123    }
124    if value.fract() == 0.0 && value.abs() < 9_007_199_254_740_992.0 {
125        out.extend_from_slice((value as i64).to_string().as_bytes());
126        return;
127    }
128    out.extend_from_slice(plain_decimal(&value.to_string()).as_bytes());
129}
130
131/// Like [`write_real`], for `f32` values (content-stream operands): the
132/// shortest decimal that parses back to the identical `f32`.
133pub fn write_real_f32(value: f32, out: &mut Vec<u8>) {
134    if !value.is_finite() || value == 0.0 {
135        out.push(b'0');
136        return;
137    }
138    out.extend_from_slice(plain_decimal(&value.to_string()).as_bytes());
139}
140
141/// Rejects a name containing NUL: ISO 32000 forbids the `#00` escape, so
142/// such a name has no legal spelling. Object and dictionary serialization
143/// validate here; [`write_name`] itself stays infallible for callers whose
144/// names are structurally NUL-free (content-stream resource names).
145fn nul_free(name: &Name) -> Result<()> {
146    if name.0.bytes().all(|b| b != 0) {
147        return Ok(());
148    }
149    Err(Error::Other(format!(
150        "name {:?} contains NUL, which has no legal escape in a name",
151        name.0
152    )))
153}
154
155const HEX: &[u8; 16] = b"0123456789ABCDEF";
156
157fn push_hex(byte: u8, out: &mut Vec<u8>) {
158    out.push(HEX[usize::from(byte >> 4)]);
159    out.push(HEX[usize::from(byte & 0x0F)]);
160}
161
162fn plain_decimal(formatted: &str) -> String {
163    let expanded = match formatted.split_once(['e', 'E']) {
164        None => formatted.to_string(),
165        Some((mantissa, exponent)) => expand_exponent(mantissa, exponent),
166    };
167    if !expanded.contains('.') {
168        return expanded;
169    }
170    expanded
171        .trim_end_matches('0')
172        .trim_end_matches('.')
173        .to_string()
174}
175
176fn expand_exponent(mantissa: &str, exponent: &str) -> String {
177    let exp: i32 = exponent.parse().unwrap_or(0);
178    let (sign, unsigned) = match mantissa.strip_prefix('-') {
179        Some(rest) => ("-", rest),
180        None => ("", mantissa),
181    };
182    let (int_part, frac_part) = match unsigned.split_once('.') {
183        Some(parts) => parts,
184        None => (unsigned, ""),
185    };
186    let digits = format!("{int_part}{frac_part}");
187    let point = int_part.len() as i32 + exp;
188    if point <= 0 {
189        let zeros = "0".repeat(point.unsigned_abs() as usize);
190        return format!("{sign}0.{zeros}{digits}");
191    }
192    let point = point as usize;
193    if point >= digits.len() {
194        let zeros = "0".repeat(point - digits.len());
195        return format!("{sign}{digits}{zeros}");
196    }
197    format!("{sign}{}.{}", &digits[..point], &digits[point..])
198}
199
200#[cfg(test)]
201mod tests {
202    use pdfboss_core::parser::{NoResolve, Parser};
203    use pdfboss_core::{Dict, Name, ObjRef, Object, Stream};
204
205    use super::*;
206    use crate::error::Error;
207
208    fn name(text: &str) -> Name {
209        Name(text.to_string())
210    }
211
212    fn ser(obj: &Object) -> String {
213        let mut out = Vec::new();
214        serialize_object(obj, &mut out).expect("serializable object");
215        String::from_utf8(out).expect("serialized syntax is UTF-8")
216    }
217
218    fn real_str(value: f64) -> String {
219        let mut out = Vec::new();
220        write_real(value, &mut out);
221        String::from_utf8(out).expect("real syntax is ASCII")
222    }
223
224    fn real32_str(value: f32) -> String {
225        let mut out = Vec::new();
226        write_real_f32(value, &mut out);
227        String::from_utf8(out).expect("real syntax is ASCII")
228    }
229
230    fn name_str(text: &str) -> String {
231        let mut out = Vec::new();
232        write_name(text, &mut out);
233        String::from_utf8(out).expect("name syntax is ASCII")
234    }
235
236    fn string_str(bytes: &[u8]) -> String {
237        let mut out = Vec::new();
238        write_string(bytes, &mut out);
239        String::from_utf8(out).expect("string syntax is ASCII")
240    }
241
242    #[test]
243    fn scalars_serialize_exactly() {
244        assert_eq!(ser(&Object::Null), "null");
245        assert_eq!(ser(&Object::Bool(true)), "true");
246        assert_eq!(ser(&Object::Bool(false)), "false");
247        assert_eq!(ser(&Object::Int(42)), "42");
248        assert_eq!(ser(&Object::Int(-7)), "-7");
249        assert_eq!(ser(&Object::Int(i64::MIN)), "-9223372036854775808");
250        assert_eq!(ser(&Object::Int(i64::MAX)), "9223372036854775807");
251    }
252
253    #[test]
254    fn real_pins_exact_bytes() {
255        assert_eq!(real_str(0.0), "0");
256        assert_eq!(real_str(-0.0), "0");
257        assert_eq!(real_str(f64::NAN), "0");
258        assert_eq!(real_str(f64::INFINITY), "0");
259        assert_eq!(real_str(f64::NEG_INFINITY), "0");
260        assert_eq!(real_str(72.0), "72");
261        assert_eq!(real_str(-72.0), "-72");
262        assert_eq!(real_str(0.5), "0.5");
263        assert_eq!(real_str(-0.25), "-0.25");
264        assert_eq!(real_str(0.1), "0.1");
265        assert_eq!(real_str(1e-7), "0.0000001");
266        assert_eq!(real_str(1.5e-10), "0.00000000015");
267        assert_eq!(real_str(9007199254740991.0), "9007199254740991");
268        assert_eq!(real_str(-9007199254740991.0), "-9007199254740991");
269        assert_eq!(real_str(9007199254740992.0), "9007199254740992");
270        assert_eq!(real_str(1e300), format!("1{}", "0".repeat(300)));
271    }
272
273    #[test]
274    fn real_f32_round_trips_hard_cases() {
275        let cases = [
276            0.1f32,
277            1e-7f32,
278            16777216.0f32,
279            f32::MIN_POSITIVE,
280            3.4e38f32,
281            1073741824.0f32,
282        ];
283        for value in cases {
284            let text = real32_str(value);
285            assert!(
286                !text.contains(['e', 'E']),
287                "{value} produced exponent form {text}"
288            );
289            let parsed: f32 = text.parse().expect("output parses as f32");
290            assert_eq!(parsed.to_bits(), value.to_bits(), "{value} -> {text}");
291        }
292        assert_eq!(real32_str(-0.0f32), "0");
293        assert_eq!(real32_str(f32::NAN), "0");
294        assert_eq!(real32_str(f32::INFINITY), "0");
295    }
296
297    #[test]
298    fn real_f32_pins_exact_bytes() {
299        assert_eq!(real32_str(0.1f32), "0.1");
300        assert_eq!(real32_str(1e-7f32), "0.0000001");
301        assert_eq!(real32_str(16777216.0f32), "16777216");
302        assert_eq!(real32_str(1073741824.0f32), "1073741800");
303        assert_eq!(real32_str(3.4e38f32), format!("34{}", "0".repeat(37)));
304        assert_eq!(
305            real32_str(f32::MIN_POSITIVE),
306            format!("0.{}11754944", "0".repeat(37))
307        );
308    }
309
310    #[test]
311    fn plain_decimal_expands_exponents() {
312        assert_eq!(plain_decimal("1e300"), format!("1{}", "0".repeat(300)));
313        assert_eq!(plain_decimal("3.4e38"), format!("34{}", "0".repeat(37)));
314        assert_eq!(
315            plain_decimal("1.1754944e-38"),
316            format!("0.{}11754944", "0".repeat(37))
317        );
318        assert_eq!(plain_decimal("-2.5e3"), "-2500");
319        assert_eq!(plain_decimal("1.25e2"), "125");
320        assert_eq!(plain_decimal("1.25e1"), "12.5");
321        assert_eq!(plain_decimal("1.25e-1"), "0.125");
322        assert_eq!(plain_decimal("1e-1"), "0.1");
323        assert_eq!(plain_decimal("2.5E3"), "2500");
324        assert_eq!(plain_decimal("0.5"), "0.5");
325        assert_eq!(plain_decimal("1.50"), "1.5");
326        assert_eq!(plain_decimal("2.0"), "2");
327    }
328
329    #[test]
330    fn names_escape_irregular_bytes() {
331        assert_eq!(name_str("Type"), "/Type");
332        assert_eq!(name_str(""), "/");
333        assert_eq!(name_str("A B"), "/A#20B");
334        assert_eq!(name_str("A#B"), "/A#23B");
335        assert_eq!(name_str("A(B)"), "/A#28B#29");
336        assert_eq!(name_str("a/b"), "/a#2Fb");
337        assert_eq!(name_str("x[y]z"), "/x#5By#5Dz");
338        assert_eq!(name_str("{}"), "/#7B#7D");
339        assert_eq!(name_str("<>"), "/#3C#3E");
340        assert_eq!(name_str("%"), "/#25");
341        assert_eq!(name_str("Ä"), "/#C3#84");
342        assert_eq!(name_str("é"), "/#C3#A9");
343        assert_eq!(name_str("\u{7F}"), "/#7F");
344        assert_eq!(name_str("~!$&*+-.;=?@^"), "/~!$&*+-.;=?@^");
345    }
346
347    #[test]
348    fn strings_use_literal_form_with_escapes() {
349        assert_eq!(string_str(b"Hello"), "(Hello)");
350        assert_eq!(string_str(b""), "()");
351        assert_eq!(string_str(b"a(b)c"), "(a\\(b\\)c)");
352        assert_eq!(string_str(b"a\\b"), "(a\\\\b)");
353        assert_eq!(string_str(b"a\tb\nc\rd"), "(a\\tb\\nc\\rd)");
354    }
355
356    #[test]
357    fn strings_fall_back_to_hex_form() {
358        assert_eq!(string_str(&[0x00, 0xFF, 0x41]), "<00FF41>");
359        assert_eq!(string_str(&[0x7F]), "<7F>");
360        assert_eq!(string_str(&[0x1F]), "<1F>");
361        let long: Vec<u8> = (0u8..=255).collect();
362        let hex: String = (0u8..=255).map(|b| format!("{b:02X}")).collect();
363        assert_eq!(string_str(&long), format!("<{hex}>"));
364    }
365
366    #[test]
367    fn arrays_separate_items_with_single_spaces() {
368        assert_eq!(ser(&Object::Array(vec![])), "[]");
369        let arr = Object::Array(vec![
370            Object::Int(1),
371            Object::Real(2.5),
372            Object::Name(name("X")),
373        ]);
374        assert_eq!(ser(&arr), "[1 2.5 /X]");
375        let nested = Object::Array(vec![
376            Object::Array(vec![Object::Int(1), Object::Int(2)]),
377            Object::Array(vec![Object::Int(3)]),
378        ]);
379        assert_eq!(ser(&nested), "[[1 2] [3]]");
380    }
381
382    #[test]
383    fn dicts_sort_keys_bytewise() {
384        assert_eq!(ser(&Object::Dict(Dict::new())), "<< >>");
385
386        let mut d = Dict::new();
387        d.insert(name("Z"), Object::Int(2));
388        d.insert(name("A"), Object::Int(1));
389        assert_eq!(ser(&Object::Dict(d)), "<< /A 1 /Z 2 >>");
390
391        let mut d = Dict::new();
392        d.insert(name("a"), Object::Int(4));
393        d.insert(name("B"), Object::Int(3));
394        d.insert(name("AB"), Object::Int(2));
395        d.insert(name("AA"), Object::Int(1));
396        assert_eq!(ser(&Object::Dict(d)), "<< /AA 1 /AB 2 /B 3 /a 4 >>");
397    }
398
399    #[test]
400    fn nested_containers_serialize_recursively() {
401        let mut inner = Dict::new();
402        inner.insert(name("X"), Object::Int(1));
403        let mut outer = Dict::new();
404        outer.insert(name("D"), Object::Dict(inner));
405        outer.insert(
406            name("Arr"),
407            Object::Array(vec![Object::Null, Object::Bool(false)]),
408        );
409        assert_eq!(
410            ser(&Object::Dict(outer)),
411            "<< /Arr [null false] /D << /X 1 >> >>"
412        );
413    }
414
415    #[test]
416    fn refs_serialize_as_num_gen_r() {
417        assert_eq!(ser(&Object::Ref(ObjRef { num: 12, gen: 3 })), "12 3 R");
418        assert_eq!(ser(&Object::Ref(ObjRef { num: 1, gen: 0 })), "1 0 R");
419    }
420
421    #[test]
422    fn nested_streams_are_errors() {
423        let stream = Object::Stream(Stream {
424            dict: Dict::new(),
425            data: b"x".to_vec(),
426        });
427        let mut out = Vec::new();
428        let top = serialize_object(&stream, &mut out);
429        assert!(matches!(top, Err(Error::NestedStream)));
430
431        let in_array = serialize_object(&Object::Array(vec![stream.clone()]), &mut out);
432        assert!(matches!(in_array, Err(Error::NestedStream)));
433
434        let mut d = Dict::new();
435        d.insert(name("S"), stream);
436        let in_dict = serialize_object(&Object::Dict(d), &mut out);
437        assert!(matches!(in_dict, Err(Error::NestedStream)));
438    }
439
440    #[test]
441    fn serialized_objects_parse_back_equal() {
442        let mut inner = Dict::new();
443        inner.insert(name("Z"), Object::Int(1));
444        inner.insert(
445            name("A"),
446            Object::Array(vec![Object::Real(0.5), Object::Null]),
447        );
448        let mut outer = Dict::new();
449        outer.insert(
450            name("Kids"),
451            Object::Array(vec![Object::Ref(ObjRef { num: 7, gen: 0 })]),
452        );
453        outer.insert(name("Inner"), Object::Dict(inner));
454        outer.insert(name("Weird Name#"), Object::String(b"a(b)\\c".to_vec()));
455
456        let objects = vec![
457            Object::Null,
458            Object::Bool(true),
459            Object::Bool(false),
460            Object::Int(-42),
461            Object::Real(2.5),
462            Object::Real(-0.125),
463            Object::String(b"a(b)\\c".to_vec()),
464            Object::String(b"tab\there".to_vec()),
465            Object::String(vec![0u8, 255, 128]),
466            Object::Name(name("Weird Name#\u{C4}")),
467            Object::Ref(ObjRef { num: 12, gen: 3 }),
468            Object::Array(vec![]),
469            Object::Dict(Dict::new()),
470            Object::Dict(outer),
471        ];
472        for obj in objects {
473            let mut out = Vec::new();
474            serialize_object(&obj, &mut out).expect("serializable object");
475            let parsed = Parser::new(&out)
476                .parse_object(&NoResolve)
477                .expect("serialized bytes parse");
478            assert_eq!(
479                parsed,
480                obj,
481                "round-trip of {}",
482                String::from_utf8_lossy(&out)
483            );
484        }
485    }
486
487    #[test]
488    fn integral_reals_parse_back_as_ints() {
489        let mut out = Vec::new();
490        serialize_object(&Object::Real(72.0), &mut out).expect("serializable object");
491        assert_eq!(out, b"72");
492        let parsed = Parser::new(&out)
493            .parse_object(&NoResolve)
494            .expect("serialized bytes parse");
495        assert_eq!(parsed, Object::Int(72));
496    }
497
498    #[test]
499    fn names_with_nul_bytes_are_rejected() {
500        let mut out = Vec::new();
501        let err = serialize_object(&Object::Name(name("a\0b")), &mut out)
502            .expect_err("a NUL in a name must not serialize");
503        assert!(err.to_string().contains("NUL"), "{err}");
504        let mut d = Dict::new();
505        d.insert(name("a\0b"), Object::Int(1));
506        let mut out = Vec::new();
507        assert!(serialize_dict(&d, &mut out).is_err());
508    }
509}