From 81e0e61a430a42b5a255f2a84c5be83efcda5776 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Mon, 4 Dec 2023 01:16:39 +0900 Subject: [PATCH] text/v2: let NewMultiFace return an error Updates #2845 --- examples/mixedfont/main.go | 6 +++++- text/v2/multi.go | 18 ++++++++++++++++-- text/v2/text_test.go | 5 ++++- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/examples/mixedfont/main.go b/examples/mixedfont/main.go index d54c3e9c0..27f2cd878 100644 --- a/examples/mixedfont/main.go +++ b/examples/mixedfont/main.go @@ -74,7 +74,11 @@ func (g *Game) Update() error { Size: 32, } - g.face = text.NewMultiFace(en, ja) + f, err := text.NewMultiFace(en, ja) + if err != nil { + return err + } + g.face = f } return nil } diff --git a/text/v2/multi.go b/text/v2/multi.go index 8797255f4..8eadbeb7a 100644 --- a/text/v2/multi.go +++ b/text/v2/multi.go @@ -15,6 +15,7 @@ package text import ( + "errors" "unicode/utf8" "github.com/hajimehoshi/ebiten/v2/vector" @@ -31,11 +32,24 @@ type MultiFace struct { } // NewMultiFace creates a new MultiFace from the given faces. -func NewMultiFace(faces ...Face) *MultiFace { +// +// NewMultiFace returns an error when no faces are given, or the faces' directions don't agree. +func NewMultiFace(faces ...Face) (*MultiFace, error) { + if len(faces) == 0 { + return nil, errors.New("text: no faces are given at NewMultiFace") + } + + d := faces[0].direction() + for _, f := range faces[1:] { + if f.direction() != d { + return nil, errors.New("text: all the faces' directions must agree") + } + } + m := &MultiFace{} m.faces = make([]Face, len(faces)) copy(m.faces, faces) - return m + return m, nil } // Metrics implements Face. diff --git a/text/v2/text_test.go b/text/v2/text_test.go index a76051d27..01e123d62 100644 --- a/text/v2/text_test.go +++ b/text/v2/text_test.go @@ -243,7 +243,10 @@ func TestUnhashableFace(t *testing.T) { func TestMultiFace(t *testing.T) { faces := []text.Face{text.NewStdFace(bitmapfont.Face)} - f := text.NewMultiFace(faces...) + f, err := text.NewMultiFace(faces...) + if err != nil { + t.Fatal(err) + } img := ebiten.NewImage(30, 30) text.Draw(img, "Hello", f, nil)