font: initialize default font once

This commit is contained in:
Jaroslavs Samcuks 2021-06-08 19:20:31 +02:00
parent c1468e8ae4
commit 29d53b2e35

31
font.go
View file

@ -7,23 +7,22 @@ import (
"github.com/wcharczuk/go-chart/v2/roboto" "github.com/wcharczuk/go-chart/v2/roboto"
) )
var ( var _defaultFont defaultFont
_defaultFontLock sync.Mutex
_defaultFont *truetype.Font
)
// GetDefaultFont returns the default font (Roboto-Medium). // GetDefaultFont returns the default font (Roboto-Medium).
func GetDefaultFont() (*truetype.Font, error) { func GetDefaultFont() (*truetype.Font, error) {
if _defaultFont == nil { return _defaultFont.Font()
_defaultFontLock.Lock() }
defer _defaultFontLock.Unlock()
if _defaultFont == nil { type defaultFont struct {
font, err := truetype.Parse(roboto.Roboto) font *truetype.Font
if err != nil { err error
return nil, err once sync.Once
} }
_defaultFont = font
} func (df *defaultFont) Font() (*truetype.Font, error) {
} df.once.Do(func() {
return _defaultFont, nil df.font, df.err = truetype.Parse(roboto.Roboto)
})
return df.font, df.err
} }