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
443 .encrypt_object(&mut container, num, 0)
444 .map_err(crate::update::core_error)?;
445 }
446 write_indirect(emit, num, &container).await?;
447 }
448
449 let mut next_num = user_count + chunks.len() as u32 + 1;
450 let mut encrypt_row = None;
451 if let Some(dict) = encrypt_dict {
452 let offset = field_offset(emit.count)?;
453 write_indirect(emit, next_num, &Object::Dict(dict.clone())).await?;
454 encrypt_row = Some((
455 ObjRef {
456 num: next_num,
457 gen: 0,
458 },
459 offset,
460 ));
461 next_num += 1;
462 }
463 let xref_num = next_num;
464 let id = emit.file_id();
465 let xref_off = field_offset(emit.count)?;
466
467 let mut data = Vec::with_capacity(7 * (xref_num as usize + 1));
468 push_row(&mut data, 0, 0, 65535);
469 for row in rows {
470 match row {
471 Row::Top(offset) => push_row(&mut data, 1, offset, 0),
472 Row::Packed { container, index } => push_row(&mut data, 2, container, index),
473 }
474 }
475 for offset in container_offsets {
476 push_row(&mut data, 1, offset, 0);
477 }
478 if let Some((_, offset)) = encrypt_row {
479 push_row(&mut data, 1, offset, 0);
480 }
481 push_row(&mut data, 1, xref_off, 0);
482
483 let mut dict = trailer_dict(xref_num as i64 + 1, root, info, id);
484 if let Some((r, _)) = encrypt_row {
485 dict.insert(literal("Encrypt"), Object::Ref(r));
486 }
487 dict.insert(literal("Type"), Object::Name(literal("XRef")));
488 dict.insert(
489 literal("W"),
490 Object::Array(vec![Object::Int(1), Object::Int(4), Object::Int(2)]),
491 );
492 let data = compress_into(&mut dict, data, options.compress);
493 write_indirect(emit, xref_num, &Object::Stream(Stream { dict, data })).await?;
494 emit.write(format!("startxref\n{xref_off}\n%%EOF").as_bytes())
495 .await
496}
497
498fn write_header(out: &mut Vec<u8>, version: (u8, u8)) {
500 out.extend_from_slice(format!("%PDF-{}.{}\n", version.0, version.1).as_bytes());
501 out.extend_from_slice(b"%\xE2\xE3\xCF\xD3\n");
502}
503
504async fn write_indirect<S: AsyncByteSink>(
510 emit: &mut Emit<S>,
511 num: u32,
512 obj: &Object,
513) -> Result<()> {
514 let mut lead = format!("{num} 0 obj\n").into_bytes();
515 match obj {
516 Object::Stream(s) => {
517 let mut dict = s.dict.clone();
518 dict.insert(literal("Length"), Object::Int(s.data.len() as i64));
519 serialize_dict(&dict, &mut lead)?;
520 lead.extend_from_slice(b"\nstream\n");
521 emit.write(&lead).await?;
522 emit.write(&s.data).await?;
523 emit.write(b"\nendstream\nendobj\n").await
524 }
525 direct => {
526 serialize_object(direct, &mut lead)?;
527 lead.extend_from_slice(b"\nendobj\n");
528 emit.write(&lead).await
529 }
530 }
531}
532
533async fn write_indirect_maybe_encrypted<S: AsyncByteSink>(
539 emit: &mut Emit<S>,
540 num: u32,
541 obj: &Object,
542 encryptor: Option<&mut Encryptor>,
543) -> Result<()> {
544 match encryptor {
545 Some(encryptor) => {
546 let mut obj = obj.clone();
547 encryptor
548 .encrypt_object(&mut obj, num, 0)
549 .map_err(crate::update::core_error)?;
550 write_indirect(emit, num, &obj).await
551 }
552 None => write_indirect(emit, num, obj).await,
553 }
554}
555
556fn build_objstm(pairs: &[(u32, &Object)], compress: bool) -> Result<Stream> {
560 let mut header = Vec::new();
561 let mut payload = Vec::new();
562 for (num, body) in pairs {
563 header.extend_from_slice(format!("{num} {} ", payload.len()).as_bytes());
564 serialize_object(body, &mut payload)?;
565 payload.push(b' ');
566 }
567 let mut dict = Dict::new();
568 dict.insert(literal("Type"), Object::Name(literal("ObjStm")));
569 dict.insert(literal("N"), Object::Int(pairs.len() as i64));
570 dict.insert(literal("First"), Object::Int(header.len() as i64));
571 header.extend_from_slice(&payload);
572 let data = compress_into(&mut dict, header, compress);
573 Ok(Stream { dict, data })
574}
575
576fn trailer_dict(size: i64, root: ObjRef, info: Option<ObjRef>, id: Object) -> Dict {
581 let mut trailer = Dict::new();
582 trailer.insert(literal("Size"), Object::Int(size));
583 trailer.insert(literal("Root"), Object::Ref(root));
584 if let Some(info) = info {
585 trailer.insert(literal("Info"), Object::Ref(info));
586 }
587 trailer.insert(literal("ID"), id);
588 trailer
589}
590
591fn compress_into(dict: &mut Dict, data: Vec<u8>, compress: bool) -> Vec<u8> {
595 if !compress || dict.get("Filter").is_some() {
596 return data;
597 }
598 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
599 let Ok(compressed) = encoder.write_all(&data).and_then(|()| encoder.finish()) else {
600 return data;
601 };
602 dict.insert(literal("Filter"), Object::Name(literal("FlateDecode")));
603 compressed
604}
605
606fn push_row(rows: &mut Vec<u8>, kind: u8, second: u32, third: u16) {
608 rows.push(kind);
609 rows.extend_from_slice(&second.to_be_bytes());
610 rows.extend_from_slice(&third.to_be_bytes());
611}
612
613fn field_offset(position: usize) -> Result<u32> {
615 u32::try_from(position)
616 .map_err(|_| Error::Other("file offset exceeds the 4-byte xref field".to_string()))
617}
618
619fn table_offset(position: usize) -> Result<usize> {
623 if position as u64 <= 9_999_999_999 {
624 return Ok(position);
625 }
626 Err(Error::Other(
627 "file offset exceeds the 10-digit xref table field".to_string(),
628 ))
629}
630
631fn literal(text: &str) -> Name {
633 Name(text.to_string())
634}
635
636#[cfg(test)]
637mod tests {
638 use pdfboss_core::xref::load_xref;
639 use pdfboss_core::{Dict, Document, Name, ObjRef, Object, Stream};
640
641 use super::*;
642 use crate::error::Error;
643
644 const CONTENT: &[u8] = b"BT /F1 12 Tf 72 720 Td (Hello, writer) Tj ET";
645
646 fn name(text: &str) -> Name {
647 Name(text.to_string())
648 }
649
650 fn table_options() -> WriteOptions {
651 WriteOptions {
652 xref: XrefStyle::Table,
653 compress: false,
654 object_streams: false,
655 version: (1, 7),
656 }
657 }
658
659 fn stream_options() -> WriteOptions {
660 WriteOptions {
661 xref: XrefStyle::Stream,
662 compress: false,
663 object_streams: false,
664 version: (1, 5),
665 }
666 }
667
668 fn objstm_options() -> WriteOptions {
669 WriteOptions {
670 xref: XrefStyle::Stream,
671 compress: true,
672 object_streams: true,
673 version: (1, 7),
674 }
675 }
676
677 struct Refs {
678 content: ObjRef,
679 pages: ObjRef,
680 page: ObjRef,
681 root: ObjRef,
682 }
683
684 fn page_dict(pages: ObjRef, content: ObjRef) -> Dict {
685 let mut page = Dict::new();
686 page.insert(name("Type"), Object::Name(name("Page")));
687 page.insert(name("Parent"), Object::Ref(pages));
688 page.insert(
689 name("MediaBox"),
690 Object::Array(vec![
691 Object::Int(0),
692 Object::Int(0),
693 Object::Int(612),
694 Object::Int(792),
695 ]),
696 );
697 page.insert(name("Contents"), Object::Ref(content));
698 page
699 }
700
701 fn build(
704 options: WriteOptions,
705 content_dict: Dict,
706 content_data: Vec<u8>,
707 raw: bool,
708 ) -> (Writer, Refs) {
709 let mut w = Writer::new(options);
710 let content = if raw {
711 w.put_stream_raw(content_dict, content_data)
712 } else {
713 w.put_stream(content_dict, content_data)
714 };
715 let pages = w.reserve();
716 let page = w.put(Object::Dict(page_dict(pages, content)));
717 let mut tree = Dict::new();
718 tree.insert(name("Type"), Object::Name(name("Pages")));
719 tree.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
720 tree.insert(name("Count"), Object::Int(1));
721 w.fill(pages, Object::Dict(tree))
722 .expect("pages slot is fillable");
723 let mut catalog = Dict::new();
724 catalog.insert(name("Type"), Object::Name(name("Catalog")));
725 catalog.insert(name("Pages"), Object::Ref(pages));
726 let root = w.put(Object::Dict(catalog));
727 (
728 w,
729 Refs {
730 content,
731 pages,
732 page,
733 root,
734 },
735 )
736 }
737
738 fn skeleton(
740 options: WriteOptions,
741 content_dict: Dict,
742 content_data: Vec<u8>,
743 raw: bool,
744 ) -> (Vec<u8>, Refs) {
745 let (w, refs) = build(options, content_dict, content_data, raw);
746 let bytes = w.finish(refs.root).expect("minimal document finishes");
747 (bytes, refs)
748 }
749
750 fn minimal_pdf(options: WriteOptions) -> (Vec<u8>, Refs) {
751 skeleton(options, Dict::new(), CONTENT.to_vec(), false)
752 }
753
754 fn assert_minimal_loads(bytes: &[u8], refs: &Refs) -> Document {
755 let doc = Document::load(bytes.to_vec()).expect("document loads");
756 assert_eq!(doc.page_count(), 1);
757 let page = doc.page(0).expect("page 0 exists");
758 assert_eq!(page.object_ref(), Some(refs.page));
759 assert_eq!(page.dict(), &page_dict(refs.pages, refs.content));
760 assert_eq!(page.content(&doc).expect("content decodes"), CONTENT);
761 doc
762 }
763
764 fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
765 haystack
766 .windows(needle.len())
767 .filter(|window| *window == needle)
768 .count()
769 }
770
771 #[test]
773 fn table_mode_minimal_document_loads() {
774 let (bytes, refs) = minimal_pdf(table_options());
775 assert!(bytes.starts_with(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n"));
776 assert!(bytes.ends_with(b"%%EOF"));
777 assert_eq!(count_occurrences(&bytes, b"xref\n0 5\n"), 1);
778 assert_eq!(count_occurrences(&bytes, b"0000000000 65535 f\r\n"), 1);
779 assert_eq!(count_occurrences(&bytes, b"trailer\n"), 1);
780 assert_minimal_loads(&bytes, &refs);
781 }
782
783 #[test]
784 fn table_mode_ignores_object_streams_option() {
785 let options = WriteOptions {
786 object_streams: true,
787 ..table_options()
788 };
789 let (bytes, refs) = minimal_pdf(options);
790 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 0);
791 assert_minimal_loads(&bytes, &refs);
792 }
793
794 #[test]
795 fn stream_mode_minimal_document_loads() {
796 let (bytes, refs) = minimal_pdf(stream_options());
797 assert!(bytes.starts_with(b"%PDF-1.5\n%\xE2\xE3\xCF\xD3\n"));
798 assert!(bytes.ends_with(b"%%EOF"));
799 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 0);
800 assert_eq!(count_occurrences(&bytes, b"/XRef"), 1);
801 assert_minimal_loads(&bytes, &refs);
802 }
803
804 #[test]
805 fn object_streams_pack_and_resolve() {
806 let (bytes, refs) = minimal_pdf(objstm_options());
807 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 1);
808 let doc = assert_minimal_loads(&bytes, &refs);
809 let root = doc
810 .resolve(&Object::Ref(refs.root))
811 .expect("catalog resolves");
812 let catalog = root.as_dict().expect("catalog is a dictionary");
813 assert_eq!(catalog.get_name("Type"), Some(&name("Catalog")));
814 assert_eq!(catalog.get_ref("Pages"), Some(refs.pages));
815 }
816
817 #[test]
818 fn object_streams_chunk_at_two_hundred() {
819 let options = WriteOptions {
820 compress: false,
821 ..objstm_options()
822 };
823 let mut w = Writer::new(options);
824 let content = w.put_stream(Dict::new(), CONTENT.to_vec());
825 let int_refs: Vec<ObjRef> = (0..205).map(|i| w.put(Object::Int(i))).collect();
826 let pages = w.reserve();
827 let page = w.put(Object::Dict(page_dict(pages, content)));
828 let mut tree = Dict::new();
829 tree.insert(name("Type"), Object::Name(name("Pages")));
830 tree.insert(name("Kids"), Object::Array(vec![Object::Ref(page)]));
831 tree.insert(name("Count"), Object::Int(1));
832 w.fill(pages, Object::Dict(tree))
833 .expect("pages slot is fillable");
834 let mut catalog = Dict::new();
835 catalog.insert(name("Type"), Object::Name(name("Catalog")));
836 catalog.insert(name("Pages"), Object::Ref(pages));
837 let root = w.put(Object::Dict(catalog));
838 let bytes = w.finish(root).expect("document finishes");
839 assert_eq!(count_occurrences(&bytes, b"/ObjStm"), 2);
840 let doc = Document::load(bytes).expect("document loads");
841 assert_eq!(
842 doc.resolve(&Object::Ref(int_refs[0])).expect("resolves"),
843 Object::Int(0)
844 );
845 assert_eq!(
846 doc.resolve(&Object::Ref(int_refs[204])).expect("resolves"),
847 Object::Int(204)
848 );
849 assert_eq!(doc.page_count(), 1);
850 }
851
852 #[test]
853 fn refs_ascend_from_one_in_call_order() {
854 let mut w = Writer::new(table_options());
855 assert_eq!(w.put(Object::Null), ObjRef { num: 1, gen: 0 });
856 assert_eq!(w.reserve(), ObjRef { num: 2, gen: 0 });
857 assert_eq!(
858 w.put_stream(Dict::new(), Vec::new()),
859 ObjRef { num: 3, gen: 0 }
860 );
861 assert_eq!(
862 w.put_stream_raw(Dict::new(), Vec::new()),
863 ObjRef { num: 4, gen: 0 }
864 );
865 }
866
867 #[test]
868 fn fill_twice_reports_already_filled() {
869 let mut w = Writer::new(table_options());
870 let r = w.reserve();
871 w.fill(r, Object::Int(1)).expect("first fill lands");
872 match w.fill(r, Object::Int(2)) {
873 Err(Error::AlreadyFilled(seen)) => assert_eq!(seen, r),
874 other => panic!("expected AlreadyFilled, got {other:?}"),
875 }
876 }
877
878 #[test]
879 fn fill_rejects_foreign_and_wrong_generation_refs() {
880 let mut w = Writer::new(table_options());
881 let r = w.reserve();
882 let unallocated = w.fill(ObjRef { num: 99, gen: 0 }, Object::Null);
883 assert!(matches!(unallocated, Err(Error::Other(msg)) if msg.contains("99")));
884 let zero = w.fill(ObjRef { num: 0, gen: 0 }, Object::Null);
885 assert!(matches!(zero, Err(Error::Other(msg)) if !msg.is_empty()));
886 let wrong_gen = w.fill(ObjRef { num: r.num, gen: 1 }, Object::Null);
887 assert!(matches!(wrong_gen, Err(Error::Other(msg)) if msg.contains("generation")));
888 }
889
890 #[test]
891 fn finish_with_unfilled_reserve_reports_the_ref() {
892 let mut w = Writer::new(table_options());
893 let root = w.put(Object::Dict(Dict::new()));
894 let reserved = w.reserve();
895 match w.finish(root) {
896 Err(Error::Unfilled(seen)) => assert_eq!(seen, reserved),
897 other => panic!("expected Unfilled, got {other:?}"),
898 }
899 }
900
901 #[test]
902 fn nested_stream_surfaces_from_finish() {
903 for options in [table_options(), objstm_options()] {
904 let mut w = Writer::new(options);
905 let root = w.put(Object::Array(vec![Object::Stream(Stream {
906 dict: Dict::new(),
907 data: b"x".to_vec(),
908 })]));
909 assert!(matches!(w.finish(root), Err(Error::NestedStream)));
910 }
911 }
912
913 #[test]
914 fn compressed_stream_round_trips() {
915 let options = WriteOptions {
916 compress: true,
917 ..table_options()
918 };
919 let data: Vec<u8> = b"q 0.5 0 0 0.5 36 36 cm Q\n".repeat(40);
920 let (bytes, refs) = skeleton(options, Dict::new(), data.clone(), false);
921 let doc = Document::load(bytes).expect("document loads");
922 let resolved = doc
923 .resolve(&Object::Ref(refs.content))
924 .expect("content stream resolves");
925 let stream = resolved.as_stream().expect("content is a stream");
926 assert_eq!(stream.dict.get_name("Filter"), Some(&name("FlateDecode")));
927 assert_eq!(
928 stream.dict.get_int("Length"),
929 Some(stream.data.len() as i64)
930 );
931 assert!(stream.data.len() < data.len());
932 assert_eq!(doc.stream_data(stream).expect("stream decodes"), data);
933 }
934
935 #[test]
936 fn preset_filter_is_not_recompressed() {
937 let options = WriteOptions {
938 compress: true,
939 ..table_options()
940 };
941 let payload = b"Hello writer";
942 let encoded: Vec<u8> = payload
943 .iter()
944 .flat_map(|b| format!("{b:02X}").into_bytes())
945 .chain(*b">")
946 .collect();
947 let mut dict = Dict::new();
948 dict.insert(name("Filter"), Object::Name(name("ASCIIHexDecode")));
949 let (bytes, refs) = skeleton(options, dict, encoded.clone(), false);
950 let doc = Document::load(bytes).expect("document loads");
951 let resolved = doc
952 .resolve(&Object::Ref(refs.content))
953 .expect("content stream resolves");
954 let stream = resolved.as_stream().expect("content is a stream");
955 assert_eq!(stream.data, encoded, "pre-filtered data stays untouched");
956 assert_eq!(
957 stream.dict.get_name("Filter"),
958 Some(&name("ASCIIHexDecode"))
959 );
960 assert_eq!(doc.stream_data(stream).expect("stream decodes"), payload);
961 }
962
963 #[test]
964 fn put_stream_raw_never_compresses() {
965 let options = WriteOptions {
966 compress: true,
967 ..table_options()
968 };
969 let (bytes, refs) = skeleton(options, Dict::new(), CONTENT.to_vec(), true);
970 let doc = Document::load(bytes).expect("document loads");
971 let resolved = doc
972 .resolve(&Object::Ref(refs.content))
973 .expect("content stream resolves");
974 let stream = resolved.as_stream().expect("content is a stream");
975 assert_eq!(stream.data, CONTENT);
976 assert!(stream.dict.get("Filter").is_none());
977 assert_eq!(stream.dict.get_int("Length"), Some(CONTENT.len() as i64));
978 }
979
980 #[test]
981 fn table_offsets_past_ten_digits_are_rejected() {
982 assert_eq!(table_offset(9_999_999_999).ok(), Some(9_999_999_999));
983 assert!(table_offset(10_000_000_000).is_err());
984 }
985
986 #[test]
988 fn id_derives_from_the_emitted_content() {
989 let (a, refs) = minimal_pdf(table_options());
990 assert_eq!(refs.root.gen, 0);
991 let (b, other_refs) = skeleton(
992 table_options(),
993 Dict::new(),
994 b"BT /F1 12 Tf 72 720 Td (Hello, other) Tj ET".to_vec(),
995 false,
996 );
997 assert_eq!(other_refs.root.gen, 0);
998 let id_of = |bytes: &[u8]| {
999 let xref = load_xref(bytes).expect("xref loads");
1000 let id = xref.trailer.get_array("ID").expect("/ID array present");
1001 id[0]
1002 .as_str_bytes()
1003 .expect("/ID entry is a string")
1004 .to_vec()
1005 };
1006 assert_ne!(
1007 id_of(&a),
1008 id_of(&b),
1009 "/ID must depend on the emitted content"
1010 );
1011 }
1012
1013 #[test]
1015 fn id_pair_is_present_and_identical() {
1016 for options in [table_options(), stream_options(), objstm_options()] {
1017 let (bytes, refs) = minimal_pdf(options);
1018 assert_eq!(refs.root.gen, 0);
1019 let xref = load_xref(&bytes).expect("xref loads");
1020 let id = xref.trailer.get_array("ID").expect("/ID array present");
1021 assert_eq!(id.len(), 2);
1022 let first = id[0].as_str_bytes().expect("/ID entry is a string");
1023 let second = id[1].as_str_bytes().expect("/ID entry is a string");
1024 assert_eq!(first.len(), 16);
1025 assert_eq!(first, second);
1026 }
1027 }
1028
1029 #[test]
1030 fn output_is_deterministic() {
1031 for options in [table_options(), stream_options(), objstm_options()] {
1032 let (first, refs) = minimal_pdf(options);
1033 let (second, again) = minimal_pdf(options);
1034 assert_eq!(refs.content, again.content);
1035 assert_eq!(first, second, "options {options:?} must be deterministic");
1036 }
1037 }
1038
1039 #[test]
1040 fn finish_into_matches_finish() {
1041 for options in [table_options(), stream_options(), objstm_options()] {
1042 let (bytes, _) = minimal_pdf(options);
1043 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1044 let mut out = Vec::new();
1045 w.finish_into(refs.root, &mut out)
1046 .expect("finish_into succeeds");
1047 assert_eq!(out, bytes, "options {options:?}");
1048 }
1049 }
1050
1051 #[test]
1052 fn finish_into_with_matches_finish() {
1053 for options in [table_options(), stream_options(), objstm_options()] {
1054 let (bytes, _) = minimal_pdf(options);
1055 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1056 let sink = pdfboss_core::block_on(w.finish_into_with(refs.root, Vec::new()))
1057 .expect("finish_into_with succeeds");
1058 assert_eq!(sink, bytes, "options {options:?}");
1059 }
1060 }
1061
1062 struct Recording {
1065 chunks: Vec<Vec<u8>>,
1066 }
1067
1068 impl crate::sink::AsyncByteSink for Recording {
1069 fn write_all<'a>(
1070 &'a mut self,
1071 buf: &'a [u8],
1072 ) -> pdfboss_core::source::BoxFuture<'a, Result<()>> {
1073 self.chunks.push(buf.to_vec());
1074 Box::pin(std::future::ready(Ok(())))
1075 }
1076 }
1077
1078 #[test]
1082 fn emission_arrives_in_bounded_chunks() {
1083 for options in [table_options(), stream_options(), objstm_options()] {
1084 let (bytes, _) = minimal_pdf(options);
1085 let (w, refs) = build(options, Dict::new(), CONTENT.to_vec(), false);
1086 let sink = pdfboss_core::block_on(
1087 w.finish_into_with(refs.root, Recording { chunks: Vec::new() }),
1088 )
1089 .expect("finish_into_with succeeds");
1090 assert_eq!(sink.chunks.concat(), bytes, "options {options:?}");
1091 assert!(
1092 sink.chunks.len() > 3,
1093 "options {options:?}: emission must arrive in many chunks, got {}",
1094 sink.chunks.len()
1095 );
1096 assert!(
1097 sink.chunks.iter().all(|chunk| chunk.len() < bytes.len()),
1098 "options {options:?}: no chunk may be the whole file"
1099 );
1100 }
1101 }
1102
1103 #[test]
1107 fn finish_into_with_over_an_owned_sink_is_spawnable() {
1108 fn assert_send_static<F: std::future::Future + Send + 'static>(_: &F) {}
1109
1110 let (w, refs) = build(stream_options(), Dict::new(), CONTENT.to_vec(), false);
1111 let future = w.finish_into_with(refs.root, Vec::new());
1112 assert_send_static(&future);
1113 let bytes = pdfboss_core::block_on(future).expect("emission succeeds");
1114 assert!(bytes.ends_with(b"%%EOF"));
1115 }
1116
1117 #[test]
1120 fn finish_into_with_reports_unfilled_reserves() {
1121 let mut w = Writer::new(table_options());
1122 let root = w.put(Object::Dict(Dict::new()));
1123 let reserved = w.reserve();
1124 let sink = Recording { chunks: Vec::new() };
1125 match pdfboss_core::block_on(w.finish_into_with(root, sink)) {
1126 Err(Error::Unfilled(seen)) => assert_eq!(seen, reserved),
1127 other => panic!("expected Unfilled, got {:?}", other.map(|s| s.chunks.len())),
1128 }
1129 }
1130}