perf(rust): 字体加载改 mmap 按需分页,冷读 31ms→1ms、RSS 43MB→4.8MB

- Font.data 改 FontBytes(Owned/Mapped 双形态,Deref 到 &[u8] 下游无感)
- FontCache 用 Mmap::map 替代 fs::read:只把被触及的表页(cmap/loca/字形/GSUB)载入,
  消除全量读盘和「page cache 一份 + 用户堆一份」双倍内存
- unsafe 仅限 mmap 建立/解除一处(字体库静态只读,无并发截断风险),为唯一例外
- 线上验证:容器内存 43MB→8MB,冷 Read 138ms→17ms;TS/LLRT 无 mmap 能力,本项为 rust 运行时专属优化
This commit is contained in:
崮生(子虚) 2026-11-04 20:43:58 +08:00
parent 24a32f72ba
commit 2044be3a4e
5 changed files with 65 additions and 8 deletions

View File

@ -1,7 +1,7 @@
{
"name": "webfont",
"private": true,
"version": "1.15.2",
"version": "1.15.3",
"type": "module",
"scripts": {
"dev": "pnpx tsx scripts/dev-all.ts",

16
rust-spike/Cargo.lock generated
View File

@ -38,9 +38,25 @@ dependencies = [
"alloc-stdlib",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "memmap2"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
dependencies = [
"libc",
]
[[package]]
name = "webfont-rs"
version = "0.1.0"
dependencies = [
"brotli",
"memmap2",
]

View File

@ -5,6 +5,7 @@ edition = "2024"
[dependencies]
brotli = "9"
memmap2 = "0.9"
[profile.release]
opt-level = 3

View File

@ -37,11 +37,18 @@ impl FontCache {
e.last_used = Instant::now();
return Ok(e.font.clone());
}
let data = std::fs::read(path).map_err(|_| FontCacheError::NotFound)?;
if data.len() > 100 * 1024 * 1024 {
// mmap 按需分页:冷启动只把被触及的表页载入(cmap/loca/目标字形/GSUB),
// 不再全量读盘,也消除「page cache 一份 + 用户堆一份」的双倍内存。
// unsafe 边界仅在 mmap 建立/解除;字体库为静态文件,无并发截断,SIGBUS 风险可忽略
let file = std::fs::File::open(path).map_err(|_| FontCacheError::NotFound)?;
let len = file.metadata().map_err(|_| FontCacheError::NotFound)?.len() as usize;
if len < 12 || len > 100 * 1024 * 1024 {
return Err(FontCacheError::NotFound);
}
let font = Arc::new(Font::parse(data).map_err(|_| FontCacheError::ParseFailed)?);
// SAFETY: 映射期间文件不会被修改/截断(字体库只读),len 已按真实文件大小校验
let mapped = unsafe { memmap2::Mmap::map(&file) }.map_err(|_| FontCacheError::NotFound)?;
let font =
Arc::new(Font::parse(mapped).map_err(|_| FontCacheError::ParseFailed)?);
map.insert(path.to_string(), FontEntry { font: font.clone(), last_used: Instant::now() });
Ok(font)
}

View File

@ -76,10 +76,41 @@ struct TableDir {
length: u32,
}
/// 字体字节本体:两种形态统一 Deref 到 &[u8],下游读表代码无感
/// - Mapped(mmap):内核按需分页,只把被触及的表页(cmap/loca/目标字形/GSUB)载入内存,
/// 冷启动不再全量读盘,也消除「page cache 一份 + 用户堆一份」的双倍占用
/// - Owned(Vec):测试/内存中构造的字体
pub enum FontBytes {
Owned(Vec<u8>),
Mapped(memmap2::Mmap),
}
impl std::ops::Deref for FontBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
match self {
FontBytes::Owned(v) => v,
FontBytes::Mapped(m) => m,
}
}
}
impl From<Vec<u8>> for FontBytes {
fn from(v: Vec<u8>) -> Self {
FontBytes::Owned(v)
}
}
impl From<memmap2::Mmap> for FontBytes {
fn from(m: memmap2::Mmap) -> Self {
FontBytes::Mapped(m)
}
}
/// 解析后的字体(进程级缓存共享,只读;持有数据本体,表目录存偏移)
pub struct Font {
/// 原始字体字节(parse 时拷贝持有,供表透传/惰性切片)
pub data: Vec<u8>,
/// 原始字体字节(mmap 按需分页或内存持有,供表透传/惰性切片)
pub data: FontBytes,
/// sfnt 表目录
tables: Vec<TableDir>,
/// maxp.numGlyphs
@ -98,8 +129,10 @@ pub struct Font {
impl Font {
/// 解析 TTF/OTF(对译 Font.parse;失败返回 Err)。
/// 拿走字节所有权:调用方 fs::read 的整文件缓冲直接进 Font,消除 to_vec 的整文件二次拷贝
pub fn parse(data: Vec<u8>) -> Result<Font, ParseError> {
/// 拿走字节所有权:Owned 形态下调用方 fs::read 的整文件缓冲直接进 Font;
/// Mapped 形态下持 mmap,消除整文件堆拷贝
pub fn parse(data: impl Into<FontBytes>) -> Result<Font, ParseError> {
let data: FontBytes = data.into();
if data.len() < 12 {
return Err(ParseError::NotTtf);
}