From dead6e007f047652d63c7a21475ceb690daeae48 Mon Sep 17 00:00:00 2001 From: Egon Elbre Date: Tue, 11 Oct 2022 11:49:00 +0300 Subject: [PATCH] f32: nicer Affine2D string formatting Signed-off-by: Egon Elbre --- f32/affine.go | 24 ++++++++++++++++++++++-- f32/affine_test.go | 23 +++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/f32/affine.go b/f32/affine.go index 7f9ab102..6ac00d59 100644 --- a/f32/affine.go +++ b/f32/affine.go @@ -3,8 +3,8 @@ package f32 import ( - "fmt" "math" + "strconv" ) // Affine2D represents an affine 2D transformation. The zero value of Affine2D @@ -148,5 +148,25 @@ func (a Affine2D) shear(radiansX, radiansY float32) Affine2D { func (a Affine2D) String() string { sx, hx, ox, hy, sy, oy := a.Elems() - return fmt.Sprintf("[[%f %f %f] [%f %f %f]]", sx, hx, ox, hy, sy, oy) + + // precision 6, one period, negative sign and space per number + const prec = 6 + const charsPerFloat = prec + 2 + 1 + s := make([]byte, 0, 6*charsPerFloat+6) + + s = append(s, '[', '[') + s = strconv.AppendFloat(s, float64(sx), 'g', prec, 32) + s = append(s, ' ') + s = strconv.AppendFloat(s, float64(hx), 'g', prec, 32) + s = append(s, ' ') + s = strconv.AppendFloat(s, float64(ox), 'g', prec, 32) + s = append(s, ']', ' ', '[') + s = strconv.AppendFloat(s, float64(hy), 'g', prec, 32) + s = append(s, ' ') + s = strconv.AppendFloat(s, float64(sy), 'g', prec, 32) + s = append(s, ' ') + s = strconv.AppendFloat(s, float64(oy), 'g', prec, 32) + s = append(s, ']', ']') + + return string(s) } diff --git a/f32/affine_test.go b/f32/affine_test.go index 4077b8d9..42c739f6 100644 --- a/f32/affine_test.go +++ b/f32/affine_test.go @@ -37,6 +37,29 @@ func TestTransformOffset(t *testing.T) { } } +func TestString(t *testing.T) { + tests := []struct { + in Affine2D + exp string + }{ + { + in: NewAffine2D(9, 11, 13, 17, 19, 23), + exp: "[[9 11 13] [17 19 23]]", + }, { + in: NewAffine2D(29, 31, 37, 43, 47, 53), + exp: "[[29 31 37] [43 47 53]]", + }, { + in: NewAffine2D(29.142342, 31.4123412, 37.53152, 43.51324213, 47.123412, 53.14312342), + exp: "[[29.1423 31.4123 37.5315] [43.5132 47.1234 53.1431]]", + }, + } + for _, test := range tests { + if test.in.String() != test.exp { + t.Errorf("string mismatch: have %q, want %q", test.in.String(), test.exp) + } + } +} + func TestTransformScale(t *testing.T) { p := Point{X: 1, Y: 2} s := Point{X: -1, Y: 2} -- 2.45.2