github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zstring/template_test.go (about) 1 package zstring_test 2 3 import ( 4 "io" 5 "strings" 6 "testing" 7 8 zls "github.com/sohaha/zlsgo" 9 "github.com/sohaha/zlsgo/zstring" 10 "github.com/sohaha/zlsgo/zutil" 11 ) 12 13 func TestNewTemplate(t *testing.T) { 14 tt := zls.NewTest(t) 15 16 tmpl, err := zstring.NewTemplate("hello {name}", "{", "}") 17 tt.NoError(err) 18 19 w := zutil.GetBuff() 20 defer zutil.PutBuff(w) 21 22 _, err = tmpl.Process(w, func(w io.Writer, tag string) (int, error) { 23 return w.Write([]byte("Go")) 24 }) 25 tt.NoError(err) 26 tt.Equal("hello Go", w.String()) 27 28 err = tmpl.ResetTemplate("The best {n} {say}") 29 tt.NoError(err) 30 31 w.Reset() 32 _, err = tmpl.Process(w, func(w io.Writer, tag string) (int, error) { 33 switch tag { 34 case "say": 35 return w.Write([]byte("!!!")) 36 } 37 return w.Write([]byte("Go")) 38 }) 39 tt.NoError(err) 40 tt.Equal("The best Go !!!", w.String()) 41 } 42 43 func BenchmarkTemplate(b *testing.B) { 44 tmpl, _ := zstring.NewTemplate("hello {name}", "{", "}") 45 46 b.Run("Buffer", func(b *testing.B) { 47 b.RunParallel(func(pb *testing.PB) { 48 for pb.Next() { 49 var w strings.Builder 50 _, _ = tmpl.Process(&w, func(w io.Writer, tag string) (int, error) { 51 return w.Write([]byte("Go")) 52 }) 53 } 54 }) 55 }) 56 57 b.Run("GetBuff", func(b *testing.B) { 58 b.RunParallel(func(pb *testing.PB) { 59 for pb.Next() { 60 w := zutil.GetBuff() 61 _, _ = tmpl.Process(w, func(w io.Writer, tag string) (int, error) { 62 return w.Write([]byte("Go")) 63 }) 64 zutil.PutBuff(w) 65 } 66 }) 67 }) 68 }