]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/string.go
runtime: use bytes.IndexByte in findnull
[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         "internal/bytealg"
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) (str 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 {
84                 racereadrangepc(unsafe.Pointer(&b[0]),
85                         uintptr(l),
86                         getcallerpc(),
87                         funcPC(slicebytetostring))
88         }
89         if msanenabled {
90                 msanread(unsafe.Pointer(&b[0]), uintptr(l))
91         }
92         if l == 1 {
93                 stringStructOf(&str).str = unsafe.Pointer(&staticbytes[b[0]])
94                 stringStructOf(&str).len = 1
95                 return
96         }
97
98         var p unsafe.Pointer
99         if buf != nil && len(b) <= len(buf) {
100                 p = unsafe.Pointer(buf)
101         } else {
102                 p = mallocgc(uintptr(len(b)), nil, false)
103         }
104         stringStructOf(&str).str = p
105         stringStructOf(&str).len = len(b)
106         memmove(p, (*(*slice)(unsafe.Pointer(&b))).array, uintptr(len(b)))
107         return
108 }
109
110 // stringDataOnStack reports whether the string's data is
111 // stored on the current goroutine's stack.
112 func stringDataOnStack(s string) bool {
113         ptr := uintptr(stringStructOf(&s).str)
114         stk := getg().stack
115         return stk.lo <= ptr && ptr < stk.hi
116 }
117
118 func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
119         if buf != nil && l <= len(buf) {
120                 b = buf[:l]
121                 s = slicebytetostringtmp(b)
122         } else {
123                 s, b = rawstring(l)
124         }
125         return
126 }
127
128 // slicebytetostringtmp returns a "string" referring to the actual []byte bytes.
129 //
130 // Callers need to ensure that the returned string will not be used after
131 // the calling goroutine modifies the original slice or synchronizes with
132 // another goroutine.
133 //
134 // The function is only called when instrumenting
135 // and otherwise intrinsified by the compiler.
136 //
137 // Some internal compiler optimizations use this function.
138 // - Used for m[string(k)] lookup where m is a string-keyed map and k is a []byte.
139 // - Used for "<"+string(b)+">" concatenation where b is []byte.
140 // - Used for string(b)=="foo" comparison where b is []byte.
141 func slicebytetostringtmp(b []byte) string {
142         if raceenabled && len(b) > 0 {
143                 racereadrangepc(unsafe.Pointer(&b[0]),
144                         uintptr(len(b)),
145                         getcallerpc(),
146                         funcPC(slicebytetostringtmp))
147         }
148         if msanenabled && len(b) > 0 {
149                 msanread(unsafe.Pointer(&b[0]), uintptr(len(b)))
150         }
151         return *(*string)(unsafe.Pointer(&b))
152 }
153
154 func stringtoslicebyte(buf *tmpBuf, s string) []byte {
155         var b []byte
156         if buf != nil && len(s) <= len(buf) {
157                 *buf = tmpBuf{}
158                 b = buf[:len(s)]
159         } else {
160                 b = rawbyteslice(len(s))
161         }
162         copy(b, s)
163         return b
164 }
165
166 func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune {
167         // two passes.
168         // unlike slicerunetostring, no race because strings are immutable.
169         n := 0
170         for range s {
171                 n++
172         }
173
174         var a []rune
175         if buf != nil && n <= len(buf) {
176                 *buf = [tmpStringBufSize]rune{}
177                 a = buf[:n]
178         } else {
179                 a = rawruneslice(n)
180         }
181
182         n = 0
183         for _, r := range s {
184                 a[n] = r
185                 n++
186         }
187         return a
188 }
189
190 func slicerunetostring(buf *tmpBuf, a []rune) string {
191         if raceenabled && len(a) > 0 {
192                 racereadrangepc(unsafe.Pointer(&a[0]),
193                         uintptr(len(a))*unsafe.Sizeof(a[0]),
194                         getcallerpc(),
195                         funcPC(slicerunetostring))
196         }
197         if msanenabled && len(a) > 0 {
198                 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
199         }
200         var dum [4]byte
201         size1 := 0
202         for _, r := range a {
203                 size1 += encoderune(dum[:], r)
204         }
205         s, b := rawstringtmp(buf, size1+3)
206         size2 := 0
207         for _, r := range a {
208                 // check for race
209                 if size2 >= size1 {
210                         break
211                 }
212                 size2 += encoderune(b[size2:], r)
213         }
214         return s[:size2]
215 }
216
217 type stringStruct struct {
218         str unsafe.Pointer
219         len int
220 }
221
222 // Variant with *byte pointer type for DWARF debugging.
223 type stringStructDWARF struct {
224         str *byte
225         len int
226 }
227
228 func stringStructOf(sp *string) *stringStruct {
229         return (*stringStruct)(unsafe.Pointer(sp))
230 }
231
232 func intstring(buf *[4]byte, v int64) string {
233         var s string
234         var b []byte
235         if buf != nil {
236                 b = buf[:]
237                 s = slicebytetostringtmp(b)
238         } else {
239                 s, b = rawstring(4)
240         }
241         if int64(rune(v)) != v {
242                 v = runeError
243         }
244         n := encoderune(b, rune(v))
245         return s[:n]
246 }
247
248 // rawstring allocates storage for a new string. The returned
249 // string and byte slice both refer to the same storage.
250 // The storage is not zeroed. Callers should use
251 // b to set the string contents and then drop b.
252 func rawstring(size int) (s string, b []byte) {
253         p := mallocgc(uintptr(size), nil, false)
254
255         stringStructOf(&s).str = p
256         stringStructOf(&s).len = size
257
258         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
259
260         return
261 }
262
263 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
264 func rawbyteslice(size int) (b []byte) {
265         cap := roundupsize(uintptr(size))
266         p := mallocgc(cap, nil, false)
267         if cap != uintptr(size) {
268                 memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size))
269         }
270
271         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
272         return
273 }
274
275 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
276 func rawruneslice(size int) (b []rune) {
277         if uintptr(size) > maxAlloc/4 {
278                 throw("out of memory")
279         }
280         mem := roundupsize(uintptr(size) * 4)
281         p := mallocgc(mem, nil, false)
282         if mem != uintptr(size)*4 {
283                 memclrNoHeapPointers(add(p, uintptr(size)*4), mem-uintptr(size)*4)
284         }
285
286         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
287         return
288 }
289
290 // used by cmd/cgo
291 func gobytes(p *byte, n int) (b []byte) {
292         if n == 0 {
293                 return make([]byte, 0)
294         }
295
296         if n < 0 || uintptr(n) > maxAlloc {
297                 panic(errorString("gobytes: length out of range"))
298         }
299
300         bp := mallocgc(uintptr(n), nil, false)
301         memmove(bp, unsafe.Pointer(p), uintptr(n))
302
303         *(*slice)(unsafe.Pointer(&b)) = slice{bp, n, n}
304         return
305 }
306
307 func gostring(p *byte) string {
308         l := findnull(p)
309         if l == 0 {
310                 return ""
311         }
312         s, b := rawstring(l)
313         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
314         return s
315 }
316
317 func gostringn(p *byte, l int) string {
318         if l == 0 {
319                 return ""
320         }
321         s, b := rawstring(l)
322         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
323         return s
324 }
325
326 func index(s, t string) int {
327         if len(t) == 0 {
328                 return 0
329         }
330         for i := 0; i < len(s); i++ {
331                 if s[i] == t[0] && hasprefix(s[i:], t) {
332                         return i
333                 }
334         }
335         return -1
336 }
337
338 func contains(s, t string) bool {
339         return index(s, t) >= 0
340 }
341
342 func hasprefix(s, t string) bool {
343         return len(s) >= len(t) && s[:len(t)] == t
344 }
345
346 const (
347         maxUint = ^uint(0)
348         maxInt  = int(maxUint >> 1)
349 )
350
351 // atoi parses an int from a string s.
352 // The bool result reports whether s is a number
353 // representable by a value of type int.
354 func atoi(s string) (int, bool) {
355         if s == "" {
356                 return 0, false
357         }
358
359         neg := false
360         if s[0] == '-' {
361                 neg = true
362                 s = s[1:]
363         }
364
365         un := uint(0)
366         for i := 0; i < len(s); i++ {
367                 c := s[i]
368                 if c < '0' || c > '9' {
369                         return 0, false
370                 }
371                 if un > maxUint/10 {
372                         // overflow
373                         return 0, false
374                 }
375                 un *= 10
376                 un1 := un + uint(c) - '0'
377                 if un1 < un {
378                         // overflow
379                         return 0, false
380                 }
381                 un = un1
382         }
383
384         if !neg && un > uint(maxInt) {
385                 return 0, false
386         }
387         if neg && un > uint(maxInt)+1 {
388                 return 0, false
389         }
390
391         n := int(un)
392         if neg {
393                 n = -n
394         }
395
396         return n, true
397 }
398
399 // atoi32 is like atoi but for integers
400 // that fit into an int32.
401 func atoi32(s string) (int32, bool) {
402         if n, ok := atoi(s); n == int(int32(n)) {
403                 return int32(n), ok
404         }
405         return 0, false
406 }
407
408 //go:nosplit
409 func findnull(s *byte) int {
410         if s == nil {
411                 return 0
412         }
413
414         // pageSize is the unit we scan at a time looking for NULL.
415         // It must be the minimum page size for any architecture Go
416         // runs on. It's okay (just a minor performance loss) if the
417         // actual system page size is larger than this value.
418         const pageSize = 4096
419
420         offset := 0
421         ptr := unsafe.Pointer(s)
422         // IndexByteString uses wide reads, so we need to be careful
423         // with page boundaries. Call IndexByteString on
424         // [ptr, endOfPage) interval.
425         safeLen := int(pageSize - uintptr(ptr)%pageSize)
426
427         for {
428                 t := *(*string)(unsafe.Pointer(&stringStruct{ptr, safeLen}))
429                 // Check one page at a time.
430                 if i := bytealg.IndexByteString(t, 0); i != -1 {
431                         return offset + i
432                 }
433                 // Move to next page
434                 ptr = unsafe.Pointer(uintptr(ptr) + uintptr(safeLen))
435                 offset += safeLen
436                 safeLen = pageSize
437         }
438 }
439
440 func findnullw(s *uint16) int {
441         if s == nil {
442                 return 0
443         }
444         p := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(s))
445         l := 0
446         for p[l] != 0 {
447                 l++
448         }
449         return l
450 }
451
452 //go:nosplit
453 func gostringnocopy(str *byte) string {
454         ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
455         s := *(*string)(unsafe.Pointer(&ss))
456         return s
457 }
458
459 func gostringw(strw *uint16) string {
460         var buf [8]byte
461         str := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(strw))
462         n1 := 0
463         for i := 0; str[i] != 0; i++ {
464                 n1 += encoderune(buf[:], rune(str[i]))
465         }
466         s, b := rawstring(n1 + 4)
467         n2 := 0
468         for i := 0; str[i] != 0; i++ {
469                 // check for race
470                 if n2 >= n1 {
471                         break
472                 }
473                 n2 += encoderune(b[n2:], rune(str[i]))
474         }
475         b[n2] = 0 // for luck
476         return s[:n2]
477 }