Skip to content

Commit b3cd042

Browse files
committed
Prevent unnecessary data copy in ChunkedStream.prototype.onReceiveData
This method is only invoked via `ChunkedStreamManager.prototype.sendRequest`, which currently returns data in `Uint8Array` format (since it potentially combines multiple `ArrayBuffer`s). Hence we end up doing a short-lived, but still completely unnecessary, data copy[1] in `ChunkedStream.prototype.onReceiveData` when handling range requests. In practice this is unlikely to be a big problem by default, given that streaming is used and the (low) value of the `rangeChunkSize` API-option. (However, in custom PDF.js deployments it might affect things more.) Given that no data copy is better than a short lived one, let's fix this small oversight and add non-production `assert`s to keep it working as intended. This way we also improve consistency, since all other streaming and range request methods (see e.g. `BasePDFStream` and related code) only return `ArrayBuffer` data. --- [1] Remember that `new Uint8Array(arrayBuffer)` only creates a view of the underlying `arrayBuffer`, whereas `new Uint8Array(typedArray)` actually creates a copy of the `typedArray`.
1 parent 01deb08 commit b3cd042

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

src/core/chunked_stream.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@ class ChunkedStream extends Stream {
7070
throw new Error(`Bad end offset: ${end}`);
7171
}
7272

73+
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
74+
assert(
75+
chunk instanceof ArrayBuffer,
76+
"onReceiveData - expected an ArrayBuffer."
77+
);
78+
}
7379
this.bytes.set(new Uint8Array(chunk), begin);
7480
const beginChunk = Math.floor(begin / chunkSize);
7581
const endChunk = Math.floor((end - 1) / chunkSize) + 1;
@@ -85,6 +91,12 @@ class ChunkedStream extends Stream {
8591
let position = this.progressiveDataLength;
8692
const beginChunk = Math.floor(position / this.chunkSize);
8793

94+
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
95+
assert(
96+
data instanceof ArrayBuffer,
97+
"onReceiveProgressiveData - expected an ArrayBuffer."
98+
);
99+
}
88100
this.bytes.set(new Uint8Array(data), position);
89101
position += data.byteLength;
90102
this.progressiveDataLength = position;
@@ -310,7 +322,7 @@ class ChunkedStreamManager {
310322
if (this.aborted) {
311323
return; // Ignoring any data after abort.
312324
}
313-
this.onReceiveData({ chunk: data, begin });
325+
this.onReceiveData({ chunk: data.buffer, begin });
314326
});
315327
}
316328

0 commit comments

Comments
 (0)