]> 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 "unsafe"
8
9 // The constant is known to the compiler.
10 // There is no fundamental theory behind this number.
11 const tmpStringBufSize = 32
12
13 type tmpBuf [tmpStringBufSize]byte
14
15 // concatstrings implements a Go string concatenation x+y+z+...
16 // The operands are passed in the slice a.
17 // If buf != nil, the compiler has determined that the result does not
18 // escape the calling function, so the string data can be stored in buf
19 // if small enough.
20 func concatstrings(buf *tmpBuf, a []string) string {
21         idx := 0
22         l := 0
23         count := 0
24         for i, x := range a {
25                 n := len(x)
26                 if n == 0 {
27                         continue
28                 }
29                 if l+n < l {
30                         throw("string concatenation too long")
31                 }
32                 l += n
33                 count++
34                 idx = i
35         }
36         if count == 0 {
37                 return ""
38         }
39
40         // If there is just one string and either it is not on the stack
41         // or our result does not escape the calling frame (buf != nil),
42         // then we can return that string directly.
43         if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {
44                 return a[idx]
45         }
46         s, b := rawstringtmp(buf, l)
47         for _, x := range a {
48                 copy(b, x)
49                 b = b[len(x):]
50         }
51         return s
52 }
53
54 func concatstring2(buf *tmpBuf, a [2]string) string {
55         return concatstrings(buf, a[:])
56 }
57
58 func concatstring3(buf *tmpBuf, a [3]string) string {
59         return concatstrings(buf, a[:])
60 }
61
62 func concatstring4(buf *tmpBuf, a [4]string) string {
63         return concatstrings(buf, a[:])
64 }
65
66 func concatstring5(buf *tmpBuf, a [5]string) string {
67         return concatstrings(buf, a[:])
68 }
69
70 // Buf is a fixed-size buffer for the result,
71 // it is not nil if the result does not escape.
72 func slicebytetostring(buf *tmpBuf, b []byte) (str string) {
73         l := len(b)
74         if l == 0 {
75                 // Turns out to be a relatively common case.
76                 // Consider that you want to parse out data between parens in "foo()bar",
77                 // you find the indices and convert the subslice to string.
78                 return ""
79         }
80         if raceenabled {
81                 racereadrangepc(unsafe.Pointer(&b[0]),
82                         uintptr(l),
83                         getcallerpc(),
84                         funcPC(slicebytetostring))
85         }
86         if msanenabled {
87                 msanread(unsafe.Pointer(&b[0]), uintptr(l))
88         }
89         if l == 1 {
90                 stringStructOf(&str).str = unsafe.Pointer(&staticbytes[b[0]])
91                 stringStructOf(&str).len = 1
92                 return
93         }
94
95         var p unsafe.Pointer
96         if buf != nil && len(b) <= len(buf) {
97                 p = unsafe.Pointer(buf)
98         } else {
99                 p = mallocgc(uintptr(len(b)), nil, false)
100         }
101         stringStructOf(&str).str = p
102         stringStructOf(&str).len = len(b)
103         memmove(p, (*(*slice)(unsafe.Pointer(&b))).array, uintptr(len(b)))
104         return
105 }
106
107 // stringDataOnStack reports whether the string's data is
108 // stored on the current goroutine's stack.
109 func stringDataOnStack(s string) bool {
110         ptr := uintptr(stringStructOf(&s).str)
111         stk := getg().stack
112         return stk.lo <= ptr && ptr < stk.hi
113 }
114
115 func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
116         if buf != nil && l <= len(buf) {
117                 b = buf[:l]
118                 s = slicebytetostringtmp(b)
119         } else {
120                 s, b = rawstring(l)
121         }
122         return
123 }
124
125 // slicebytetostringtmp returns a "string" referring to the actual []byte bytes.
126 //
127 // Callers need to ensure that the returned string will not be used after
128 // the calling goroutine modifies the original slice or synchronizes with
129 // another goroutine.
130 //
131 // The function is only called when instrumenting
132 // and otherwise intrinsified by the compiler.
133 //
134 // Some internal compiler optimizations use this function.
135 // - Used for m[string(k)] lookup where m is a string-keyed map and k is a []byte.
136 // - Used for "<"+string(b)+">" concatenation where b is []byte.
137 // - Used for string(b)=="foo" comparison where b is []byte.
138 func slicebytetostringtmp(b []byte) string {
139         if raceenabled && len(b) > 0 {
140                 racereadrangepc(unsafe.Pointer(&b[0]),
141                         uintptr(len(b)),
142                         getcallerpc(),
143                         funcPC(slicebytetostringtmp))
144         }
145         if msanenabled && len(b) > 0 {
146                 msanread(unsafe.Pointer(&b[0]), uintptr(len(b)))
147         }
148         return *(*string)(unsafe.Pointer(&b))
149 }
150
151 func stringtoslicebyte(buf *tmpBuf, s string) []byte {
152         var b []byte
153         if buf != nil && len(s) <= len(buf) {
154                 *buf = tmpBuf{}
155                 b = buf[:len(s)]
156         } else {
157                 b = rawbyteslice(len(s))
158         }
159         copy(b, s)
160         return b
161 }
162
163 func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune {
164         // two passes.
165         // unlike slicerunetostring, no race because strings are immutable.
166         n := 0
167         for range s {
168                 n++
169         }
170
171         var a []rune
172         if buf != nil && n <= len(buf) {
173                 *buf = [tmpStringBufSize]rune{}
174                 a = buf[:n]
175         } else {
176                 a = rawruneslice(n)
177         }
178
179         n = 0
180         for _, r := range s {
181                 a[n] = r
182                 n++
183         }
184         return a
185 }
186
187 func slicerunetostring(buf *tmpBuf, a []rune) string {
188         if raceenabled && len(a) > 0 {
189                 racereadrangepc(unsafe.Pointer(&a[0]),
190                         uintptr(len(a))*unsafe.Sizeof(a[0]),
191                         getcallerpc(),
192                         funcPC(slicerunetostring))
193         }
194         if msanenabled && len(a) > 0 {
195                 msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
196         }
197         var dum [4]byte
198         size1 := 0
199         for _, r := range a {
200                 size1 += encoderune(dum[:], r)
201         }
202         s, b := rawstringtmp(buf, size1+3)
203         size2 := 0
204         for _, r := range a {
205                 // check for race
206                 if size2 >= size1 {
207                         break
208                 }
209                 size2 += encoderune(b[size2:], r)
210         }
211         return s[:size2]
212 }
213
214 type stringStruct struct {
215         str unsafe.Pointer
216         len int
217 }
218
219 // Variant with *byte pointer type for DWARF debugging.
220 type stringStructDWARF struct {
221         str *byte
222         len int
223 }
224
225 func stringStructOf(sp *string) *stringStruct {
226         return (*stringStruct)(unsafe.Pointer(sp))
227 }
228
229 func intstring(buf *[4]byte, v int64) string {
230         var s string
231         var b []byte
232         if buf != nil {
233                 b = buf[:]
234                 s = slicebytetostringtmp(b)
235         } else {
236                 s, b = rawstring(4)
237         }
238         if int64(rune(v)) != v {
239                 v = runeError
240         }
241         n := encoderune(b, rune(v))
242         return s[:n]
243 }
244
245 // rawstring allocates storage for a new string. The returned
246 // string and byte slice both refer to the same storage.
247 // The storage is not zeroed. Callers should use
248 // b to set the string contents and then drop b.
249 func rawstring(size int) (s string, b []byte) {
250         p := mallocgc(uintptr(size), nil, false)
251
252         stringStructOf(&s).str = p
253         stringStructOf(&s).len = size
254
255         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
256
257         return
258 }
259
260 // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
261 func rawbyteslice(size int) (b []byte) {
262         cap := roundupsize(uintptr(size))
263         p := mallocgc(cap, nil, false)
264         if cap != uintptr(size) {
265                 memclrNoHeapPointers(add(p, uintptr(size)), cap-uintptr(size))
266         }
267
268         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
269         return
270 }
271
272 // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
273 func rawruneslice(size int) (b []rune) {
274         if uintptr(size) > maxAlloc/4 {
275                 throw("out of memory")
276         }
277         mem := roundupsize(uintptr(size) * 4)
278         p := mallocgc(mem, nil, false)
279         if mem != uintptr(size)*4 {
280                 memclrNoHeapPointers(add(p, uintptr(size)*4), mem-uintptr(size)*4)
281         }
282
283         *(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
284         return
285 }
286
287 // used by cmd/cgo
288 func gobytes(p *byte, n int) (b []byte) {
289         if n == 0 {
290                 return make([]byte, 0)
291         }
292
293         if n < 0 || uintptr(n) > maxAlloc {
294                 panic(errorString("gobytes: length out of range"))
295         }
296
297         bp := mallocgc(uintptr(n), nil, false)
298         memmove(bp, unsafe.Pointer(p), uintptr(n))
299
300         *(*slice)(unsafe.Pointer(&b)) = slice{bp, n, n}
301         return
302 }
303
304 func gostring(p *byte) string {
305         l := findnull(p)
306         if l == 0 {
307                 return ""
308         }
309         s, b := rawstring(l)
310         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
311         return s
312 }
313
314 func gostringn(p *byte, l int) string {
315         if l == 0 {
316                 return ""
317         }
318         s, b := rawstring(l)
319         memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
320         return s
321 }
322
323 func index(s, t string) int {
324         if len(t) == 0 {
325                 return 0
326         }
327         for i := 0; i < len(s); i++ {
328                 if s[i] == t[0] && hasprefix(s[i:], t) {
329                         return i
330                 }
331         }
332         return -1
333 }
334
335 func contains(s, t string) bool {
336         return index(s, t) >= 0
337 }
338
339 func hasprefix(s, t string) bool {
340         return len(s) >= len(t) && s[:len(t)] == t
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         ss := stringStruct{unsafe.Pointer(s), maxAlloc/2 - 1}
411         t := *(*string)(unsafe.Pointer(&ss))
412         return stringsIndexByte(t, 0)
413 }
414
415 func findnullw(s *uint16) int {
416         if s == nil {
417                 return 0
418         }
419         p := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(s))
420         l := 0
421         for p[l] != 0 {
422                 l++
423         }
424         return l
425 }
426
427 //go:nosplit
428 func gostringnocopy(str *byte) string {
429         ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
430         s := *(*string)(unsafe.Pointer(&ss))
431         return s
432 }
433
434 func gostringw(strw *uint16) string {
435         var buf [8]byte
436         str := (*[maxAlloc/2/2 - 1]uint16)(unsafe.Pointer(strw))
437         n1 := 0
438         for i := 0; str[i] != 0; i++ {
439                 n1 += encoderune(buf[:], rune(str[i]))
440         }
441         s, b := rawstring(n1 + 4)
442         n2 := 0
443         for i := 0; str[i] != 0; i++ {
444                 // check for race
445                 if n2 >= n1 {
446                         break
447                 }
448                 n2 += encoderune(b[n2:], rune(str[i]))
449         }
450         b[n2] = 0 // for luck
451         return s[:n2]
452 }