/
builder.go
63 lines (53 loc) · 1.15 KB
/
builder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package strUtil
import (
"fmt"
"strings"
)
type Builder struct {
data []string
index int
capacity int
}
func NewBuilder(str ...string) *Builder {
return (&Builder{}).Append(str...)
}
func (this *Builder) Empty() bool { return this.index == 0 }
func (this *Builder) Clear() { this.index = 0 }
func (this *Builder) Append(str ...string) *Builder {
if n := len(str); n > 0 {
this.prepareAppend(n)
for _, s := range str {
this.data[this.index] = s
this.index++
}
}
return this
}
func (this *Builder) Appendf(format string, a ...interface{}) *Builder {
return this.Append(fmt.Sprintf(format, a...))
}
func (this *Builder) Reset() *Builder {
this.index = 0
return this
}
func (this *Builder) String() string {
return strings.Join(this.data, "")
}
func (this *Builder) prepareAppend(n int) {
if n2 := this.index + n; n2 > this.capacity {
for n2 > this.capacity {
if this.capacity == 0 {
this.capacity = 8
} else {
this.capacity *= 2
}
}
if this.index == 0 {
this.data = make([]string, this.capacity)
} else {
newData := make([]string, this.capacity)
copy(newData, this.data)
this.data = newData
}
}
}