Reduce unnecessary type conversion in writeStream

Currently we're unnecessarily converting data between strings and typed-arrays, when dealing with compressible data, in the `writeStream` function.
Note how we're *first* getting a string-representation of the stream, which involves converting the underlying typed-array into a string, only to immediately convert this back into a typed-array. This seems completely unnecessary, and is easy enough to avoid, and we'll now only do a *single* type-conversion in this function.
This commit is contained in:
Jonas Jenwald 2023-10-18 15:30:31 +02:00
parent 22d6d95f03
commit 25a1a9d28f

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { bytesToString, info, stringToBytes, warn } from "../shared/util.js"; import { bytesToString, info, warn } from "../shared/util.js";
import { Dict, isName, Name, Ref } from "./primitives.js"; import { Dict, isName, Name, Ref } from "./primitives.js";
import { import {
escapePDFName, escapePDFName,
@ -48,7 +48,7 @@ async function writeDict(dict, buffer, transform) {
} }
async function writeStream(stream, buffer, transform) { async function writeStream(stream, buffer, transform) {
let string = stream.getString(); let bytes = stream.getBytes();
const { dict } = stream; const { dict } = stream;
const [filter, params] = await Promise.all([ const [filter, params] = await Promise.all([
@ -67,18 +67,17 @@ async function writeStream(stream, buffer, transform) {
if ( if (
typeof CompressionStream !== "undefined" && typeof CompressionStream !== "undefined" &&
(string.length >= MIN_LENGTH_FOR_COMPRESSING || isFilterZeroFlateDecode) (bytes.length >= MIN_LENGTH_FOR_COMPRESSING || isFilterZeroFlateDecode)
) { ) {
try { try {
const byteArray = stringToBytes(string);
const cs = new CompressionStream("deflate"); const cs = new CompressionStream("deflate");
const writer = cs.writable.getWriter(); const writer = cs.writable.getWriter();
writer.write(byteArray); writer.write(bytes);
writer.close(); writer.close();
// Response::text doesn't return the correct data. // Response::text doesn't return the correct data.
const buf = await new Response(cs.readable).arrayBuffer(); const buf = await new Response(cs.readable).arrayBuffer();
string = bytesToString(new Uint8Array(buf)); bytes = new Uint8Array(buf);
let newFilter, newParams; let newFilter, newParams;
if (!filter) { if (!filter) {
@ -104,6 +103,7 @@ async function writeStream(stream, buffer, transform) {
} }
} }
let string = bytesToString(bytes);
if (transform) { if (transform) {
string = transform.encryptString(string); string = transform.encryptString(string);
} }