1use std::io::Write;
15
16use flate2::write::ZlibEncoder;
17use flate2::Compression;
18use pdfboss_core::crypt::Sha256;
19use pdfboss_core::{block_on, Dict, Encryptor, Name, ObjRef, Object, Stream};
20
21use crate::error::{Error, Result};
22use crate::ser::{serialize_dict, serialize_object};
23use crate::sink::{AsyncByteSink, Immediate};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum XrefStyle {
28 Table,
31 #[default]
34 Stream,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq)]
39pub struct WriteOptions {
40 pub xref: XrefStyle,
42 pub compress: bool,
44 pub object_streams: bool,
47 pub version: (u8, u8),
49}
50
51impl Default for WriteOptions {
52 fn default() -> WriteOptions {
53 WriteOptions {
54 xref: XrefStyle::Stream,
55 compress: true,
56 object_streams: true,
57 version: (1, 7),
58 }
59 }
60}
61
62pub struct Writer {
66 options: WriteOptions,
67 slots: Vec<Slot>,
68 info: Option<ObjRef>,
69 encryption: Option<(Encryptor, Dict)>,
74}
75
76impl std::fmt::Debug for Writer {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.debug_struct("Writer")
81 .field("options", &self.options)
82 .field("slots", &self.slots)
83 .field("info", &self.info)
84 .field("encrypted", &self.encryption.is_some())
85 .finish()
86 }
87}
88
89#[derive(Debug)]
91enum Slot {
92 Reserved,
93 Filled(Object),
94}
95
96impl Writer {
97 pub fn new(options: WriteOptions) -> Writer {
99 Writer {
100 options,
101 slots: Vec::new(),
102 info: None,
103 encryption: None,
104 }
105 }
106
107 pub fn new_encrypted(
118 options: WriteOptions,
119 encryptor: Encryptor,
120 encrypt_dict: Dict,
121 ) -> Writer {
122 Writer {
123 options,
124 slots: Vec::new(),
125 info: None,
126 encryption: Some((encryptor, encrypt_dict)),
127 }
128 }
129
130 pub fn reserve(&mut self) -> ObjRef {
133 self.push(Slot::Reserved)
134 }
135
136 pub fn put(&mut self, obj: Object) -> ObjRef {
138 self.push(Slot::Filled(obj))
139 }
140
141 pub fn put_stream(&mut self, mut dict: Dict, data: Vec<u8>) -> ObjRef {
145 let data = compress_into(&mut dict, data, self.options.compress);
146 self.push(Slot::Filled(Object::Stream(Stream { dict, data })))
147 }
148
149 pub fn put_stream_raw(&mut self, dict: Dict, data: Vec<u8>) -> ObjRef {
153 self.push(Slot::Filled(Object::Stream(Stream { dict, data })))
154 }
155
156 pub fn fill(&mut self, r: ObjRef, obj: Object) -> Result<()> {
158 if r.gen != 0 {
159 return Err(Error::Other(format!(
160 "cannot fill {} {} R: this writer only issues generation 0",
161 r.num, r.gen
162 )));
163 }
164 if r.num == 0 || r.num as usize > self.slots.len() {
165 return Err(Error::Other(format!(
166 "cannot fill {} 0 R: this writer never allocated that object number",
167 r.num
168 )));
169 }
170 let slot = &mut self.slots[r.num as usize - 1];
171 if matches!(slot, Slot::Filled(_)) {
172 return Err(Error::AlreadyFilled(r));
173 }
174 *slot = Slot::Filled(obj);
175 Ok(())
176 }
177
178 fn push(&mut self, slot: Slot) -> ObjRef {
179 self.slots.push(slot);
180 ObjRef {
181 num: self.slots.len() as u32,
182 gen: 0,
183 }
184 }
185
186 pub fn set_info(&mut self, info: ObjRef) {
188 self.info = Some(info);
189 }
190
191 pub fn compress(&self) -> bool {
193 self.options.compress
194 }
195
196 pub fn finish(self, root: ObjRef) -> Result<Vec<u8>> {
202 block_on(self.finish_into_with(root, Vec::new()))
203 }
204
205 pub fn finish_into(self, root: ObjRef, out: impl Write) -> Result<()> {
210 block_on(self.finish_into_with(root, Immediate(out)))?;
211 Ok(())
212 }
213
214 pub async fn finish_into_with<S: AsyncByteSink>(self, root: ObjRef, sink: S) -> Result<S> {
221 let Writer {
222 options,
223 slots,
224 info,
225 mut encryption,
226 } = self;
227 let mut bodies = Vec::with_capacity(slots.len());
228 for (index, slot) in slots.into_iter().enumerate() {
229 match slot {
230 Slot::Reserved => {
231 return Err(Error::Unfilled(ObjRef {
232 num: index as u32 + 1,
233 gen: 0,
234 }))
235 }
236 Slot::Filled(obj) => bodies.push(obj),
237 }
238 }
239 let (encryptor, encrypt_dict) = split_encryption(&mut encryption);
240 let mut emit = Emit::new(sink);
241 match options.xref {
242 XrefStyle::Table => {
243 emit_table(
244 options,
245 &bodies,
246 root,
247 info,
248 encryptor,
249 encrypt_dict,
250 &mut emit,
251 )
252 .await?
253 }
254 XrefStyle::Stream => {
255 emit_stream(
256 options,
257 &bodies,
258 root,
259 info,
260 encryptor,
261 encrypt_dict,
262 &mut emit,
263 )
264 .await?
265 }
266 }
267 Ok(emit.sink)
268 }
269}
270
271fn split_encryption(
277 encryption: &mut Option<(Encryptor, Dict)>,
278) -> (Option<&mut Encryptor>, Option<&Dict>) {
279 match encryption {
280 Some((enc, dict)) => (Some(enc), Some(&*dict)),
281 None => (None, None),
282 }
283}
284
285struct Emit<S> {
289 sink: S,
290 count: usize,
291 hasher: Sha256,
292}
293
294impl<S: AsyncByteSink> Emit<S> {
295 fn new(sink: S) -> Emit<S> {
296 Emit {
297 sink,
298 count: 0,
299 hasher: Sha256::new(),
300 }
301 }
302
303 async fn write(&mut self, bytes: &[u8]) -> Result<()> {
304 self.hasher.update(bytes);
305 self.count += bytes.len();
306 self.sink.write_all(bytes).await
307 }
308
309 fn file_id(&self) -> Object {
314 let digest = self.hasher.clone().finalize();
315 let id = Object::String(digest[..16].to_vec());
316 Object::Array(vec![id.clone(), id])
317 }
318}
319
320const OBJSTM_CAPACITY: usize = 200;
322
323#[derive(Clone, Copy)]
326enum Row {
327 Top(u32),
328 Packed { container: u32, index: u16 },
329}
330
331async fn emit_table<S: AsyncByteSink>(
335 options: WriteOptions,
336 bodies: &[Object],
337 root: ObjRef,
338 info: Option<ObjRef>,
339 mut encryptor: Option<&mut Encryptor>,
340 encrypt_dict: Option<&Dict>,
341 emit: &mut Emit<S>,
342) -> Result<()> {
343 let mut head = Vec::new();
344 write_header(&mut head, options.version);
345 emit.write(&head).await?;
346 let mut offsets = Vec::with_capacity(bodies.len() + 1);
347 for (index, body) in bodies.iter().enumerate() {
348 offsets.push(emit.count);
349 let num = index as u32 + 1;
350 write_indirect_maybe_encrypted(emit, num, body, encryptor.as_deref_mut()).await?;
351 }
352 let mut encrypt_ref = None;
353 if let Some(dict) = encrypt_dict {
354 let num = bodies.len() as u32 + 1;
355 offsets.push(emit.count);
356 write_indirect(emit, num, &Object::Dict(dict.clone())).await?;
357 encrypt_ref = Some(ObjRef { num, gen: 0 });
358 }
359 let id = emit.file_id();
360 let xref_off = emit.count;
361 let mut section = format!("xref\n0 {}\n", offsets.len() + 1).into_bytes();
362 section.extend_from_slice(b"0000000000 65535 f\r\n");
363 let size = offsets.len() as i64 + 1;
364 for offset in offsets {
365 let offset = table_offset(offset)?;
366 section.extend_from_slice(format!("{offset:010} 00000 n\r\n").as_bytes());
367 }
368 section.extend_from_slice(b"trailer\n");
369 let mut trailer = trailer_dict(size, root, info, id);
370 if let Some(r) = encrypt_ref {
371 trailer.insert(literal("Encrypt"), Object::Ref(r));
372 }
373 serialize_dict(&trailer, &mut section)?;
374 section.extend_from_slice(format!("\nstartxref\n{xref_off}\n%%EOF").as_bytes());
375 emit.write(§ion).await
376}
377
378async fn emit_stream<S: AsyncByteSink>(
387 options: WriteOptions,
388 bodies: &[Object],
389 root: ObjRef,
390 info: Option<ObjRef>,
391 mut encryptor: Option<&mut Encryptor>,
392 encrypt_dict: Option<&Dict>,
393 emit: &mut Emit<S>,
394) -> Result<()> {
395 let mut head = Vec::new();
396 write_header(&mut head, options.version);
397 emit.write(&head).await?;
398 let user_count = bodies.len() as u32;
399
400 let packed: Vec<u32> = if options.object_streams {
401 bodies
402 .iter()
403 .enumerate()
404 .filter(|(_, body)| !matches!(body, Object::Stream(_)))
405 .map(|(index, _)| index as u32 + 1)
406 .collect()
407 } else {
408 Vec::new()
409 };
410 let chunks: Vec<&[u32]> = packed.chunks(OBJSTM_CAPACITY).collect();
411
412 let mut rows: Vec<Row> = vec![Row::Top(0); bodies.len()];
413 for (c, chunk) in chunks.iter().enumerate() {
414 for (index, num) in chunk.iter().enumerate() {
415 rows[*num as usize - 1] = Row::Packed {
416 container: user_count + c as u32 + 1,
417 index: index as u16,
418 };
419 }
420 }
421
422 for (index, body) in bodies.iter().enumerate() {
423 if matches!(rows[index], Row::Packed { .. }) {
424 continue;
425 }
426 rows[index] = Row::Top(field_offset(emit.count)?);
427 let num = index as u32 + 1;
428 write_indirect_maybe_encrypted(emit, num, body, encryptor.as_deref_mut()).await?;
429 }
430
431 let mut container_offsets = Vec::with_capacity(chunks.len());
432 for (c, chunk) in chunks.iter().enumerate() {
433 let pairs: Vec<(u32, &Object)> = chunk
434 .iter()
435 .map(|&num| (num, &bodies[num as usize - 1]))
436 .collect();
437 let container = build_objstm(&pairs, options.compress)?;
438 container_offsets.push(field_offset(emit.count)?);
439 let num = user_count + c as u32 + 1;
440 let mut container = Object::Stream(container);
441 if let Some(encryptor) = encryptor.as_deref_mut() {
442 encryptor.encrypt_object(&mut container, num, 0);
443 }
444 write_indirect(emit, num, &container).await?;
445 }
446
447 let mut next_num = user_count + chunks.len() as u32 + 1;
448 let mut encrypt_row = None;
449 if let Some(dict) = encrypt_dict {
450 let offset = field_offset(emit.count)?;
451 write_indirect(emit, next_num, &Object::Dict(dict.clone())).await?;
452 encrypt_row = Some((
453 ObjRef {
454 num: next_num,
455 gen: 0,
456 },
457 offset,
458 ));
459 next_num += 1;
460 }
461 let xref_num = next_num;
462 let id = emit.file_id();
463 let xref_off = field_offset(emit.count)?;
464
465 let mut data = Vec::with_capacity(7 * (xref_num as usize + 1));
466 push_row(&mut data, 0, 0, 65535);
467 for row in rows {
468 match row {
469 Row::Top(offset) => push_row(&mut data, 1, offset, 0),
470 Row::Packed { container, index } => push_row(&mut data, 2, container, index),
471 }
472 }
473 for offset in container_offsets {
474 push_row(&mut data, 1, offset, 0);
475 }
476 if let Some((_, offset)) = encrypt_row {
477 push_row(&mut data, 1, offset, 0);
478 }
479 push_row(&mut data, 1, xref_off, 0);
480
481 let mut dict = trailer_dict(xref_num as i64 + 1, root, info, id);
482 if let Some((r, _)) = encrypt_row {
483 dict.insert(literal("Encrypt"), Object::Ref(r));
484 }
485 dict.insert(literal("Type"), Object::Name(literal("XRef")));
486 dict.insert(
487 literal("W"),
488 Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]),
489 );
490 let data = compress_into(&mut dict, data, options.compress);
491 write_indirect(emit, xref_num, &Object::Stream(Stream { dict, data })).await?;
492 emit.write(format!("startxref\n{xref_off}\n%%EOF").as_bytes())
493 .await
494}
495
496fn write_header(out: &mut Vec<u8>, version: (u8, u8)) {
498 out.extend_from_slice(format!("%PDF-{}.{}\n", version.0, version.1).as_bytes());
499 out.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n");
500}
501
502async fn write_indirect<S: AsyncByteSink>(
508 emit: &mut Emit<S>,
509 num: u32,
510 obj: &Object,
511) -> Result<()> {
512 let mut lead = format!("{num} 0 obj\n").into_bytes();
513 match obj {
514 Object::Stream(s) => {
515 let mut dict = s.dict.clone();
516 dict.insert(literal("Length"), Object::Int(s.data.len() as i64));
517 serialize_dict(&dict, &mut lead)?;
518 lead.extend_from_slice(b"\nstream\n");
519 emit.write(&lead).await?;
520 emit.write(&s.data).await?;
521 emit.write(b"\nendstream\nendobj\n").await
522 }
523 direct => {
524 serialize_object(direct, &mut lead)?;
525 lead.extend_from_slice(b"\nendobj\n");
526 emit.write(&lead).await
527 }
528 }
529}
530
531async fn write_indirect_maybe_encrypted<S: AsyncByteSink>(
537 emit: &mut Emit<S>,
538 num: u32,
539 obj: &Object,
540 encryptor: Option<&mut Encryptor>,
541) -> Result<()> {
542 match encryptor {
543 Some(encryptor) => {
544 let mut obj = obj.clone();
545 encryptor.encrypt_object(&mut obj, num, 0);
546 write_indirect(emit, num, &obj).await
547 }
548 None => write_indirect(emit, num, obj).await,
549 }
550}
551
552fn build_objstm(pairs: &[(u32, &Object)], compress: bool) -> Result<Stream> {
556 let mut header = Vec::new();
557 let mut payload = Vec::new();
558 for (num, body) in pairs {
559 header.extend_from_slice(format!("{num} {} ", payload.len()).as_bytes());
560 serialize_object(body, &mut payload)?;
561 payload.push(b' ');
562 }
563 let mut dict = Dict::new();
564 dict.insert(literal("Type"), Object::Name(literal("ObjStm")));
565 dict.insert(literal("N"), Object::Int(pairs.len() as i64));
566 dict.insert(literal("First"), Object::Int(header.len() as i64));
567 header.extend_from_slice(&payload);
568 let data = compress_into(&mut dict, header, compress);
569 Ok(Stream { dict, data })
570}
571
572fn trailer_dict(size: i64, root: ObjRef, info: Option<ObjRef>, id: Object) -> Dict {
577 let mut trailer = Dict::new();
578 trailer.insert(literal("Size"), Object::Int(size));
579 trailer.insert(literal("Root"), Object::Ref(root));
580 if let Some(info) = info {
581 trailer.insert(literal("Info"), Object::Ref(info));
582 }
583 trailer.insert(literal("ID"), id);
584 trailer
585}
586
587fn compress_into(dict: &mut Dict, data: Vec<u8>, compress: bool) -> Vec<u8> {
591 if !compress || dict.get("Filter").is_some() {
592 return data;
593 }
594 dict.insert(literal("Filter"), Object::Name(literal("FlateDecode")));
595 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
596 encoder
597 .write_all(&data)
598 .expect("writing into a Vec cannot fail");
599 encoder
600 .finish()
601 .expect("finishing an in-memory zlib stream cannot fail")
602}
603
604fn push_row(rows: &mut Vec<u8>, kind: u8, second: u32, third: u16) {
606 rows.push(kind);
607 rows.extend_from_slice(&second.to_be_bytes());
608 rows.extend_from_slice(&third.to_be_bytes());
609}
610
611fn field_offset(position: usize) -> Result<u32> {
613 u32::try_from(position)
614 .map_err(|_| Error::Other("file offset exceeds the 4-byte xref field".to_string()))
615}
616
617fn table_offset(position: usize) -> Result<usize> {
621 if position as u64 <= 9_999_999_999 {
622 return Ok(position);
623 }
624 Err(Error::Other(
625 "file offset exceeds the 10-digit xref table field".to_string(),
626 ))
627}
628
629fn literal(text: &str) -> Name {
631 Name(text.to_string())
632}
633
634#[cfg(test)]
635mod tests {
636 use pdfboss_core::xref::load_xref;
637 use pdfboss_core::{Dict, Document, Name, ObjRef, Object, Stream};
638
639 use super::*;
640 use crate::error::Error;
641
642 const CONTENT: &[u8] = b"BT /F1 12 Tf 72 720 Td (Hello, writer) Tj ET";
643
644 fn name(text: &str) -> Name {
645 Name(text.to_string())
646 }
647
648 fn table_options() -> WriteOptions {
649 WriteOptions {
650 xref: XrefStyle::Table,
651 compress: false,
652 object_streams: false,
653 version: (1, 7),
654 }
655 }
656
657 fn stream_options() -> WriteOptions {
658 WriteOptions {
659 xref: XrefStyle::Stream,
660 compress: false,
661 object_streams: false,
662 version: (1, 5),
663 }
664 }
665
666 fn objstm_options() -> WriteOptions {
667 WriteOptions {
668 xref: XrefStyle::Stream,
669 compress: true,
670 object_streams: true,
671 version: (1, 7),
672 }
673 }
674
675 struct Refs {
676 content: ObjRef,
677 pages: ObjRef,
678 page: ObjRef,
679 root: ObjRef,
680 }
681
682 fn page_dict(pages: ObjRef, content: ObjRef) -> Dict {
683 let mut page = Dict::new();
684 page.insert(name("Type"), Object::Name(name("Page")));
685 page.insert(name("Parent"), Object::Ref(pages));
686 page.insert(
687 name("MediaBox"),
688 Object::Array(vec![
689 Object::Int(0),
690 Object::Int(0),
691 Object::Int(612),
692 Object::Int(792),
693 ]),
694 );
695 page.insert(name("Contents"), Object::Ref(content));
696 page
697 }
698
699 fn build(
702 options: WriteOptions,
703 content_dict: Dict,
704 content_data: Vec<u8>,
705 raw: bool,
706 ) -> (Writer, Refs) {
707 let mut w = Writer::new(options);
708 let content = if raw {
709 w.put_stream_raw(content_dict, content_data)
710 } else {
711 w.put_stream(content_dict, content_data)
712 };
713 let pages = w.reserve();
714 let page = w.put(Object::Dict(page_dict(pages, content)));
715 let mut tree = Dict::new();
716 tree.insert(name("Type"), Object::Name(name("Pages")));
717 tree.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
718 tree.insert(name("Count"), Object::Int(1));
719 w.fill(pages, Object::Dict(tree))
720 .expect("pages slot is fillable");
721 let mut catalog = Dict::new();
722 catalog.insert(name("Type"), Object::Name(name("Catalog")));
723 catalog.insert(name("Pages"), Object::Ref(pages));
724 let root = w.put(Object::Dict(catalog));
725 (
726 w,
727 Refs {
728 content,
729 pages,
730 page,
731 root,
732 },
733 )
734 }
735
736 fn skeleton(
738 options: WriteOptions,
739 content_dict: Dict,
740 content_data: Vec<u8>,
741 raw: bool,
742 ) -> (Vec<u8>, Refs) {
743 let (w, refs) = build(options, content_dict, content_data, raw);
744 let bytes = w.finish(refs.root).expect("minimal document finishes");
745 (bytes, refs)
746 }
747
748 fn minimal_pdf(options: WriteOptions) -> (Vec<u8>, Refs) {
749 skeleton(options, Dict::new(), CONTENT.to_vec(), false)
750 }
751
752 fn assert_minimal_loads(bytes: &[u8], refs: &Refs) -> Document {
753 let doc = Document::load(bytes.to_vec()).expect("document loads");
754 assert_eq!(doc.page_count(), 1);
755 let page = doc.page(0).expect("page 0 exists");
756 assert_eq!(page.object_ref(), Some(refs.page));
757 assert_eq!(page.dict(), &page_dict(refs.pages, refs.content));
758 assert_eq!(page.content(&doc).expect("content decodes"), CONTENT);
759 doc
760 }
761
762 fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
763 haystack
764 .windows(needle.len())
765 .filter(|window| *window == needle)
766 .count()
767 }
768
769 #[test]
771 fn table_mode_minimal_document_loads() {
772 let (bytes, refs) = minimal_pdf(table_options());
773 assert!(bytes.starts_with(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n"));
774 assert!(bytes.ends_with(b"%%EOF"));
775 assert_eq!(count_occurrences(&bytes, b"xref\n0 5\n"), 1);
776 assert_eq!(count_occurrences(&bytes, b"0000000000 65535 f\r\n"), 1);
777 assert_eq!(count_occurrences(&bytes, b"trailer\n"), 1);
778 assert_minimal_loads(&bytes, &refs);
779 }
780
781 #[test]
782 fn table_mode_ignores_object_streams_option() {
783 let options = WriteOptions {
784 object_streams: true,
785 ..table_options()
786 };
787 let (bytes, refs) = minimal_pdf(options);
788 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 0);
789 assert_minimal_loads(&bytes, &refs);
790 }
791
792 #[test]
793 fn stream_mode_minimal_document_loads() {
794 let (bytes, refs) = minimal_pdf(stream_options());
795 assert!(bytes.starts_with(b"%PDF-1.5\n%\xE2\xE3\xCF\xD3\n"));
796 assert!(bytes.ends_with(b"%%EOF"));
797 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 0);
798 assert_eq!(count_occurrences(&bytes, b"/XRef"), 1);
799 assert_minimal_loads(&bytes, &refs);
800 }
801
802 #[test]
803 fn object_streams_pack_and_resolve() {
804 let (bytes, refs) = minimal_pdf(objstm_options());
805 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 1);
806 let doc = assert_minimal_loads(&bytes, &refs);
807 let root = doc
808 .resolve(&Object::Ref(refs.root))
809 .expect("catalog resolves");
810 let catalog = root.as_dict().expect("catalog is a dictionary");
811 assert_eq!(catalog.get_name("Type"), Some(&name("Catalog")));
812 assert_eq!(catalog.get_ref("Pages"), Some(refs.pages));
813 }
814
815 #[test]
816 fn object_streams_chunk_at_two_hundred() {
817 let options = WriteOptions {
818 compress: false,
819 ..objstm_options()
820 };
821 let mut w = Writer::new(options);
822 let content = w.put_stream(Dict::new(), CONTENT.to_vec());
823 let int_refs: Vec<ObjRef> = (0..205).map(|i| w.put(Object::Int(i))).collect();
824 let pages = w.reserve();
825 let page = w.put(Object::Dict(page_dict(pages, content)));
826 let mut tree = Dict::new();
827 tree.insert(name("Type"), Object::Name(name("Pages")));
828 tree.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
829 tree.insert(name("Count"), Object::Int(1));
830 w.fill(pages, Object::Dict(tree))
831 .expect("pages slot is fillable");
832 let mut catalog = Dict::new();
833 catalog.insert(name("Type"), Object::Name(name("Catalog")));
834 catalog.insert(name("Pages"), Object::Ref(pages));
835 let root = w.put(Object::Dict(catalog));
836 let bytes = w.finish(root).expect("document finishes");
837 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 2);
838 let doc = Document::load(bytes).expect("document loads");
839 assert_eq!(
840 doc.resolve(&Object::Ref(int_refs[0])).expect("resolves"),
841 Object::Int(0)
842 );
843 assert_eq!(
844 doc.resolve(&Object::Ref(int_refs[204])).expect("resolves"),
845 Object::Int(204)
846 );
847 assert_eq!(doc.page_count(), 1);
848 }
849
850 #[test]
851 fn refs_ascend_from_one_in_call_order() {
852 let mut w = Writer::new(table_options());
853 assert_eq!(w.put(Object::Null), ObjRef { num: 1, gen: 0 });
854 assert_eq!(w.reserve(), ObjRef { num: 2, gen: 0 });
855 assert_eq!(
856 w.put_stream(Dict::new(), Vec::new()),
857 ObjRef { num: 3, gen: 0 }
858 );
859 assert_eq!(
860 w.put_stream_raw(Dict::new(), Vec::new()),
861 ObjRef { num: 4, gen: 0 }
862 );
863 }
864
865 #[test]
866 fn fill_twice_reports_already_filled() {
867 let mut w = Writer::new(table_options());
868 let r = w.reserve();
869 w.fill(r, Object::Int(1)).expect("first fill lands");
870 match w.fill(r, Object::Int(2)) {
871 Err(Error::AlreadyFilled(seen)) => assert_eq!(seen, r),
872 other => panic!("expected AlreadyFilled, got {other:?}"),
873 }
874 }
875
876 #[test]
877 fn fill_rejects_foreign_and_wrong_generation_refs() {
878 let mut w = Writer::new(table_options());
879 let r = w.reserve();
880 let unallocated = w.fill(ObjRef { num: 99, gen: 0 }, Object::Null);
881 assert!(matches!(unallocated, Err(Error::Other(msg)) if msg.contains("99")));
882 let zero = w.fill(ObjRef { num: 0, gen: 0 }, Object::Null);
883 assert!(matches!(zero, Err(Error::Other(msg)) if !msg.is_empty()));
884 let wrong_gen = w.fill(ObjRef { num: r.num, gen: 1 }, Object::Null);
885 assert!(matches!(wrong_gen, Err(Error::Other(msg)) if msg.contains("generation")));
886 }
887
888 #[test]
889 fn finish_with_unfilled_reserve_reports_the_ref() {
890 let mut w = Writer::new(table_options());
891 let root = w.put(Object::Dict(Dict::new()));
892 let reserved = w.reserve();
893 match w.finish(root) {
894 Err(Error::Unfilled(seen)) => assert_eq!(seen, reserved),
895 other => panic!("expected Unfilled, got {other:?}"),
896 }
897 }
898
899 #[test]
900 fn nested_stream_surfaces_from_finish() {
901 for options in [table_options(), objstm_options()] {
902 let mut w = Writer::new(options);
903 let root = w.put(Object::Array(vec![Object::Stream(Stream {
904 dict: Dict::new(),
905 data: b"x".to_vec(),
906 })]));
907 assert!(matches!(w.finish(root), Err(Error::NestedStream)));
908 }
909 }
910
911 #[test]
912 fn compressed_stream_round_trips() {
913 let options = WriteOptions {
914 compress: true,
915 ..table_options()
916 };
917 let data: Vec<u8> = b"q 0.5 0 0 0.5 36 36 cm Q\n".repeat(40);
918 let (bytes, refs) = skeleton(options, Dict::new(), data.clone(), false);
919 let doc = Document::load(bytes).expect("document loads");
920 let resolved = doc
921 .resolve(&Object::Ref(refs.content))
922 .expect("content stream resolves");
923 let stream = resolved.as_stream().expect("content is a stream");
924 assert_eq!(stream.dict.get_name("Filter"), Some(&name("FlateDecode")));
925 assert_eq!(
926 stream.dict.get_int("Length"),
927 Some(stream.data.len() as i64)
928 );
929 assert!(stream.data.len() < data.len());
930 assert_eq!(doc.stream_data(stream).expect("stream decodes"), data);
931 }
932
933 #[test]
934 fn preset_filter_is_not_recompressed() {
935 let options = WriteOptions {
936 compress: true,
937 ..table_options()
938 };
939 let payload = b"Hello writer";
940 let encoded: Vec<u8> = payload
941 .iter()
942 .flat_map(|b| format!("{b:02X}").into_bytes())
943 .chain(*b">")
944 .collect();
945 let mut dict = Dict::new();
946 dict.insert(name("Filter"), Object::Name(name("ASCIIHexDecode")));
947 let (bytes, refs) = skeleton(options, dict, encoded.clone(), false);
948 let doc = Document::load(bytes).expect("document loads");
949 let resolved = doc
950 .resolve(&Object::Ref(refs.content))
951 .expect("content stream resolves");
952 let stream = resolved.as_stream().expect("content is a stream");
953 assert_eq!(stream.data, encoded, "pre-filtered data stays untouched");
954 assert_eq!(
955 stream.dict.get_name("Filter"),
956 Some(&name("ASCIIHexDecode"))
957 );
958 assert_eq!(doc.stream_data(stream).expect("stream decodes"), payload);
959 }
960
961 #[test]
962 fn put_stream_raw_never_compresses() {
963 let options = WriteOptions {
964 compress: true,
965 ..table_options()
966 };
967 let (bytes, refs) = skeleton(options, Dict::new(), CONTENT.to_vec(), true);
968 let doc = Document::load(bytes).expect("document loads");
969 let resolved = doc
970 .resolve(&Object::Ref(refs.content))
971 .expect("content stream resolves");
972 let stream = resolved.as_stream().expect("content is a stream");
973 assert_eq!(stream.data, CONTENT);
974 assert!(stream.dict.get("Filter").is_none());
975 assert_eq!(stream.dict.get_int("Length"), Some(CONTENT.len() as i64));
976 }
977
978 #[test]
979 fn table_offsets_past_ten_digits_are_rejected() {
980 assert_eq!(table_offset(9_999_999_999).ok(), Some(9_999_999_999));
981 assert!(table_offset(10_000_000_000).is_err());
982 }
983
984 #[test]
986 fn id_derives_from_the_emitted_content() {
987 let (a, refs) = minimal_pdf(table_options());
988 assert_eq!(refs.root.gen, 0);
989 let (b, other_refs) = skeleton(
990 table_options(),
991 Dict::new(),
992 b"BT /F1 12 Tf 72 720 Td (Hello, other) Tj ET".to_vec(),
993 false,
994 );
995 assert_eq!(other_refs.root.gen, 0);
996 let id_of = |bytes: &[u8]| {
997 let xref = load_xref(bytes).expect("xref loads");
998 let id = xref.trailer.get_array("ID").expect("/ID array present");
999 id[0]
1000 .as_str_bytes()
1001 .expect("/ID entry is a string")
1002 .to_vec()
1003 };
1004 assert_ne!(
1005 id_of(&a),
1006 id_of(&b),
1007 "/ID must depend on the emitted content"
1008 );
1009 }
1010
1011 #[test]
1013 fn id_pair_is_present_and_identical() {
1014 for options in [table_options(), stream_options(), objstm_options()] {
1015 let (bytes, refs) = minimal_pdf(options);
1016 assert_eq!(refs.root.gen, 0);
1017 let xref = load_xref(&bytes).expect("xref loads");
1018 let id = xref.trailer.get_array("ID").expect("/ID array present");
1019 assert_eq!(id.len(), 2);
1020 let first = id[0].as_str_bytes().expect("/ID entry is a string");
1021 let second = id[1].as_str_bytes().expect("/ID entry is a string");
1022 assert_eq!(first.len(), 16);
1023 assert_eq!(first, second);
1024 }
1025 }
1026
1027 #[test]
1028 fn output_is_deterministic() {
1029 for options in [table_options(), stream_options(), objstm_options()] {
1030 let (first, refs) = minimal_pdf(options);
1031 let (second, again) = minimal_pdf(options);
1032 assert_eq!(refs.content, again.content);
1033 assert_eq!(first, second, "options {options:?} must be deterministic");
1034 }
1035 }
1036
1037 #[test]
1038 fn finish_into_matches_finish() {
1039 for options in [table_options(), stream_options(), objstm_options()] {
1040 let (bytes, _) = minimal_pdf(options);
1041 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1042 let mut out = Vec::new();
1043 w.finish_into(refs.root, &mut out)
1044 .expect("finish_into succeeds");
1045 assert_eq!(out, bytes, "options {options:?}");
1046 }
1047 }
1048
1049 #[test]
1050 fn finish_into_with_matches_finish() {
1051 for options in [table_options(), stream_options(), objstm_options()] {
1052 let (bytes, _) = minimal_pdf(options);
1053 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1054 let sink = pdfboss_core::block_on(w.finish_into_with(refs.root, Vec::new()))
1055 .expect("finish_into_with succeeds");
1056 assert_eq!(sink, bytes, "options {options:?}");
1057 }
1058 }
1059
1060 struct Recording {
1063 chunks: Vec<Vec<u8>>,
1064 }
1065
1066 impl crate::sink::AsyncByteSink for Recording {
1067 fn write_all<'a>(
1068 &'a mut self,
1069 buf: &'a [u8],
1070 ) -> pdfboss_core::source::BoxFuture<'a, Result<()>> {
1071 self.chunks.push(buf.to_vec());
1072 Box::pin(std::future::ready(Ok(())))
1073 }
1074 }
1075
1076 #[test]
1080 fn emission_arrives_in_bounded_chunks() {
1081 for options in [table_options(), stream_options(), objstm_options()] {
1082 let (bytes, _) = minimal_pdf(options);
1083 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1084 let sink = pdfboss_core::block_on(
1085 w.finish_into_with(refs.root, Recording { chunks: Vec::new() }),
1086 )
1087 .expect("finish_into_with succeeds");
1088 assert_eq!(sink.chunks.concat(), bytes, "options {options:?}");
1089 assert!(
1090 sink.chunks.len() > 3,
1091 "options {options:?}: emission must arrive in many chunks, got {}",
1092 sink.chunks.len()
1093 );
1094 assert!(
1095 sink.chunks.iter().all(|chunk| chunk.len() < bytes.len()),
1096 "options {options:?}: no chunk may be the whole file"
1097 );
1098 }
1099 }
1100
1101 #[test]
1105 fn finish_into_with_over_an_owned_sink_is_spawnable() {
1106 fn assert_send_static<F: std::future::Future + Send + 'static>(_: &F) {}
1107
1108 let (w, refs) = build(stream_options(), Dict::new(), CONTENT.to_vec(), false);
1109 let future = w.finish_into_with(refs.root, Vec::new());
1110 assert_send_static(&future);
1111 let bytes = pdfboss_core::block_on(future).expect("emission succeeds");
1112 assert!(bytes.ends_with(b"%%EOF"));
1113 }
1114
1115 #[test]
1118 fn finish_into_with_reports_unfilled_reserves() {
1119 let mut w = Writer::new(table_options());
1120 let root = w.put(Object::Dict(Dict::new()));
1121 let reserved = w.reserve();
1122 let sink = Recording { chunks: Vec::new() };
1123 match pdfboss_core::block_on(w.finish_into_with(root, sink)) {
1124 Err(Error::Unfilled(seen)) => assert_eq!(seen, reserved),
1125 other => panic!("expected Unfilled, got {:?}", other.map(|s| s.chunks.len())),
1126 }
1127 }
1128}