]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/string.go
[dev.typeparams] all: merge master (2725522) into dev.typeparams
[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/abi"
9         "internal/bytealg"
10         "runtime/internal/sys"
11         "unsafe"
12 )
13
14 // The constant is known to the compiler.
15 // There is no fundamental theory behind this number.
16 const tmpStringBufSize = 32
17
18 type tmpBuf [tmpStringBufSize]byte
19
20 // concatstrings implements a Go string concatenation x+y+z+...
21 // The operands are passed in the slice a.
22 // If buf != nil, the compiler has determined that the result does not
23 // escape the calling function, so the string data can be stored in buf
24 // if small enough.
25 func concatstrings(buf *tmpBuf, a []string) string {
26         idx := 0
27         l := 0
28         count := 0
29         for i, x := range a {
30                 n := len(x)
31                 if n == 0 {
32                         continue
33                 }
34                 if l+n < l {
35                         throw("string concatenation too long")
36                 }
37                 l += n
38                 count++
39                 idx = i
40         }
41         if count == 0 {
42                 return ""
43         }
44
45         // If there is just one string and either it is not on the stack
46         // or our result does not escape the calling frame (buf != nil),
47         // then we can return that string directly.
48         if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
49                 return a[idx]
50         }
51         s, b := rawstringtmp(buf, l)
52         for _, x := range a {
53                 copy(b, x)
54                 b = b[len(x):]
55         }
56         return s
57 }
58
59 func concatstring2(buf *tmpBuf, a0, a1 string) string {
60         return concatstrings(buf, []string{a0, a1})
61 }
62
63 func concatstring3(buf *tmpBuf, a0, a1, a2 string) string {
64         return concatstrings(buf, []string{a0, a1, a2})
65 }
66
67 func concatstring4(buf *tmpBuf, a0, a1, a2, a3 string) string {
68         return concatstrings(buf, []string{a0, a1, a2, a3})
69 }
70
71 func concatstring5(buf *tmpBuf, a0, a1, a2, a3, a4 string) string {
72         return concatstrings(buf, []string{a0, a1, a2, a3, a4})
73 }
74
75 // slicebytetostring converts a byte slice to a string.
76 // It is inserted by the compiler into generated code.
77 // ptr is a pointer to the first element of the slice;
78 // n is the length of the slice.
79 // Buf is a fixed-size buffer for the result,
80 // it is not nil if the result does not escape.
81 func slicebytetostring(buf *tmpBuf, ptr *byte, n int) (str string) {
82         if n == 0 {
83                 // Turns out to be a relatively common case.
84                 // Consider that you want to parse out data between parens in "foo()bar",
85                 // you find the indices and convert the subslice to string.
86                 return ""
87         }
88         if raceenabled {
89                 racereadrangepc(unsafe.Pointer(ptr),
90                         uintptr(n),
91                         getcallerpc(),
92                         abi.FuncPCABIInternal(slicebytetostring))
93         }
94         if msanenabled {
95                 msanread(unsafe.Pointer(ptr), uintptr(n))
96         }
97         if n == 1 {
98                 p := unsafe.Pointer(&staticuint64s[*ptr])
99                 if sys.BigEndian {
100                         p = add(p, 7)
101                 }
102                 stringStructOf(&str).str = p
103                 stringStructOf(&str).len = 1
104                 return
105         }
106
107         var p unsafe.Pointer
108         if buf != nil && n <= len(buf) {
109                 p = unsafe.Pointer(buf)
110         } else {
111                 p = mallocgc(uintptr(n), nil, false)
112         }
113         stringStructOf(&str).str = p
114         stringStructOf(&str).len = n
115         memmove(p, unsafe.Pointer(ptr), uintptr(n))
116         return
117 }
118
119 // stringDataOnStack reports whether the string's data is
120 // stored on the current goroutine's stack.
121 func stringDataOnStack(s string) bool {
122         ptr := uintptr(stringStructOf(&s).str)
123         stk := getg().stack
124         return stk.lo <= ptr && ptr < stk.hi
125 }
126
127 func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
128         if buf != nil && l <= len(buf) {
129                 b = buf[:l]
130                 s = slicebytetostringtmp(&b[0], len(b))
131         } else {
132                 s, b = rawstring(l)
133         }
134         return
135 }
136
137 // slicebytetostringtmp returns a "string" referring to the actual []byte bytes.
138 //
139 // Callers need to ensure that the returned string will not be used after
140 // the calling goroutine modifies the original slice or synchronizes with
141 // another goroutine.
142 //
143 // The function is only called when instrumenting
144 // and otherwise intrinsified by the compiler.
145 //
146 // Some internal compiler optimizations use this function.
147 // - Used for m[T1{... Tn{..., string(k), ...} ...}] and m[string(k)]
148 //   where k is []byte, T1 to Tn is a nesting of struct and array literals.
149 // - Used for "<"+string(b)+">" concatenation where b is []byte.
150 // - Used for string(b)=="foo" comparison where b is []byte.
151 func slicebytetostringtmp(ptr *byte, n int) (str string) {
152         if raceenabled && n > 0 {
153                 racereadrangepc(unsafe.Pointer(ptr),
154                         uintptr(n),
155                         getcallerpc(),
156                         abi.FuncPCABIInternal(slicebytetostringtmp))
157         }
158         if msanenabled && n > 0 {
159                 msanread(unsafe.Pointer(ptr), uintptr(n))
160         }
161         stringStructOf(&str).str = unsafe.Pointer(ptr)
162         stringStructOf(&str).len = n
163         return
164 }
165
166 func stringtoslicebyte(buf *tmpBuf, s string) []byte {
167         var b []byte
168         if buf != nil && len(s) <= len(buf) {
169                 *buf = tmpBuf{}
170                 b = buf[:len(s)]
171         } else {
172                 b = rawbyteslice(len(s))
173         }
174         copy(b, s)
175         return b
176 }
177
178 func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune {
179         // two passes.
180         // unlike slicerunetostring, no race because strings are immutable.
181         n := 0
182         for range s {
183                 n++
184         }
185
186         var a []rune
187         if buf != nil && n <= len(buf) {
188                 *buf = [tmpStringBufSize]rune{}
189                 a = buf[:n]
190         } else {
191                 a = rawruneslice(n)
192         }
193
194         n = 0
195         for _, r := range s {
196                 a[n] = r
197                 n++
198         }
199         return a
200 }
201
202 func slicerunetostring(buf *tmpBuf, a []rune) string {
203         if raceenabled && len(a) > 0 {
204                 racereadrangepc(unsafe.Pointer(&a[0]),
205                         uintptr(len(a))*unsafe.Sizeof(a[0]),
206                         getcallerpc(),
207                         abi.FuncPCABIInternal(slicerunetostring))
208         }
209         if msanenabled && len(a) > 0 {
210                 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
211         }
212         var dum [4]byte
213         size1 := 0
214         for _, r := range a {
215                 size1 += encoderune(dum[:], r)
216         }
217         s, b := rawstringtmp(buf, size1+3)
218         size2 := 0
219         for _, r := range a {
220                 // check for race
221                 if size2 >= size1 {
222                         break
223                 }
224                 size2 += encoderune(b[size2:], r)
225         }
226         return s[:size2]
227 }
228
229 type stringStruct struct {
230         str unsafe.Pointer
231         len int
232 }
233
234 // Variant with *byte pointer type for DWARF debugging.
235 type stringStructDWARF struct {
236         str *byte
237         len int
238 }
239
240 func stringStructOf(sp *string) *stringStruct {
241         return (*stringStruct)(unsafe.Pointer(sp))
242 }
243
244 func intstring(buf *[4]byte, v int64) (s string) {
245         var b []byte
246         if buf != nil {
247                 b = buf[:]
248                 s = slicebytetostringtmp(&b[0], len(b))
249         } else {
250                 s, b = rawstring(4)
251         }
252         if int64(rune(v)) != v {
253                 v = runeError
254         }
255         n := encoderune(b, rune(v))
256         return s[:n]
257 }
258
259 // rawstring allocates storage for a new string. The returned
260 // string and byte slice both refer to the same storage.
261 // The storage is not zeroed. Callers should use
262 // b to set the string contents and then drop b.
263 func rawstring(size int) (s string, b []byte) {
264         p := mallocgc(uintptr(size), nil, false)
265
266         stringStructOf(&s).str = p
267         stringStructOf(&s).len = size
268
269         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
270
271         return
272 }
273
274 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
275 func rawbyteslice(size int) (b []byte) {
276         cap := roundupsize(uintptr(size))
277         p := mallocgc(cap, nil, false)
278         if cap != uintptr(size) {
279                 memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size))
280         }
281
282         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
283         return
284 }
285
286 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
287 func rawruneslice(size int) (b []rune) {
288         if uintptr(size) > maxAlloc/4 {
289                 throw("out of memory")
290         }
291         mem := roundupsize(uintptr(size) * 4)
292         p := mallocgc(mem, nil, false)
293         if mem != uintptr(size)*4 {
294                 memclrNoHeapPointers(add(p, uintptr(size)*4), mem-uintptr(size)*4)
295         }
296
297         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
298         return
299 }
300
301 // used by cmd/cgo
302 func gobytes(p *byte, n int) (b []byte) {
303         if n == 0 {
304                 return make([]byte, 0)
305         }
306
307         if n < 0 || uintptr(n) > maxAlloc {
308                 panic(errorString("gobytes: length out of range"))
309         }
310
311         bp := mallocgc(uintptr(n), nil, false)
312         memmove(bp, unsafe.Pointer(p), uintptr(n))
313
314         *(*slice)(unsafe.Pointer(&b)) = slice{bp, n, n}
315         return
316 }
317
318 // This is exported via linkname to assembly in syscall (for Plan9).
319 //go:linkname gostring
320 func gostring(p *byte) string {
321         l := findnull(p)
322         if l == 0 {
323                 return ""
324         }
325         s, b := rawstring(l)
326         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
327         return s
328 }
329
330 func gostringn(p *byte, l int) string {
331         if l == 0 {
332                 return ""
333         }
334         s, b := rawstring(l)
335         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
336         return s
337 }
338
339 func hasPrefix(s, prefix string) bool {
340         return len(s) >= len(prefix) && s[:len(prefix)] == prefix
341 }
342
343 const (
344         maxUint = ^uint(0)
345         maxInt  = int(maxUint >> 1)
346 )
347
348 // atoi parses an int from a string s.
349 // The bool result reports whether s is a number
350 // representable by a value of type int.
351 func atoi(s string) (int, bool) {
352         if s == "" {
353                 return 0, false
354         }
355
356         neg := false
357         if s[0] == '-' {
358                 neg = true
359                 s = s[1:]
360         }
361
362         un := uint(0)
363         for i := 0; i < len(s); i++ {
364                 c := s[i]
365                 if c < '0' || c > '9' {
366                         return 0, false
367                 }
368                 if un > maxUint/10 {
369                         // overflow
370                         return 0, false
371                 }
372                 un *= 10
373                 un1 := un + uint(c) - '0'
374                 if un1 < un {
375                         // overflow
376                         return 0, false
377                 }
378                 un = un1
379         }
380
381         if !neg && un > uint(maxInt) {
382                 return 0, false
383         }
384         if neg && un > uint(maxInt)+1 {
385                 return 0, false
386         }
387
388         n := int(un)
389         if neg {
390                 n = -n
391         }
392
393         return n, true
394 }
395
396 // atoi32 is like atoi but for integers
397 // that fit into an int32.
398 func atoi32(s string) (int32, bool) {
399         if n, ok := atoi(s); n == int(int32(n)) {
400                 return int32(n), ok
401         }
402         return 0, false
403 }
404
405 //go:nosplit
406 func findnull(s *byte) int {
407         if s == nil {
408                 return 0
409         }
410
411         // Avoid IndexByteString on Plan 9 because it uses SSE instructions
412         // on x86 machines, and those are classified as floating point instructions,
413         // which are illegal in a note handler.
414         if GOOS == "plan9" {
415                 p := (*[maxAlloc/2 - 1]byte)(unsafe.Pointer(s))
416                 l := 0
417                 for p[l] != 0 {
418                         l++
419                 }
420                 return l
421         }
422
423         // pageSize is the unit we scan at a time looking for NULL.
424         // It must be the minimum page size for any architecture Go
425         // runs on. It's okay (just a minor performance loss) if the
426         // actual system page size is larger than this value.
427         const pageSize = 4096
428
429         offset := 0
430         ptr := unsafe.Pointer(s)
431         // IndexByteString uses wide reads, so we need to be careful
432         // with page boundaries. Call IndexByteString on
433         // [ptr, endOfPage) interval.
434         safeLen := int(pageSize - uintptr(ptr)%pageSize)
435
436         for {
437                 t := *(*string)(unsafe.Pointer(&stringStruct{ptr, safeLen}))
438                 // Check one page at a time.
439                 if i := bytealg.IndexByteString(t, 0); i != -1 {
440                         return offset + i
441                 }
442                 // Move to next page
443                 ptr = unsafe.Pointer(uintptr(ptr) + uintptr(safeLen))
444                 offset += safeLen
445                 safeLen = pageSize
446         }
447 }
448
449 func findnullw(s *uint16) int {
450         if s == nil {
451                 return 0
452         }
453         p := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(s))
454         l := 0
455         for p[l] != 0 {
456                 l++
457         }
458         return l
459 }
460
461 //go:nosplit
462 func gostringnocopy(str *byte) string {
463         ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
464         s := *(*string)(unsafe.Pointer(&ss))
465         return s
466 }
467
468 func gostringw(strw *uint16) string {
469         var buf [8]byte
470         str := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(strw))
471         n1 := 0
472         for i := 0; str[i] != 0; i++ {
473                 n1 += encoderune(buf[:], rune(str[i]))
474         }
475         s, b := rawstring(n1 + 4)
476         n2 := 0
477         for i := 0; str[i] != 0; i++ {
478                 // check for race
479                 if n2 >= n1 {
480                         break
481                 }
482                 n2 += encoderune(b[n2:], rune(str[i]))
483         }
484         b[n2] = 0 // for luck
485         return s[:n2]
486 }