1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package buffer
22
23 import (
24 "bytes"
25 "strings"
26 "testing"
27 "time"
28
29 "github.com/stretchr/testify/assert"
30 )
31
32 func TestBufferWrites(t *testing.T) {
33 buf := NewPool().Get()
34
35 tests := []struct {
36 desc string
37 f func()
38 want string
39 }{
40 {"AppendByte", func() { buf.AppendByte('v') }, "v"},
41 {"AppendString", func() { buf.AppendString("foo") }, "foo"},
42 {"AppendIntPositive", func() { buf.AppendInt(42) }, "42"},
43 {"AppendIntNegative", func() { buf.AppendInt(-42) }, "-42"},
44 {"AppendUint", func() { buf.AppendUint(42) }, "42"},
45 {"AppendBool", func() { buf.AppendBool(true) }, "true"},
46 {"AppendFloat64", func() { buf.AppendFloat(3.14, 64) }, "3.14"},
47
48 {"AppendFloat32", func() { buf.AppendFloat(float64(float32(3.14)), 32) }, "3.14"},
49 {"AppendWrite", func() { buf.Write([]byte("foo")) }, "foo"},
50 {"AppendTime", func() { buf.AppendTime(time.Date(2000, 1, 2, 3, 4, 5, 6, time.UTC), time.RFC3339) }, "2000-01-02T03:04:05Z"},
51 {"WriteByte", func() { buf.WriteByte('v') }, "v"},
52 {"WriteString", func() { buf.WriteString("foo") }, "foo"},
53 }
54
55 for _, tt := range tests {
56 t.Run(tt.desc, func(t *testing.T) {
57 buf.Reset()
58 tt.f()
59 assert.Equal(t, tt.want, buf.String(), "Unexpected buffer.String().")
60 assert.Equal(t, tt.want, string(buf.Bytes()), "Unexpected string(buffer.Bytes()).")
61 assert.Equal(t, len(tt.want), buf.Len(), "Unexpected buffer length.")
62
63 assert.Equal(t, _size, buf.Cap(), "Expected buffer capacity to remain constant.")
64 })
65 }
66 }
67
68 func BenchmarkBuffers(b *testing.B) {
69
70
71
72
73 str := strings.Repeat("a", 1024)
74 slice := make([]byte, 1024)
75 buf := bytes.NewBuffer(slice)
76 custom := NewPool().Get()
77 b.Run("ByteSlice", func(b *testing.B) {
78 for i := 0; i < b.N; i++ {
79 slice = append(slice, str...)
80 slice = slice[:0]
81 }
82 })
83 b.Run("BytesBuffer", func(b *testing.B) {
84 for i := 0; i < b.N; i++ {
85 buf.WriteString(str)
86 buf.Reset()
87 }
88 })
89 b.Run("CustomBuffer", func(b *testing.B) {
90 for i := 0; i < b.N; i++ {
91 custom.AppendString(str)
92 custom.Reset()
93 }
94 })
95 }
96
View as plain text