@@ -10,7 +10,7 @@ export interface Entry {
1010
1111/**
1212 * Entries should be added using the [[addEntry]] and [[addDeletedEntry]]
13- * methods **in order of ascending object number** .
13+ * methods.
1414 */
1515class PDFCrossRefSection {
1616 static create = ( ) =>
@@ -37,6 +37,22 @@ class PDFCrossRefSection {
3737 }
3838
3939 addDeletedEntry ( ref : PDFRef , nextFreeObjectNumber : number ) : void {
40+ // fix the first entry if required
41+ if ( ! this . subsections . length ) {
42+ this . subsections = [
43+ [
44+ {
45+ ref : PDFRef . of ( 0 , 65535 ) ,
46+ offset : ref . objectNumber ,
47+ deleted : true ,
48+ } ,
49+ ] ,
50+ ] ;
51+ this . chunkIdx = 0 ;
52+ this . chunkLength = 1 ;
53+ } else if ( ! this . subsections [ 0 ] [ 0 ] . offset ) {
54+ this . subsections [ 0 ] [ 0 ] . offset = ref . objectNumber ;
55+ }
4056 this . append ( { ref, offset : nextFreeObjectNumber , deleted : true } ) ;
4157 }
4258
@@ -159,7 +175,35 @@ class PDFCrossRefSection {
159175 const chunk = this . subsections [ this . chunkIdx ] ;
160176 const prevEntry = chunk [ this . chunkLength - 1 ] ;
161177
162- if ( currEntry . ref . objectNumber - prevEntry . ref . objectNumber > 1 ) {
178+ if ( currEntry . ref . objectNumber - prevEntry . ref . objectNumber !== 1 ) {
179+ // the current chunk is not the right chunk, find the right one, or create a new one
180+ for ( let c = 0 ; c < this . subsections . length ; c ++ ) {
181+ const first = this . subsections [ c ] [ 0 ] ;
182+ const last = this . subsections [ c ] [ this . subsections [ c ] . length - 1 ] ;
183+ if ( first . ref . objectNumber > currEntry . ref . objectNumber ) {
184+ // goes before this subsection, or at the start of it
185+ if ( first . ref . objectNumber - currEntry . ref . objectNumber === 1 ) {
186+ // first element of subsection
187+ this . subsections [ c ] . unshift ( currEntry ) ;
188+ if ( c === this . chunkIdx ) this . chunkLength += 1 ;
189+ return ;
190+ } else {
191+ // create subsection
192+ this . subsections . splice ( c , 0 , [ currEntry ] ) ;
193+ this . chunkIdx ++ ;
194+ return ;
195+ }
196+ } else if ( last . ref . objectNumber > currEntry . ref . objectNumber ) {
197+ // goes in this subsection, find its place..
198+ const cep = this . subsections [ c ] . findIndex (
199+ ( ee ) => ee . ref . objectNumber > currEntry . ref . objectNumber ,
200+ ) ;
201+ this . subsections [ c ] . splice ( cep , 0 , currEntry ) ;
202+ if ( c === this . chunkIdx ) this . chunkLength += 1 ;
203+ }
204+ // bigger, keep looking
205+ }
206+ // if got to here, then a new subsection is required
163207 this . subsections . push ( [ currEntry ] ) ;
164208 this . chunkIdx += 1 ;
165209 this . chunkLength = 1 ;
0 commit comments