fix(font-metrics): evict oldest advance-cache entry instead of clearing (#281)

Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
ANIRUDDHA ADAK
2026-09-10 17:48:28 +08:00
committed by GitHub
co-authored by Aniruddha Adak
parent 150246dc32
commit 1179ea77ec
2 changed files with 49 additions and 2 deletions
+15 -1
View File
@@ -143,6 +143,20 @@ const styleTokensOf = (style: AdvanceStyle): string[] => [
const faceCache = new Map<string, ParsedFace | null>()
const FACE_CACHE_MAX = 8
/**
* Make room for one entry, evicting the least-recently-inserted one.
* Map preserves insertion order, so the first key is the oldest. Evicting
* one entry (instead of clearing the whole cache) keeps the other parsed
* faces hot when a document cycles through more families than fit.
*/
export function evictOldestEntry<K, V>(cache: Map<K, V>, max: number): void {
while (cache.size >= max) {
const oldest = cache.keys().next()
if (oldest.done) return
cache.delete(oldest.value)
}
}
function faceAdvances(face: FaceRef): ParsedFace | null {
const key = `${face.path}#${face.offset}`
const hit = faceCache.get(key)
@@ -158,7 +172,7 @@ function faceAdvances(face: FaceRef): ParsedFace | null {
} catch {
return null // transient open/read failure: not cached, retried next call
}
if (faceCache.size >= FACE_CACHE_MAX) faceCache.clear()
evictOldestEntry(faceCache, FACE_CACHE_MAX)
faceCache.set(key, parsed)
return parsed
}
+34 -1
View File
@@ -1,5 +1,6 @@
import { existsSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { evictOldestEntry } from '../src/advance'
import { advanceWidths, isFamilyInstalled } from '../src/index'
const darwin = process.platform === 'darwin'
@@ -42,8 +43,40 @@ describe('advanceWidths', () => {
it('marks unmapped codepoints as NaN instead of guessing', () => {
if (!hasHelvetica) return
const w = advanceWidths('Helvetica', '\u{10FFF0}x', 12)!
const w = advanceWidths('Helvetica', '￿x', 12)!
expect(Number.isNaN(w[0]!)).toBe(true)
expect(w[1]!).toBeGreaterThan(0)
})
})
describe('evictOldestEntry', () => {
it('is a no-op below capacity', () => {
const cache = new Map([
['a', 1],
['b', 2],
])
evictOldestEntry(cache, 8)
expect([...cache.keys()]).toEqual(['a', 'b'])
})
it('evicts only the oldest entry at capacity', () => {
const cache = new Map([
['a', 1],
['b', 2],
['c', 3],
])
evictOldestEntry(cache, 3)
expect([...cache.keys()]).toEqual(['b', 'c'])
})
it('evicts repeatedly until under max', () => {
const cache = new Map([
['a', 1],
['b', 2],
['c', 3],
['d', 4],
])
evictOldestEntry(cache, 2)
expect([...cache.keys()]).toEqual(['c', 'd'])
})
})