]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/string.go
cmd/compile: improve string iteration performance
[gostls13.git] / src / runtime / string.go
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package runtime
6
7 import (
8         "runtime/internal/atomic"
9         "unsafe"
10 )
11
12 // The constant is known to the compiler.
13 // There is no fundamental theory behind this number.
14 const tmpStringBufSize = 32
15
16 type tmpBuf [tmpStringBufSize]byte
17
18 // concatstrings implements a Go string concatenation x+y+z+...
19 // The operands are passed in the slice a.
20 // If buf != nil, the compiler has determined that the result does not
21 // escape the calling function, so the string data can be stored in buf
22 // if small enough.
23 func concatstrings(buf *tmpBuf, a []string) string {
24         idx := 0
25         l := 0
26         count := 0
27         for i, x := range a {
28                 n := len(x)
29                 if n == 0 {
30                         continue
31                 }
32                 if l+n < l {
33                         throw("string concatenation too long")
34                 }
35                 l += n
36                 count++
37                 idx = i
38         }
39         if count == 0 {
40                 return ""
41         }
42
43         // If there is just one string and either it is not on the stack
44         // or our result does not escape the calling frame (buf != nil),
45         // then we can return that string directly.
46         if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
47                 return a[idx]
48         }
49         s, b := rawstringtmp(buf, l)
50         for _, x := range a {
51                 copy(b, x)
52                 b = b[len(x):]
53         }
54         return s
55 }
56
57 func concatstring2(buf *tmpBuf, a [2]string) string {
58         return concatstrings(buf, a[:])
59 }
60
61 func concatstring3(buf *tmpBuf, a [3]string) string {
62         return concatstrings(buf, a[:])
63 }
64
65 func concatstring4(buf *tmpBuf, a [4]string) string {
66         return concatstrings(buf, a[:])
67 }
68
69 func concatstring5(buf *tmpBuf, a [5]string) string {
70         return concatstrings(buf, a[:])
71 }
72
73 // Buf is a fixed-size buffer for the result,
74 // it is not nil if the result does not escape.
75 func slicebytetostring(buf *tmpBuf, b []byte) string {
76         l := len(b)
77         if l == 0 {
78                 // Turns out to be a relatively common case.
79                 // Consider that you want to parse out data between parens in "foo()bar",
80                 // you find the indices and convert the subslice to string.
81                 return ""
82         }
83         if raceenabled && l > 0 {
84                 racereadrangepc(unsafe.Pointer(&b[0]),
85                         uintptr(l),
86                         getcallerpc(unsafe.Pointer(&buf)),
87                         funcPC(slicebytetostring))
88         }
89         if msanenabled && l > 0 {
90                 msanread(unsafe.Pointer(&b[0]), uintptr(l))
91         }
92         s, c := rawstringtmp(buf, l)
93         copy(c, b)
94         return s
95 }
96
97 // stringDataOnStack reports whether the string's data is
98 // stored on the current goroutine's stack.
99 func stringDataOnStack(s string) bool {
100         ptr := uintptr(stringStructOf(&s).str)
101         stk := getg().stack
102         return stk.lo <= ptr && ptr < stk.hi
103 }
104
105 func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
106         if buf != nil && l <= len(buf) {
107                 b = buf[:l]
108                 s = slicebytetostringtmp(b)
109         } else {
110                 s, b = rawstring(l)
111         }
112         return
113 }
114
115 func slicebytetostringtmp(b []byte) string {
116         // Return a "string" referring to the actual []byte bytes.
117         // This is only for use by internal compiler optimizations
118         // that know that the string form will be discarded before
119         // the calling goroutine could possibly modify the original
120         // slice or synchronize with another goroutine.
121         // First such case is a m[string(k)] lookup where
122         // m is a string-keyed map and k is a []byte.
123         // Second such case is "<"+string(b)+">" concatenation where b is []byte.
124         // Third such case is string(b)=="foo" comparison where b is []byte.
125
126         if raceenabled && len(b) > 0 {
127                 racereadrangepc(unsafe.Pointer(&b[0]),
128                         uintptr(len(b)),
129                         getcallerpc(unsafe.Pointer(&b)),
130                         funcPC(slicebytetostringtmp))
131         }
132         if msanenabled && len(b) > 0 {
133                 msanread(unsafe.Pointer(&b[0]), uintptr(len(b)))
134         }
135         return *(*string)(unsafe.Pointer(&b))
136 }
137
138 func stringtoslicebyte(buf *tmpBuf, s string) []byte {
139         var b []byte
140         if buf != nil && len(s) <= len(buf) {
141                 *buf = tmpBuf{}
142                 b = buf[:len(s)]
143         } else {
144                 b = rawbyteslice(len(s))
145         }
146         copy(b, s)
147         return b
148 }
149
150 func stringtoslicebytetmp(s string) []byte {
151         // Return a slice referring to the actual string bytes.
152         // This is only for use by internal compiler optimizations
153         // that know that the slice won't be mutated.
154         // The only such case today is:
155         // for i, c := range []byte(str)
156
157         str := stringStructOf(&s)
158         ret := slice{array: str.str, len: str.len, cap: str.len}
159         return *(*[]byte)(unsafe.Pointer(&ret))
160 }
161
162 func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune {
163         // two passes.
164         // unlike slicerunetostring, no race because strings are immutable.
165         n := 0
166         for range s {
167                 n++
168         }
169
170         var a []rune
171         if buf != nil && n <= len(buf) {
172                 *buf = [tmpStringBufSize]rune{}
173                 a = buf[:n]
174         } else {
175                 a = rawruneslice(n)
176         }
177
178         n = 0
179         for _, r := range s {
180                 a[n] = r
181                 n++
182         }
183         return a
184 }
185
186 func slicerunetostring(buf *tmpBuf, a []rune) string {
187         if raceenabled && len(a) > 0 {
188                 racereadrangepc(unsafe.Pointer(&a[0]),
189                         uintptr(len(a))*unsafe.Sizeof(a[0]),
190                         getcallerpc(unsafe.Pointer(&buf)),
191                         funcPC(slicerunetostring))
192         }
193         if msanenabled && len(a) > 0 {
194                 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
195         }
196         var dum [4]byte
197         size1 := 0
198         for _, r := range a {
199                 size1 += runetochar(dum[:], r)
200         }
201         s, b := rawstringtmp(buf, size1+3)
202         size2 := 0
203         for _, r := range a {
204                 // check for race
205                 if size2 >= size1 {
206                         break
207                 }
208                 size2 += runetochar(b[size2:], r)
209         }
210         return s[:size2]
211 }
212
213 type stringStruct struct {
214         str unsafe.Pointer
215         len int
216 }
217
218 // Variant with *byte pointer type for DWARF debugging.
219 type stringStructDWARF struct {
220         str *byte
221         len int
222 }
223
224 func stringStructOf(sp *string) *stringStruct {
225         return (*stringStruct)(unsafe.Pointer(sp))
226 }
227
228 func intstring(buf *[4]byte, v int64) string {
229         var s string
230         var b []byte
231         if buf != nil {
232                 b = buf[:]
233                 s = slicebytetostringtmp(b)
234         } else {
235                 s, b = rawstring(4)
236         }
237         if int64(rune(v)) != v {
238                 v = runeerror
239         }
240         n := runetochar(b, rune(v))
241         return s[:n]
242 }
243
244 // rawstring allocates storage for a new string. The returned
245 // string and byte slice both refer to the same storage.
246 // The storage is not zeroed. Callers should use
247 // b to set the string contents and then drop b.
248 func rawstring(size int) (s string, b []byte) {
249         p := mallocgc(uintptr(size), nil, false)
250
251         stringStructOf(&s).str = p
252         stringStructOf(&s).len = size
253
254         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
255
256         for {
257                 ms := maxstring
258                 if uintptr(size) <= ms || atomic.Casuintptr((*uintptr)(unsafe.Pointer(&maxstring)), ms, uintptr(size)) {
259                         return
260                 }
261         }
262 }
263
264 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
265 func rawbyteslice(size int) (b []byte) {
266         cap := roundupsize(uintptr(size))
267         p := mallocgc(cap, nil, false)
268         if cap != uintptr(size) {
269                 memclr(add(p, uintptr(size)), cap-uintptr(size))
270         }
271
272         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
273         return
274 }
275
276 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
277 func rawruneslice(size int) (b []rune) {
278         if uintptr(size) > _MaxMem/4 {
279                 throw("out of memory")
280         }
281         mem := roundupsize(uintptr(size) * 4)
282         p := mallocgc(mem, nil, false)
283         if mem != uintptr(size)*4 {
284                 memclr(add(p, uintptr(size)*4), mem-uintptr(size)*4)
285         }
286
287         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
288         return
289 }
290
291 // used by cmd/cgo
292 func gobytes(p *byte, n int) []byte {
293         if n == 0 {
294                 return make([]byte, 0)
295         }
296         x := make([]byte, n)
297         memmove(unsafe.Pointer(&x[0]), unsafe.Pointer(p), uintptr(n))
298         return x
299 }
300
301 func gostring(p *byte) string {
302         l := findnull(p)
303         if l == 0 {
304                 return ""
305         }
306         s, b := rawstring(l)
307         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
308         return s
309 }
310
311 func gostringn(p *byte, l int) string {
312         if l == 0 {
313                 return ""
314         }
315         s, b := rawstring(l)
316         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
317         return s
318 }
319
320 func index(s, t string) int {
321         if len(t) == 0 {
322                 return 0
323         }
324         for i := 0; i < len(s); i++ {
325                 if s[i] == t[0] && hasprefix(s[i:], t) {
326                         return i
327                 }
328         }
329         return -1
330 }
331
332 func contains(s, t string) bool {
333         return index(s, t) >= 0
334 }
335
336 func hasprefix(s, t string) bool {
337         return len(s) >= len(t) && s[:len(t)] == t
338 }
339
340 func atoi(s string) int {
341         n := 0
342         for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
343                 n = n*10 + int(s[0]) - '0'
344                 s = s[1:]
345         }
346         return n
347 }
348
349 //go:nosplit
350 func findnull(s *byte) int {
351         if s == nil {
352                 return 0
353         }
354         p := (*[_MaxMem/2 - 1]byte)(unsafe.Pointer(s))
355         l := 0
356         for p[l] != 0 {
357                 l++
358         }
359         return l
360 }
361
362 func findnullw(s *uint16) int {
363         if s == nil {
364                 return 0
365         }
366         p := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(s))
367         l := 0
368         for p[l] != 0 {
369                 l++
370         }
371         return l
372 }
373
374 var maxstring uintptr = 256 // a hint for print
375
376 //go:nosplit
377 func gostringnocopy(str *byte) string {
378         ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
379         s := *(*string)(unsafe.Pointer(&ss))
380         for {
381                 ms := maxstring
382                 if uintptr(len(s)) <= ms || atomic.Casuintptr(&maxstring, ms, uintptr(len(s))) {
383                         break
384                 }
385         }
386         return s
387 }
388
389 func gostringw(strw *uint16) string {
390         var buf [8]byte
391         str := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(strw))
392         n1 := 0
393         for i := 0; str[i] != 0; i++ {
394                 n1 += runetochar(buf[:], rune(str[i]))
395         }
396         s, b := rawstring(n1 + 4)
397         n2 := 0
398         for i := 0; str[i] != 0; i++ {
399                 // check for race
400                 if n2 >= n1 {
401                         break
402                 }
403                 n2 += runetochar(b[n2:], rune(str[i]))
404         }
405         b[n2] = 0 // for luck
406         return s[:n2]
407 }