工具使用指南
文件为 340,712 字节,含 18 个表。卡片的 333 KB 是二进制大小取整,不是精确字节数。
适合验证二进制读取程序,不适合比较多个字体家族,也不能据此证明浏览器渲染成功。
检查的边界
目录及偏移一致不代表每个轮廓或指令都有效。这里没有验证排版、渲染或许可。
如何使用
DejaVu Sans Mono 字体 — 读取前 12 字节和 18 个目录项,检查各表范围是否落在文件内。
from pathlib import Path
import struct
b = Path("sample.ttf").read_bytes()
assert len(b) == 340712 and b[:4] == bytes.fromhex("00010000")
u16 = lambda o: struct.unpack_from(">H", b, o)[0]
n = u16(4)
assert n == 18
tables = {}
for i in range(n):
o = 12 + 16 * i
tag = b[o:o+4].decode("ascii")
offset, length = struct.unpack_from(">II", b, o+8)
assert offset + length <= len(b)
tables[tag] = (offset, length)
print(len(b), n, "glyf" in tables, "loca" in tables)结果
签名为 00010000,18 个范围均未越界,并有 glyf 和 loca 表。这只是边界检查,不是完整有效性验证。
如何使用
DejaVu Sans Mono 字体 — 筛选 name 中平台 3、语言 1033 的记录,以 UTF-16BE 解码选定字符串。
base, size = tables["name"]
count, start = struct.unpack_from(">HH", b, base+2)
print(count)
for i in range(count):
platform, encoding, language, ident, length, offset = struct.unpack_from(">6H", b, base+6+12*i)
assert start + offset + length <= size
if platform == 3 and language == 1033 and ident in (1, 2, 4, 6):
raw = b[base+start+offset:base+start+offset+length]
print(ident, raw.decode("utf-16-be"))结果
家族名和全名为 DejaVu Sans Mono,样式为 Book,PostScript 名为 DejaVuSansMono。共有 22 条名称记录,不是 22 个字体家族。
如何使用
DejaVu Sans Mono 字体 — 读取 maxp.numGlyphs 和 head.indexToLocFormat,再检查 loca 中的长偏移量。
head = tables["head"][0]
glyphs = u16(tables["maxp"][0]+4)
assert struct.unpack_from(">h", b, head+50)[0] == 1
base, length = tables["loca"]
assert length == 4 * (glyphs + 1)
offsets = struct.unpack_from(">" + "I"*(glyphs+1), b, base)
assert all(a <= z for a, z in zip(offsets, offsets[1:]))
assert offsets[-1] <= tables["glyf"][1]
print(glyphs, len(offsets), u16(head+18))结果
3,377 个字形槽对应 3,378 个位置项。偏移量不递减且位于 glyf 范围内;字形数不等于 Unicode 字符覆盖数。
不是。它是 head 中的设计坐标尺度,不是显示像素大小。