Skip to content

Commit

Permalink
cache the font files
Browse files Browse the repository at this point in the history
  • Loading branch information
JessonChan committed Aug 6, 2022
1 parent de34ee1 commit 38dc470
Showing 1 changed file with 36 additions and 11 deletions.
47 changes: 36 additions & 11 deletions internal/gdi/font/font.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ package font
import (
"fmt"
"image"
"io/ioutil"
"io"
"os"
"path"
"sync"

Expand Down Expand Up @@ -87,19 +88,43 @@ func (p *Default) findFontAtPath(
return false
}

func (p *Default) tryFontFile(name, tryFile string, options *truetype.Options) bool {
fp, err := fsutil.OpenFile(tryFile)
if err != nil {
return false
}
defer fp.Close()
// Each Default.(Font.Face) object holds all the content of the font file in memory,
// in fact the file content is read-only.
// Different Default-Objects with same file should share the content,not allocate new memory.
var fontFileCache = struct {
files map[string][]byte
sync.Mutex
}{
files: map[string][]byte{},
}

b, err := ioutil.ReadAll(fp)
if err != nil {
return false
func (p *Default) tryFontFile(name, tryFile string, options *truetype.Options) bool {
fontFileCache.Lock()
var bs []byte
var ok bool
if bs, ok = fontFileCache.files[tryFile]; !ok {
fp, err := fsutil.OpenFile(tryFile)
if err != nil {
fontFileCache.Unlock()
return false
}
defer fp.Close()
fi, err := os.Stat(tryFile)
if err != nil {
fontFileCache.Unlock()
return false
}
bs = make([]byte, fi.Size())
n, err := io.ReadFull(fp, bs)
if err != nil || n != len(bs) {
fontFileCache.Unlock()
return false
}
fontFileCache.files[tryFile] = bs
}
fontFileCache.Unlock()

tt, err := truetype.Parse(b)
tt, err := truetype.Parse(bs)
if err != nil {
return false
}
Expand Down

0 comments on commit 38dc470

Please sign in to comment.