Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions internal/fontfile/fontfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
14 changes: 8 additions & 6 deletions internal/fontfile/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down