From 8d1590caea8624d98185f072e814ed7f166eea9c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 12 Nov 2026 05:14:55 +0800 Subject: [PATCH] fontfile: name staged fonts by SHA-256 Registering a font hashes its bytes to name the staged file. FNV-1a 128 runs a byte at a time, about 390 MB/s on an M-series Mac, so an application that registers a few dozen megabytes of faces before its first paint (an interface family, a code family and a patched terminal family) waited about 75 ms on the hash alone. SHA-256 uses the platform's hash instructions and runs at about 3.3 GB/s. The key keeps its shape (128 bits and the length byte); a face staged under the old name is staged once more under the new one. --- internal/fontfile/fontfile_test.go | 13 +++++++++++++ internal/fontfile/store.go | 14 ++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/internal/fontfile/fontfile_test.go b/internal/fontfile/fontfile_test.go index 16a6c9810..698423e58 100644 --- a/internal/fontfile/fontfile_test.go +++ b/internal/fontfile/fontfile_test.go @@ -93,3 +93,16 @@ func TestAFontTheEngineRefusesIsNotKept(t *testing.T) { t.Fatalf("after a refusal the font registers again: %v, added %d", err, added) } } + +// BenchmarkKeyOf measures naming a face the size of a patched terminal font (2.5 MB), which an +// application registers before its first paint. +func BenchmarkKeyOf(b *testing.B) { + data := make([]byte, 5<<19) + for i := range data { + data[i] = byte(i * 31) + } + b.SetBytes(int64(len(data))) + for b.Loop() { + keyOf(data) + } +} diff --git a/internal/fontfile/store.go b/internal/fontfile/store.go index d4983cb6a..242c8096e 100644 --- a/internal/fontfile/store.go +++ b/internal/fontfile/store.go @@ -2,24 +2,26 @@ package fontfile import ( "bytes" + "crypto/sha256" "encoding/hex" "errors" "fmt" - "hash/fnv" "os" "path/filepath" "sync" ) -// fontKey names a font by its content: a 128-bit FNV-1a hash and the length. It is a name, not a -// guarantee, so a file found under it is used only when it holds exactly the same bytes. +// fontKey names a font by its content: the first 128 bits of its SHA-256 and the length. It is a +// name, not a guarantee, so a file found under it is used only when it holds exactly the same +// bytes. SHA-256 rather than a byte-at-a-time hash because the platforms' instructions for it hash +// a font family of a few dozen megabytes in milliseconds, which an application registering its +// fonts before its first paint waits for. type fontKey [17]byte func keyOf(data []byte) fontKey { - hash := fnv.New128a() - hash.Write(data) + sum := sha256.Sum256(data) var key fontKey - hash.Sum(key[:0]) + copy(key[:16], sum[:16]) key[16] = byte(len(data)) return key }