...
Source file
src/strings/builder.go
Documentation: strings
1
2
3
4
5 package strings
6
7 import (
8 "unicode/utf8"
9 "unsafe"
10 )
11
12
13
14
15 type Builder struct {
16 addr *Builder
17 buf []byte
18 }
19
20
21
22
23
24
25
26
27
28 func noescape(p unsafe.Pointer) unsafe.Pointer {
29 x := uintptr(p)
30 return unsafe.Pointer(x ^ 0)
31 }
32
33 func (b *Builder) copyCheck() {
34 if b.addr == nil {
35
36
37
38
39
40 b.addr = (*Builder)(noescape(unsafe.Pointer(b)))
41 } else if b.addr != b {
42 panic("strings: illegal use of non-zero Builder copied by value")
43 }
44 }
45
46
47 func (b *Builder) String() string {
48 return *(*string)(unsafe.Pointer(&b.buf))
49 }
50
51
52 func (b *Builder) Len() int { return len(b.buf) }
53
54
55
56
57 func (b *Builder) Cap() int { return cap(b.buf) }
58
59
60 func (b *Builder) Reset() {
61 b.addr = nil
62 b.buf = nil
63 }
64
65
66
67 func (b *Builder) grow(n int) {
68 buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)
69 copy(buf, b.buf)
70 b.buf = buf
71 }
72
73
74
75
76 func (b *Builder) Grow(n int) {
77 b.copyCheck()
78 if n < 0 {
79 panic("strings.Builder.Grow: negative count")
80 }
81 if cap(b.buf)-len(b.buf) < n {
82 b.grow(n)
83 }
84 }
85
86
87
88 func (b *Builder) Write(p []byte) (int, error) {
89 b.copyCheck()
90 b.buf = append(b.buf, p...)
91 return len(p), nil
92 }
93
94
95
96 func (b *Builder) WriteByte(c byte) error {
97 b.copyCheck()
98 b.buf = append(b.buf, c)
99 return nil
100 }
101
102
103
104 func (b *Builder) WriteRune(r rune) (int, error) {
105 b.copyCheck()
106
107 if uint32(r) < utf8.RuneSelf {
108 b.buf = append(b.buf, byte(r))
109 return 1, nil
110 }
111 l := len(b.buf)
112 if cap(b.buf)-l < utf8.UTFMax {
113 b.grow(utf8.UTFMax)
114 }
115 n := utf8.EncodeRune(b.buf[l:l+utf8.UTFMax], r)
116 b.buf = b.buf[:l+n]
117 return n, nil
118 }
119
120
121
122 func (b *Builder) WriteString(s string) (int, error) {
123 b.copyCheck()
124 b.buf = append(b.buf, s...)
125 return len(s), nil
126 }
127
View as plain text