From e3deefa89b7347fb6ef1abeaece14fd0fe5d9ef4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B4=AE=E7=94=9F=EF=BC=88=E5=AD=90=E8=99=9A=EF=BC=89?= <2234839456@qq.com> Date: Thu, 5 Nov 2026 09:04:10 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20/api/svg=20=E6=96=87=E5=AD=97=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E5=BD=A2=E7=9F=A2=E9=87=8F=E8=BD=AE=E5=BB=93=20SVG?= =?UTF-8?q?=EF=BC=88TS+Rust=20=E5=8F=8C=E7=AB=AF=EF=BC=89=EF=BC=8CREADME?= =?UTF-8?q?=20=E5=AD=97=E4=BD=93=E6=95=88=E6=9E=9C=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E9=A2=84=E8=A7=88=EF=BC=8C=E5=8F=91=E5=B8=83=20v1.16.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - backend/routes/svg.ts:文字→TrueType 二次贝塞尔轮廓路径 SVG,LRU 缓存+颜色注入防护,供 README/邮件等 场景展示字体效果(SVG 图片无法引用外部字体,矢量路径是唯一可渲染形态) - rust-spike/src/svg.rs:对译 Rust 版,复用进程级 Font 缓存 cmap_get+glyph_contours(跳过子集化更快),与 TS 版输出字节级一致(cmp 验证) - ttf.rs 新增 Font::advance_width(hmtx spec 继承语义) - README 新增「字体效果预览」章节,6 款字体实时 SVG - v1.16.0 已发布上线,公网 /api/svg 验证 200+缓存 HIT --- README.md | 37 +++++ backend/app.ts | 4 + backend/font_util/glyph_bitmap.ts | 5 + backend/routes/svg.ts | 217 +++++++++++++++++++++++++ package.json | 2 +- rust-spike/src/main.rs | 4 + rust-spike/src/svg.rs | 252 ++++++++++++++++++++++++++++++ rust-spike/src/ttf.rs | 23 +++ 8 files changed, 543 insertions(+), 1 deletion(-) create mode 100644 backend/routes/svg.ts create mode 100644 rust-spike/src/svg.rs diff --git a/README.md b/README.md index bc80d77..cb0dc1e 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,43 @@ - LeaferJS 画布 / 设计工具 — [leafer-x-webfont](https://www.npmjs.com/package/leafer-x-webfont) 插件,画布 Text 用什么字体就加载那几个字([在线 demo](https://webfont.shenzilong.cn/leafer-demo/)) - AI 生成网页 — 让 AI 也能输出有设计感的中文字体方案 +## 字体效果预览 + +下面这些图片不是截图,而是服务端实时返回的 **SVG 矢量文字**(`/api/svg` 接口把字符转成字形轮廓路径,无需加载字体文件即可在任意环境渲染): + +

+ 令东齐伋复刻体 - 静心茶舍
+ 令东齐伋复刻体 +

+

+ 得意黑 - 快如闪电
+ 得意黑 +

+

+ 霞鹜文楷 - 温柔岁月
+ 霞鹜文楷 +

+

+ 马克笔哥特体 - 无畏造梦
+ 马克笔哥特体 +

+

+ 刘建毛草 - 乘物游心
+ 刘建毛草 +

+

+ 优设标题黑 - 字随需载
+ 优设标题黑 +

+ +用法(参数:`font` 字体名 / `text` 文字 / `size` 字号 12-400 / `color` 十六进制颜色): + +```html + +``` + +适合 README 徽章式标题、邮件内嵌图、不支持自定义字体的第三方页面等场景——输出的 SVG 只有几 KB,且矢量无限清晰。 + ## 核心能力 > [在线体验中文字体效果对比](https://webfont.shenzilong.cn/?demo) — 同一内容,字体不同,体验天壤之别 diff --git a/backend/app.ts b/backend/app.ts index f34188a..8528cd2 100644 --- a/backend/app.ts +++ b/backend/app.ts @@ -21,6 +21,7 @@ import { handleGetConfig } from "./routes/config"; import { handleStats, handleStatsEvent } from "./routes/stats"; import { handleUpload } from "./routes/upload"; import { handleFontSubset } from "./routes/subset"; +import { handleFontSvg } from "./routes/svg"; import { handleGlyphMatch } from "./routes/glyph_match"; import { handleFontDetail } from "./routes/font_detail"; import { handleFontMeta } from "./routes/font_meta"; @@ -179,6 +180,9 @@ const fontApiMiddleware: cMiddleware = async (req, res, next) => { if (url.pathname === "/api" && req.method === "GET") { return handleFontSubset(req, res); } + if (url.pathname === "/api/svg" && req.method === "GET") { + return handleFontSvg(req, res); + } if (url.pathname === "/api/glyph-match" && req.method === "POST") { return handleGlyphMatch(req, res); } diff --git a/backend/font_util/glyph_bitmap.ts b/backend/font_util/glyph_bitmap.ts index 479e76e..209ed32 100644 --- a/backend/font_util/glyph_bitmap.ts +++ b/backend/font_util/glyph_bitmap.ts @@ -83,6 +83,11 @@ function readGlyphContours(ttf: any, glyf: any): RawContour[] { return contours; } +/** 对外:读取一个字形的轮廓并统一为对象点形态(供 SVG 矢量化等复用) */ +export function readGlyphContoursNormalized(ttf: any, glyf: any): Array> { + return readGlyphContours(ttf, glyf).map(normalizeContour); +} + /** 把对象点或扁平三元组统一成对象点 */ function normalizeContour(contour: RawContour): GlyphPoint[] { const points: GlyphPoint[] = []; diff --git a/backend/routes/svg.ts b/backend/routes/svg.ts new file mode 100644 index 0000000..2ce62c5 --- /dev/null +++ b/backend/routes/svg.ts @@ -0,0 +1,217 @@ +import { parseUrl, stats, subsetCache, findFontPath, markStatsDirty } from "../shared"; +import { markFontUsed } from "../temp_cleaner"; +import { withMemoryGate } from "../subset_queue"; +import { estimateSubsetMemory, subsetFontFile } from "../font_util/subset_file"; +import { SUBSET_CACHE_KEY } from "./subset"; +import { readGlyphContoursNormalized } from "../font_util/glyph_bitmap"; +import { subsetQueueTimeoutSeconds } from "../config"; + +/** + * GET /api/svg?font=...&text=...&size=64&color=333333 + * + * 把文字转成「字形矢量轮廓」的 SVG(文字不是 ,而是 )。 + * 用途:README / 网页中 直接展示字体效果——SVG 作为图片加载时无法引用 + * 外部 @font-face(GitHub camo 代理与浏览器安全策略双重限制),矢量路径是唯一 + * 可在任意上下文渲染的形态,且体积只有几 KB。 + * + * 实现复用裁剪管线:先按 text 裁出小子集,再从内存 ttf 对象读取每个字形的 + * 二次贝塞尔轮廓(subset 模式下 compound 已展开为 simple),拼接为 SVG path。 + * OTF(CFF)源字体裁剪管线返回内存对象为 null,返回 422 提示不支持。 + */ + +/** 二次贝塞尔轮廓点(TrueType 字形坐标,y 向上) */ +type GlyphPoint = { x: number; y: number; onCurve: boolean }; + +/** 单条轮廓转 SVG path 片段(M/L/Q/Z,含 TrueType 隐含中点 on-curve 语义) */ +function contourToPath(contour: GlyphPoint[], parts: string[]): void { + if (contour.length < 2) return; + const mid = (a: GlyphPoint, b: GlyphPoint): GlyphPoint => ({ + x: (a.x + b.x) / 2, + y: (a.y + b.y) / 2, + onCurve: true, + }); + const n = contour.length; + /** 找 on-curve 起点;全 off-curve(极罕见)用首尾中点作隐含起点 */ + let startIdx = contour.findIndex((p) => p.onCurve); + let start: GlyphPoint; + if (startIdx === -1) { + start = mid(contour[n - 1]!, contour[0]!); + startIdx = 0; + } else { + start = contour[startIdx]!; + } + parts.push(`M ${start.x} ${start.y}`); + /** 上一段终点的 on-curve 点(作为潜在 Q 的起点) */ + let prev = start; + /** 悬挂中的 off-curve 控制点(连续 off-curve 时逐段消耗) */ + let ctrl: GlyphPoint | null = null; + for (let k = 1; k <= n; k++) { + const p = contour[(startIdx + k) % n]!; + if (p.onCurve) { + if (ctrl) { + parts.push(`Q ${ctrl.x} ${ctrl.y} ${p.x} ${p.y}`); + ctrl = null; + } else { + parts.push(`L ${p.x} ${p.y}`); + } + prev = p; + } else { + if (ctrl) { + /** 连续 off-curve:前控制点与本控制点的中点是隐含 on-curve 终点 */ + const implied = mid(ctrl, p); + parts.push(`Q ${ctrl.x} ${ctrl.y} ${implied.x} ${implied.y}`); + prev = implied; + } + ctrl = p; + } + } + /** 收尾:悬挂控制点指回起点 */ + if (ctrl) parts.push(`Q ${ctrl.x} ${ctrl.y} ${start.x} ${start.y}`); + parts.push("Z"); +} + +/** 参数安全化:颜色仅允许 3/6 位十六进制,防 SVG 注入 */ +function sanitizeColor(input: string | null): string { + const v = (input ?? "").replace(/[^0-9a-fA-F]/g, ""); + return /^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(v) ? v : "333333"; +} + +/** GET /api/svg — 文字 → 字形矢量路径 SVG */ +export async function handleFontSvg(req: Request, res: Response) { + const url = parseUrl(req); + const params = new URLSearchParams(url.search); + const font = params.get("font") || ""; + const text = params.get("text") || ""; + if (text.length === 0) { + return { req, res }; + } + const fontPath = await findFontPath(font); + if (!fontPath) { + return { + req, + res: new Response(`Font not found: ${font}`, { + status: 404, + headers: { "Content-Type": "text/plain; charset=utf-8" }, + }), + }; + } + + /** 输出像素字号(决定 viewBox 缩放)与填充色 */ + const size = Math.min(Math.max(Number(params.get("size")) || 64, 12), 400); + const color = sanitizeColor(params.get("color")); + + markFontUsed(fontPath); + stats.totalRequests++; + stats.subsetRequests++; + stats.totalChars += text.length; + markStatsDirty(); + + /** 与裁剪接口同一缓存命名空间:SVG 输出确定性,可长缓存 */ + const cacheKey = `${SUBSET_CACHE_KEY}:svg:${fontPath}:${size}:${color}:${text}`; + const cached = subsetCache.get(cacheKey); + if (cached) { + stats.subsetCacheHits++; + markStatsDirty(); + return { + req, + res: new Response(cached.bytes as unknown as BodyInit, { + status: 200, + headers: { + "Content-Type": "image/svg+xml; charset=utf-8", + "Cache-Control": "public, max-age=86400", + "X-Cache": "HIT", + }, + }), + }; + } + + const memoryBytes = await estimateSubsetMemory(fontPath); + const subsetResult = await withMemoryGate( + () => subsetFontFile(fontPath, text, "ttf"), + subsetQueueTimeoutSeconds * 1000, + memoryBytes, + ); + if (subsetResult === null) { + return { + req, + res: new Response("Server busy, please retry", { + status: 503, + headers: { "Content-Type": "text/plain; charset=utf-8", "Retry-After": "1" }, + }), + }; + } + const ttf = subsetResult.ttf as { + head: { unitsPerEm: number }; + glyf: Array<{ unicode?: number | number[]; advanceWidth?: number; contours?: unknown; compound?: unknown }>; + } | null; + if (!ttf) { + return { + req, + res: new Response("SVG output is not supported for this font (CFF/OTF outline)", { + status: 422, + headers: { "Content-Type": "text/plain; charset=utf-8" }, + }), + }; + } + + const upem = ttf.head.unitsPerEm || 1000; + /** 子集 glyf 自带 unicode 标注 → codepoint → 新 gid 映射(与 glyph-match 同法) */ + const cmap: Record = {}; + for (const [index, glyph] of ttf.glyf.entries()) { + if (!glyph.unicode) continue; + for (const cp of Array.isArray(glyph.unicode) ? glyph.unicode : [glyph.unicode]) { + if (!(cp in cmap)) cmap[cp] = index; + } + } + + /** 逐字符取轮廓拼 path;缺字跳过(与 .notdef 等价的降级是空占位) */ + const paths: Array<{ d: string; dx: number }> = []; + const codePoints: number[] = []; + for (let i = 0; i < text.length; i++) { + const cp = text.codePointAt(i)!; + if (cp > 0xffff) i++; + codePoints.push(cp); + } + /** 水平布局游标(字体单位) */ + let penX = 0; + for (const cp of codePoints) { + const gid = cmap[cp]; + if (gid === undefined) { + penX += upem / 2; + continue; + } + const glyph = ttf.glyf[gid]!; + const parts: string[] = []; + for (const contour of readGlyphContoursNormalized(ttf, glyph)) contourToPath(contour, parts); + if (parts.length > 0) paths.push({ d: parts.join(" "), dx: penX }); + penX += glyph.advanceWidth ?? upem; + } + + /** 高度行框按字体单位 1.3 倍(含 ascender/descender 余量),y 翻转由 group transform 完成 */ + const ascent = upem * 1.05; + const descent = upem * 0.25; + const totalW = penX; + const scale = size / upem; + const svgW = Math.max(totalW * scale, 1).toFixed(2); + const svgH = (size * (ascent + descent) / upem).toFixed(2); + const body = paths + .map((p) => ``) + .join(""); + const svg = + `${body}`; + + const svgBytes = new TextEncoder().encode(svg); + subsetCache.set(cacheKey, { bytes: svgBytes, ttf: null }); + return { + req, + res: new Response(svg, { + status: 200, + headers: { + "Content-Type": "image/svg+xml; charset=utf-8", + "Cache-Control": "public, max-age=86400", + "X-Cache": "MISS", + }, + }), + }; +} diff --git a/package.json b/package.json index 6e0a7d2..c4ef4e1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "webfont", "private": true, - "version": "1.15.6", + "version": "1.16.0", "type": "module", "scripts": { "dev": "pnpx tsx scripts/dev-all.ts", diff --git a/rust-spike/src/main.rs b/rust-spike/src/main.rs index babc810..80cbebd 100644 --- a/rust-spike/src/main.rs +++ b/rust-spike/src/main.rs @@ -10,6 +10,7 @@ mod glyph_match; mod gsub; mod http; mod misc; +mod svg; mod ttf; mod woff2; @@ -385,6 +386,9 @@ fn route_request( if r.path == "/api" && is_get { return handle_subset(app, stream, r.query, close, r.if_none_match.as_deref()); } + if r.path == "/api/svg" && is_get { + return svg::handle_svg(app, stream, r.query, close, r.if_none_match.as_deref()); + } if r.path == "/api/glyph-match" && is_post { return misc::handle_glyph_match(stream, &app.font_dirs, &app.fonts, r.body, close); } diff --git a/rust-spike/src/svg.rs b/rust-spike/src/svg.rs new file mode 100644 index 0000000..92f6f9a --- /dev/null +++ b/rust-spike/src/svg.rs @@ -0,0 +1,252 @@ +//! GET /api/svg?font=..&text=..&size=..&color=.. —— 文字 → 字形矢量轮廓 SVG +//! +//! 语义对齐 backend/routes/svg.ts:把字符转成 TrueType 二次贝塞尔轮廓路径 +//! (非 ),供 README / 邮件 / 不支持自定义字体的环境用 直接展示。 +//! 与 TS 版的结构性差异:Rust 版不做子集化——直接从进程级缓存的完整 Font 上 +//! 查 cmap + 取轮廓,省掉整条裁剪管线(更快且结果相同)。 + +use crate::cache::FontCacheError; +use crate::{cache, http, misc, ttf, App}; + +/// 二次贝塞尔轮廓 → SVG path 片段(M/L/Q/Z;TrueType 隐含中点 on-curve 语义) +fn contour_to_path(contour: &[ttf::GlyfPt], parts: &mut Vec) { + if contour.len() < 2 { + return; + } + let n = contour.len(); + let mid = |a: &ttf::GlyfPt, b: &ttf::GlyfPt| (f64::from(a.x + b.x) / 2.0, f64::from(a.y + b.y) / 2.0); + // 数值格式化:整数不带小数点,节省体积 + let num = |v: f64| -> String { + if v.fract() == 0.0 { + format!("{}", v as i64) + } else { + format!("{v}") + } + }; + + // 找 on-curve 起点;全 off-curve(极罕见)用首尾中点作隐含起点 + let start_idx = match contour.iter().position(|p| p.on_curve) { + Some(i) => i, + None => 0, + }; + let (sx, sy): (f64, f64) = if contour[start_idx].on_curve { + (f64::from(contour[start_idx].x), f64::from(contour[start_idx].y)) + } else { + let (mx, my) = mid(&contour[n - 1], &contour[0]); + (mx, my) + }; + parts.push(format!("M {} {}", num(sx), num(sy))); + + let mut prev = (sx, sy); + // 悬挂中的 off-curve 控制点 + let mut ctrl: Option<(f64, f64)> = None; + for k in 1..=n { + let p = &contour[(start_idx + k) % n]; + let cur = (f64::from(p.x), f64::from(p.y)); + if p.on_curve { + match ctrl.take() { + Some(c) => parts.push(format!("Q {} {} {} {}", num(c.0), num(c.1), num(cur.0), num(cur.1))), + None => parts.push(format!("L {} {}", num(cur.0), num(cur.1))), + } + prev = cur; + } else { + if let Some(c) = ctrl { + // 连续 off-curve:前控制点与本控制点的中点是隐含 on-curve 终点 + let implied = ((c.0 + cur.0) / 2.0, (c.1 + cur.1) / 2.0); + parts.push(format!("Q {} {} {} {}", num(c.0), num(c.1), num(implied.0), num(implied.1))); + prev = implied; + } + ctrl = Some(cur); + } + } + // 收尾:悬挂控制点指回起点 + if let Some(c) = ctrl { + parts.push(format!("Q {} {} {} {}", num(c.0), num(c.1), num(sx), num(sy))); + } + let _ = prev; + parts.push("Z".to_string()); +} + +/// 参数安全化:颜色仅允许 3/6 位十六进制,防 SVG 注入 +fn sanitize_color(input: &str) -> String { + let v: String = input.chars().filter(|c| c.is_ascii_hexdigit()).collect(); + if v.len() == 3 || v.len() == 6 { + v + } else { + "333333".to_string() + } +} + +/// GET /api/svg —— 文字 → 字形矢量路径 SVG(对译 backend/routes/svg.ts) +pub fn handle_svg( + app: &App, + stream: &mut std::net::TcpStream, + query: &str, + close: bool, + if_none_match: Option<&str>, +) -> std::io::Result { + let mut font_name = Vec::new(); + let mut text = Vec::new(); + let mut size: i64 = 64; + let mut color = String::new(); + for kv in query.split('&') { + let Some(eq) = kv.find('=') else { continue }; + let (k, v) = (&kv[..eq], &kv[eq + 1..]); + match k { + "font" => font_name = http::url_decode(v), + "text" => text = http::url_decode(v), + "size" => size = v.parse().unwrap_or(64), + "color" => color = sanitize_color(&String::from_utf8_lossy(&http::url_decode(v))), + _ => {} + } + } + let Ok(font_name) = std::str::from_utf8(&font_name) else { + http::send_text(stream, 400, "bad font", close, &[])?; + return Ok(close); + }; + if text.is_empty() { + return Ok(true); + } + if font_name.contains("..") { + http::send_text(stream, 400, "bad font", close, &[])?; + return Ok(close); + } + let Ok(text) = std::str::from_utf8(&text) else { + http::send_text(stream, 400, "bad text", close, &[])?; + return Ok(close); + }; + let Some(font_path) = crate::find_font_path(&app.font_dirs, font_name) else { + let msg = format!("Font not found: {font_name}"); + http::send_text(stream, 404, &msg, close, &[])?; + return Ok(close); + }; + + let size = size.clamp(12, 400); + + misc::mark_font_used(&font_path); + misc::stats_record_subset(misc::utf16_len_utf8(text)); + + // 缓存 key 对齐 TS:svg 前缀 + 字体路径 + size + color + 文本 + let cache_key = format!("svg:{font_path}:{size}:{color}:{text}"); + if let Some(bytes) = app.subset_cache.get(&cache_key) { + misc::stats_record_cache_hit(); + let etag = http::etag_of(&bytes); + http::send_font( + stream, + &bytes, + close, + "image/svg+xml; charset=utf-8", + &["X-Cache: HIT"], + &[], + &etag, + if_none_match, + )?; + return Ok(close); + } + + // 与 handle_subset 同闸门:字体读取/解析在闸门内,轮廓提取(毫秒级 CPU)在外 + let est = misc::estimate_subset_memory(&font_path); + if !misc::gate_acquire(misc::queue_timeout_ms(), est) { + http::send_text(stream, 503, "Server busy, please retry", close, &["Retry-After: 1"])?; + return Ok(close); + } + let font = match app.fonts.get_or_parse(&font_path) { + Ok(f) => f, + Err(cache::FontCacheError::NotFound) => { + misc::gate_release(est); + http::send_text(stream, 404, "font not found", close, &[])?; + return Ok(close); + } + Err(FontCacheError::ParseFailed) => { + misc::gate_release(est); + http::send_text(stream, 422, "font parse failed", close, &[])?; + return Ok(close); + } + }; + misc::gate_release(est); + + let upem = f64::from(font.units_per_em.max(1)); + + // 逐字符取轮廓拼 path;缺字跳过(空占位,与 TS 版一致) + let mut paths: Vec<(f64 /*dx*/, String /*d*/)> = Vec::new(); + let mut pen_x: f64 = 0.0; + for ch in text.chars() { + let cp = ch as u32; + let Some(gid) = font.cmap_get(cp) else { + pen_x += upem / 2.0; + continue; + }; + let contours = match ttf::glyph_contours(&font, gid, 0) { + Ok(c) => c, + // CFF/OTF 轮廓不经过 glyf 表,无法转 SVG 路径(对齐 TS 版 422) + Err(_) => { + http::send_text( + stream, + 422, + "SVG output is not supported for this font (CFF/OTF outline)", + close, + &[], + )?; + return Ok(close); + } + }; + let mut parts: Vec = Vec::new(); + for c in &contours { + contour_to_path(c, &mut parts); + } + if !parts.is_empty() { + paths.push((pen_x, parts.join(" "))); + } + pen_x += f64::from(font.advance_width(gid).unwrap_or_else(|| font.units_per_em.max(1) as u16)); + } + + // 高度行框按字体单位 1.3 倍(含 ascender/descender 余量),y 翻转由 group transform 完成 + let ascent = upem * 1.05; + let descent = upem * 0.25; + let size_f = size as f64; + let scale = size_f / upem; + let total_w = pen_x; + let svg_w = (total_w * scale).max(1.0); + let svg_h = size_f * (ascent + descent) / upem; + let mut svg = format!( + r##""##, + fmt_num(total_w), + fmt_num(ascent + descent), + svg_w, + svg_h, + color + ); + for (dx, d) in &paths { + svg.push_str(&format!( + r#""#, + fmt_num(*dx), + fmt_num(ascent), + d + )); + } + svg.push_str(""); + + let bytes = svg.into_bytes(); + app.subset_cache.insert(&cache_key, bytes.clone()); + let etag = http::etag_of(&bytes); + http::send_font( + stream, + &bytes, + close, + "image/svg+xml; charset=utf-8", + &["X-Cache: MISS"], + &[], + &etag, + if_none_match, + )?; + Ok(close) +} + +/// 数值格式化:整数不带小数点 +fn fmt_num(v: f64) -> String { + if v.fract() == 0.0 { + format!("{}", v as i64) + } else { + format!("{v}") + } +} diff --git a/rust-spike/src/ttf.rs b/rust-spike/src/ttf.rs index fd82769..a370503 100644 --- a/rust-spike/src/ttf.rs +++ b/rust-spike/src/ttf.rs @@ -260,6 +260,29 @@ impl Font { (pairs, idx) } + /// gid 的 advance width(hmtx spec 继承:≥numberOfHMetrics 复用末条;缺表回退 unitsPerEm) + /// 供 /api/svg 水平布局使用 + pub fn advance_width(&self, gid: u16) -> Option { + let hmtx = self.find_table(b"hmtx")?; + let nhm: u32 = self + .find_table(b"hhea") + .filter(|h| h.len() >= 36) + .map(|h| ru16(h, 34) as u32) + .unwrap_or(0); + let src: u32 = if u32::from(gid) < nhm { + u32::from(gid) + } else if nhm > 0 { + nhm - 1 + } else { + 0 + }; + let o = src as usize * 4; + if o + 2 > hmtx.len() { + return None; + } + Some(ru16(hmtx, o)) + } + /// 查表体切片(越界表按缺失处理,对译 findTable) fn find_table(&self, tag: &[u8; 4]) -> Option<&[u8]> { for t in &self.tables {