Add a private FontInfo helper method for reading array-data (PR 20197 follow-up)

Currently the `bbox`, `fontMatrix`, and `defaultVMetrics` getters duplicate almost the same code, which we can avoid by adding a new helper method (similar to existing ones for reading numbers and strings).

The added `assert` in the new helper method also caught a bug in how the `defaultVMetrics` length was compiled.
This commit is contained in:
Jonas Jenwald 2026-03-13 09:47:20 +01:00
parent 3842936edf
commit 67f3972bf0
2 changed files with 31 additions and 34 deletions

View File

@ -192,7 +192,7 @@ function compileFontInfo(font) {
); );
if (font.defaultVMetrics) { if (font.defaultVMetrics) {
view.setUint8(offset++, 1); view.setUint8(offset++, 3);
for (const metric of font.defaultVMetrics) { for (const metric of font.defaultVMetrics) {
view.setInt16(offset, metric, true); view.setInt16(offset, metric, true);
offset += 2; offset += 2;

View File

@ -198,49 +198,46 @@ class FontInfo {
return this.#readNumber(2); return this.#readNumber(2);
} }
get bbox() { #readArray(offset, arrLen, lookupName, increment) {
let offset = FONT_INFO.OFFSET_BBOX; const len = this.#view.getUint8(offset);
const numCoords = this.#view.getUint8(offset); if (len === 0) {
if (numCoords === 0) {
return undefined; return undefined;
} }
assert(len === arrLen, "Invalid array length.");
offset += 1; offset += 1;
const bbox = []; const arr = new Array(len);
for (let i = 0; i < 4; i++) { for (let i = 0; i < len; i++) {
bbox.push(this.#view.getInt16(offset, true)); arr[i] = this.#view[lookupName](offset, true);
offset += 2; offset += increment;
} }
return bbox; return arr;
}
get bbox() {
return this.#readArray(
/* offset = */ FONT_INFO.OFFSET_BBOX,
/* arrLen = */ 4,
/* lookup = */ "getInt16",
/* increment = */ 2
);
} }
get fontMatrix() { get fontMatrix() {
let offset = FONT_INFO.OFFSET_FONT_MATRIX; return this.#readArray(
const numPoints = this.#view.getUint8(offset); /* offset = */ FONT_INFO.OFFSET_FONT_MATRIX,
if (numPoints === 0) { /* arrLen = */ 6,
return undefined; /* lookup = */ "getFloat64",
} /* increment = */ 8
offset += 1; );
const fontMatrix = [];
for (let i = 0; i < 6; i++) {
fontMatrix.push(this.#view.getFloat64(offset, true));
offset += 8;
}
return fontMatrix;
} }
get defaultVMetrics() { get defaultVMetrics() {
let offset = FONT_INFO.OFFSET_DEFAULT_VMETRICS; return this.#readArray(
const numMetrics = this.#view.getUint8(offset); /* offset = */ FONT_INFO.OFFSET_DEFAULT_VMETRICS,
if (numMetrics === 0) { /* arrLen = */ 3,
return undefined; /* lookup = */ "getInt16",
} /* increment = */ 2
offset += 1; );
const defaultVMetrics = [];
for (let i = 0; i < 3; i++) {
defaultVMetrics.push(this.#view.getInt16(offset, true));
offset += 2;
}
return defaultVMetrics;
} }
#readString(index) { #readString(index) {