@@ -651,6 +651,14 @@ impl<'a> Obj<'a> {
651651 /// Write a primitive object.
652652 #[ inline]
653653 pub fn primitive < T : Primitive > ( self , value : T ) {
654+ // Normally, we need to separate different PDF objects by a whitespace. he key to the
655+ // optimizations applied here are explained in 7.2.3 in the PDF reference:
656+ // > The delimiter characters (, ), <, >, [, ], /, and % are special. They
657+ // > delimit syntactic entities such as arrays, names, and comments. Any of these
658+ // > delimiters terminates the entity preceding it and is not included in the entity.
659+ // Therefore, if either the previous byte is a delimiter character or the current token
660+ // starts with one, we don't need to add a whitespace for padding.
661+
654662 let ends_with_delimiter =
655663 self . buf . last ( ) . copied ( ) . is_some_and ( is_delimiter_character) ;
656664
@@ -659,6 +667,7 @@ impl<'a> Obj<'a> {
659667 }
660668
661669 value. write ( self . buf ) ;
670+
662671 if self . indirect {
663672 self . buf . extend ( b"\n endobj\n " ) ;
664673
@@ -668,6 +677,9 @@ impl<'a> Obj<'a> {
668677 }
669678 }
670679
680+ // Note: Arrays and dictionaries always start with a delimiter, so we don't need to do any case
681+ // distinction, unlike in `primitive`.
682+
671683 /// Start writing an array.
672684 #[ inline]
673685 pub fn array ( self ) -> Array < ' a > {
@@ -763,7 +775,9 @@ impl<'a> Array<'a> {
763775 } else {
764776 false
765777 } ;
778+
766779 self . len += 1 ;
780+
767781 Obj :: direct ( self . buf , self . indent , self . settings , needs_padding)
768782 }
769783
@@ -915,6 +929,8 @@ impl<'a> Dict<'a> {
915929 pub fn insert ( & mut self , key : Name ) -> Obj < ' _ > {
916930 self . len += 1 ;
917931
932+ // Keys always start with a delimiter since they are names, so we never need
933+ // padding unless `pretty` is activated.
918934 if self . settings . pretty {
919935 self . buf . push ( b'\n' ) ;
920936
@@ -924,6 +940,7 @@ impl<'a> Dict<'a> {
924940 }
925941
926942 self . buf . push_val ( key) ;
943+
927944 let needs_padding = if self . settings . pretty {
928945 self . buf . push ( b' ' ) ;
929946 false
0 commit comments