]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/string.go
runtime: minor string/rune optimizations
[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         t := s
167         for len(s) > 0 {
168                 _, k := charntorune(s)
169                 s = s[k:]
170                 n++
171         }
172         var a []rune
173         if buf != nil && n <= len(buf) {
174                 *buf = [tmpStringBufSize]rune{}
175                 a = buf[:n]
176         } else {
177                 a = rawruneslice(n)
178         }
179         n = 0
180         for len(t) > 0 {
181                 r, k := charntorune(t)
182                 t = t[k:]
183                 a[n] = r
184                 n++
185         }
186         return a
187 }
188
189 func slicerunetostring(buf *tmpBuf, a []rune) string {
190         if raceenabled && len(a) > 0 {
191                 racereadrangepc(unsafe.Pointer(&a[0]),
192                         uintptr(len(a))*unsafe.Sizeof(a[0]),
193                         getcallerpc(unsafe.Pointer(&buf)),
194                         funcPC(slicerunetostring))
195         }
196         if msanenabled && len(a) > 0 {
197                 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
198         }
199         var dum [4]byte
200         size1 := 0
201         for _, r := range a {
202                 size1 += runetochar(dum[:], r)
203         }
204         s, b := rawstringtmp(buf, size1+3)
205         size2 := 0
206         for _, r := range a {
207                 // check for race
208                 if size2 >= size1 {
209                         break
210                 }
211                 size2 += runetochar(b[size2:], r)
212         }
213         return s[:size2]
214 }
215
216 type stringStruct struct {
217         str unsafe.Pointer
218         len int
219 }
220
221 // Variant with *byte pointer type for DWARF debugging.
222 type stringStructDWARF struct {
223         str *byte
224         len int
225 }
226
227 func stringStructOf(sp *string) *stringStruct {
228         return (*stringStruct)(unsafe.Pointer(sp))
229 }
230
231 func intstring(buf *[4]byte, v int64) string {
232         var s string
233         var b []byte
234         if buf != nil {
235                 b = buf[:]
236                 s = slicebytetostringtmp(b)
237         } else {
238                 s, b = rawstring(4)
239         }
240         if int64(rune(v)) != v {
241                 v = runeerror
242         }
243         n := runetochar(b, rune(v))
244         return s[:n]
245 }
246
247 // stringiter returns the index of the next
248 // rune after the rune that starts at s[k].
249 func stringiter(s string, k int) int {
250         if k >= len(s) {
251                 // 0 is end of iteration
252                 return 0
253         }
254
255         c := s[k]
256         if c < runeself {
257                 return k + 1
258         }
259
260         // multi-char rune
261         _, n := charntorune(s[k:])
262         return k + n
263 }
264
265 // stringiter2 returns the rune that starts at s[k]
266 // and the index where the next rune starts.
267 func stringiter2(s string, k int) (int, rune) {
268         if k >= len(s) {
269                 // 0 is end of iteration
270                 return 0, 0
271         }
272
273         c := s[k]
274         if c < runeself {
275                 return k + 1, rune(c)
276         }
277
278         // multi-char rune
279         r, n := charntorune(s[k:])
280         return k + n, r
281 }
282
283 // rawstring allocates storage for a new string. The returned
284 // string and byte slice both refer to the same storage.
285 // The storage is not zeroed. Callers should use
286 // b to set the string contents and then drop b.
287 func rawstring(size int) (s string, b []byte) {
288         p := mallocgc(uintptr(size), nil, false)
289
290         stringStructOf(&s).str = p
291         stringStructOf(&s).len = size
292
293         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
294
295         for {
296                 ms := maxstring
297                 if uintptr(size) <= ms || atomic.Casuintptr((*uintptr)(unsafe.Pointer(&maxstring)), ms, uintptr(size)) {
298                         return
299                 }
300         }
301 }
302
303 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
304 func rawbyteslice(size int) (b []byte) {
305         cap := roundupsize(uintptr(size))
306         p := mallocgc(cap, nil, false)
307         if cap != uintptr(size) {
308                 memclr(add(p, uintptr(size)), cap-uintptr(size))
309         }
310
311         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
312         return
313 }
314
315 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
316 func rawruneslice(size int) (b []rune) {
317         if uintptr(size) > _MaxMem/4 {
318                 throw("out of memory")
319         }
320         mem := roundupsize(uintptr(size) * 4)
321         p := mallocgc(mem, nil, false)
322         if mem != uintptr(size)*4 {
323                 memclr(add(p, uintptr(size)*4), mem-uintptr(size)*4)
324         }
325
326         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
327         return
328 }
329
330 // used by cmd/cgo
331 func gobytes(p *byte, n int) []byte {
332         if n == 0 {
333                 return make([]byte, 0)
334         }
335         x := make([]byte, n)
336         memmove(unsafe.Pointer(&x[0]), unsafe.Pointer(p), uintptr(n))
337         return x
338 }
339
340 func gostring(p *byte) string {
341         l := findnull(p)
342         if l == 0 {
343                 return ""
344         }
345         s, b := rawstring(l)
346         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
347         return s
348 }
349
350 func gostringn(p *byte, l int) string {
351         if l == 0 {
352                 return ""
353         }
354         s, b := rawstring(l)
355         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
356         return s
357 }
358
359 func index(s, t string) int {
360         if len(t) == 0 {
361                 return 0
362         }
363         for i := 0; i < len(s); i++ {
364                 if s[i] == t[0] && hasprefix(s[i:], t) {
365                         return i
366                 }
367         }
368         return -1
369 }
370
371 func contains(s, t string) bool {
372         return index(s, t) >= 0
373 }
374
375 func hasprefix(s, t string) bool {
376         return len(s) >= len(t) && s[:len(t)] == t
377 }
378
379 func atoi(s string) int {
380         n := 0
381         for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
382                 n = n*10 + int(s[0]) - '0'
383                 s = s[1:]
384         }
385         return n
386 }
387
388 //go:nosplit
389 func findnull(s *byte) int {
390         if s == nil {
391                 return 0
392         }
393         p := (*[_MaxMem/2 - 1]byte)(unsafe.Pointer(s))
394         l := 0
395         for p[l] != 0 {
396                 l++
397         }
398         return l
399 }
400
401 func findnullw(s *uint16) int {
402         if s == nil {
403                 return 0
404         }
405         p := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(s))
406         l := 0
407         for p[l] != 0 {
408                 l++
409         }
410         return l
411 }
412
413 var maxstring uintptr = 256 // a hint for print
414
415 //go:nosplit
416 func gostringnocopy(str *byte) string {
417         ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
418         s := *(*string)(unsafe.Pointer(&ss))
419         for {
420                 ms := maxstring
421                 if uintptr(len(s)) <= ms || atomic.Casuintptr(&maxstring, ms, uintptr(len(s))) {
422                         break
423                 }
424         }
425         return s
426 }
427
428 func gostringw(strw *uint16) string {
429         var buf [8]byte
430         str := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(strw))
431         n1 := 0
432         for i := 0; str[i] != 0; i++ {
433                 n1 += runetochar(buf[:], rune(str[i]))
434         }
435         s, b := rawstring(n1 + 4)
436         n2 := 0
437         for i := 0; str[i] != 0; i++ {
438                 // check for race
439                 if n2 >= n1 {
440                         break
441                 }
442                 n2 += runetochar(b[n2:], rune(str[i]))
443         }
444         b[n2] = 0 // for luck
445         return s[:n2]
446 }