From 2a5baefff8579cb3749ce4d0f921d568d4b77a10 Mon Sep 17 00:00:00 2001 From: Abi Hafshin Date: Sat, 22 Jun 2024 18:29:05 +0700 Subject: [PATCH] feat: Add LRUCache for font layout caching --- lib/font/embedded.js | 9 ++++++--- package.json | 3 ++- yarn.lock | 5 +++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/font/embedded.js b/lib/font/embedded.js index 0eddfe0e..b2abe410 100644 --- a/lib/font/embedded.js +++ b/lib/font/embedded.js @@ -1,3 +1,4 @@ +import { LRUCache } from 'lru-cache'; import PDFFont from '../font'; const toHex = function(num) { @@ -24,7 +25,9 @@ class EmbeddedFont extends PDFFont { this.bbox = this.font.bbox; if (document.options.fontLayoutCache !== false) { - this.layoutCache = Object.create(null); + this.layoutCache = new LRUCache({ + max: document.options.fontLayoutMaxCacheSize || 1000 + }); } } @@ -49,12 +52,12 @@ class EmbeddedFont extends PDFFont { return this.layoutRun(text); } let cached; - if ((cached = this.layoutCache[text])) { + if ((cached = this.layoutCache.get(text))) { return cached; } const run = this.layoutRun(text); - this.layoutCache[text] = run; + this.layoutCache.set(text, run); return run; } diff --git a/package.json b/package.json index 0bbbf212..0406bf35 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "fontkit": "^1.8.1", "jpeg-exif": "^1.1.4", "linebreak": "^1.0.2", + "lru-cache": "^10.2.2", "png-js": "^1.0.0" }, "scripts": { @@ -89,4 +90,4 @@ "/tests/unit/setupTests.js" ] } -} \ No newline at end of file +} diff --git a/yarn.lock b/yarn.lock index 273331f5..9948baba 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5016,6 +5016,11 @@ longest@^1.0.1: resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" integrity sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc= +lru-cache@^10.2.2: + version "10.2.2" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.2.2.tgz#48206bc114c1252940c41b25b41af5b545aca878" + integrity sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ== + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920"