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 }