Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/api/pdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import { serializeOperators } from "#src/drawing/serialize";
import type { EmbeddedFont, EmbedFontOptions } from "#src/fonts/embedded-font";
import { formatPdfDate, parsePdfDate } from "#src/helpers/format";
import { min } from "#src/helpers/math";
import { resolvePageSize } from "#src/helpers/page-size";
import { checkIncrementalSaveBlocker, type IncrementalSaveBlocker } from "#src/helpers/save-utils";
import { isJpeg, parseJpegHeader } from "#src/images/jpeg";
Expand Down Expand Up @@ -385,7 +386,7 @@ export class PDF {

try {
// Find the first object (lowest object number)
const firstObjNum = Math.min(...parsed.xref.keys());
const firstObjNum = min(parsed.xref.keys(), 0);

if (firstObjNum > 0) {
const firstObj = parsed.getObject(PdfRef.of(firstObjNum, 0));
Expand Down Expand Up @@ -485,7 +486,7 @@ export class PDF {
let isLinearized = false;

try {
const firstObjNum = Math.min(...parsed.xref.keys());
const firstObjNum = min(parsed.xref.keys(), 0);

if (firstObjNum > 0) {
const firstObj = parsed.getObject(PdfRef.of(firstObjNum, 0));
Expand Down
14 changes: 14 additions & 0 deletions src/document/object-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ describe("ObjectRegistry", () => {

expect(registry.nextObjectNumber).toBe(6); // max(1,5,3) + 1
});

it("handles very large xref maps without stack overflow", () => {
// Math.max(...keys) blows the call stack around ~200k args.
// Build a map with 250k entries to verify the iterative approach.
const xref = new Map<number, XRefEntry>();

for (let i = 0; i < 250_000; i++) {
xref.set(i, { type: "uncompressed", offset: i * 100, generation: 0 });
}

const registry = new ObjectRegistry(xref);

expect(registry.nextObjectNumber).toBe(250_000); // max key is 249999
});
});

describe("loaded objects", () => {
Expand Down
5 changes: 2 additions & 3 deletions src/document/object-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* tracks new objects, and assigns object numbers.
*/

import { max } from "#src/helpers/math";
import type { RefResolver } from "#src/helpers/types";
import type { PdfObject } from "#src/objects/pdf-object";
import { PdfRef } from "#src/objects/pdf-ref";
Expand Down Expand Up @@ -47,9 +48,7 @@ export class ObjectRegistry {
*/
constructor(xref?: Map<number, XRefEntry>) {
if (xref && xref.size > 0) {
// Find max object number from xref
const maxObjNum = Math.max(...xref.keys());
this._nextObjNum = maxObjNum + 1;
this._nextObjNum = max(xref.keys()) + 1;
} else {
// Start from 1 (0 is reserved for free list head)
this._nextObjNum = 1;
Expand Down
3 changes: 2 additions & 1 deletion src/fonts/font-embedder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import { CFFSubsetter } from "#src/fontbox/cff/subsetter.ts";
import { TTFSubsetter } from "#src/fontbox/ttf/subsetter.ts";
import { max } from "#src/helpers/math";
import { PdfArray } from "#src/objects/pdf-array.ts";
import { PdfDict } from "#src/objects/pdf-dict.ts";
import { PdfName } from "#src/objects/pdf-name.ts";
Expand Down Expand Up @@ -546,7 +547,7 @@ function buildFullToUnicodeCMap(program: FontProgram): Uint8Array {
*/
function buildCidToGidMapStream(oldToNewGidMap: Map<number, number>): PdfStream {
// Find the maximum old GID (CID) we need to map
const maxOldGid = Math.max(...oldToNewGidMap.keys());
const maxOldGid = max(oldToNewGidMap.keys());

// Create array of 2-byte entries (one per CID from 0 to maxOldGid)
const data = new Uint8Array((maxOldGid + 1) * 2);
Expand Down
65 changes: 65 additions & 0 deletions src/helpers/math.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";

import { max, min } from "./math";

describe("max", () => {
it("returns the largest value", () => {
expect(max([3, 1, 4, 1, 5, 9, 2, 6])).toBe(9);
});

it("works with negative values", () => {
expect(max([-10, -3, -7])).toBe(-3);
});

it("returns fallback for empty iterable", () => {
expect(max([])).toBe(0);
expect(max([], -1)).toBe(-1);
});

it("works with Map keys", () => {
const map = new Map([
[5, "a"],
[2, "b"],
[8, "c"],
]);

expect(max(map.keys())).toBe(8);
});

it("handles 250k elements without stack overflow", () => {
const arr = Array.from({ length: 250_000 }, (_, i) => i);

expect(max(arr)).toBe(249_999);
});
});

describe("min", () => {
it("returns the smallest value", () => {
expect(min([3, 1, 4, 1, 5, 9, 2, 6])).toBe(1);
});

it("works with negative values", () => {
expect(min([-10, -3, -7])).toBe(-10);
});

it("returns fallback for empty iterable", () => {
expect(min([])).toBe(0);
expect(min([], 999)).toBe(999);
});

it("works with Map keys", () => {
const map = new Map([
[5, "a"],
[2, "b"],
[8, "c"],
]);

expect(min(map.keys())).toBe(2);
});

it("handles 250k elements without stack overflow", () => {
const arr = Array.from({ length: 250_000 }, (_, i) => i);

expect(min(arr)).toBe(0);
});
});
37 changes: 37 additions & 0 deletions src/helpers/math.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Math utilities that operate on iterables.
*
* Unlike `Math.max(...arr)` / `Math.min(...arr)`, these don't spread into
* function arguments and therefore can't overflow the call stack on large
* collections.
*/

/**
* Return the largest value in an iterable, or `fallback` if empty.
*/
export function max(values: Iterable<number>, fallback = 0): number {
let result = Number.NEGATIVE_INFINITY;

for (const v of values) {
if (v > result) {
result = v;
}
}

return result === Number.NEGATIVE_INFINITY ? fallback : result;
}

/**
* Return the smallest value in an iterable, or `fallback` if empty.
*/
export function min(values: Iterable<number>, fallback = 0): number {
let result = Number.POSITIVE_INFINITY;

for (const v of values) {
if (v < result) {
result = v;
}
}

return result === Number.POSITIVE_INFINITY ? fallback : result;
}
10 changes: 6 additions & 4 deletions src/text/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* including position information for searching and highlighting.
*/

import { max, min } from "#src/helpers/math";

/**
* Rectangle in PDF coordinates (origin at bottom-left).
*/
Expand Down Expand Up @@ -128,10 +130,10 @@ export function mergeBboxes(boxes: BoundingBox[]): BoundingBox {
return { x: 0, y: 0, width: 0, height: 0 };
}

const minX = Math.min(...boxes.map(b => b.x));
const minY = Math.min(...boxes.map(b => b.y));
const maxX = Math.max(...boxes.map(b => b.x + b.width));
const maxY = Math.max(...boxes.map(b => b.y + b.height));
const minX = min(boxes.map(b => b.x));
const minY = min(boxes.map(b => b.y));
const maxX = max(boxes.map(b => b.x + b.width));
const maxY = max(boxes.map(b => b.y + b.height));

return {
x: minX,
Expand Down