github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/runtime/string.go (about)

     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  	l = 0
    51  	for _, x := range a {
    52  		copy(b[l:], x)
    53  		l += len(x)
    54  	}
    55  	return s
    56  }
    57  
    58  func concatstring2(buf *tmpBuf, a [2]string) string {
    59  	return concatstrings(buf, a[:])
    60  }
    61  
    62  func concatstring3(buf *tmpBuf, a [3]string) string {
    63  	return concatstrings(buf, a[:])
    64  }
    65  
    66  func concatstring4(buf *tmpBuf, a [4]string) string {
    67  	return concatstrings(buf, a[:])
    68  }
    69  
    70  func concatstring5(buf *tmpBuf, a [5]string) string {
    71  	return concatstrings(buf, a[:])
    72  }
    73  
    74  // Buf is a fixed-size buffer for the result,
    75  // it is not nil if the result does not escape.
    76  func slicebytetostring(buf *tmpBuf, b []byte) string {
    77  	l := len(b)
    78  	if l == 0 {
    79  		// Turns out to be a relatively common case.
    80  		// Consider that you want to parse out data between parens in "foo()bar",
    81  		// you find the indices and convert the subslice to string.
    82  		return ""
    83  	}
    84  	if raceenabled && l > 0 {
    85  		racereadrangepc(unsafe.Pointer(&b[0]),
    86  			uintptr(l),
    87  			getcallerpc(unsafe.Pointer(&b)),
    88  			funcPC(slicebytetostring))
    89  	}
    90  	if msanenabled && l > 0 {
    91  		msanread(unsafe.Pointer(&b[0]), uintptr(l))
    92  	}
    93  	s, c := rawstringtmp(buf, l)
    94  	copy(c, b)
    95  	return s
    96  }
    97  
    98  // stringDataOnStack reports whether the string's data is
    99  // stored on the current goroutine's stack.
   100  func stringDataOnStack(s string) bool {
   101  	ptr := uintptr(stringStructOf(&s).str)
   102  	stk := getg().stack
   103  	return stk.lo <= ptr && ptr < stk.hi
   104  }
   105  
   106  func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {
   107  	if buf != nil && l <= len(buf) {
   108  		b = buf[:l]
   109  		s = slicebytetostringtmp(b)
   110  	} else {
   111  		s, b = rawstring(l)
   112  	}
   113  	return
   114  }
   115  
   116  func slicebytetostringtmp(b []byte) string {
   117  	// Return a "string" referring to the actual []byte bytes.
   118  	// This is only for use by internal compiler optimizations
   119  	// that know that the string form will be discarded before
   120  	// the calling goroutine could possibly modify the original
   121  	// slice or synchronize with another goroutine.
   122  	// First such case is a m[string(k)] lookup where
   123  	// m is a string-keyed map and k is a []byte.
   124  	// Second such case is "<"+string(b)+">" concatenation where b is []byte.
   125  	// Third such case is string(b)=="foo" comparison where b is []byte.
   126  
   127  	if raceenabled && len(b) > 0 {
   128  		racereadrangepc(unsafe.Pointer(&b[0]),
   129  			uintptr(len(b)),
   130  			getcallerpc(unsafe.Pointer(&b)),
   131  			funcPC(slicebytetostringtmp))
   132  	}
   133  	if msanenabled && len(b) > 0 {
   134  		msanread(unsafe.Pointer(&b[0]), uintptr(len(b)))
   135  	}
   136  	return *(*string)(unsafe.Pointer(&b))
   137  }
   138  
   139  func stringtoslicebyte(buf *tmpBuf, s string) []byte {
   140  	var b []byte
   141  	if buf != nil && len(s) <= len(buf) {
   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: unsafe.Pointer(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  		a = buf[:n]
   175  	} else {
   176  		a = rawruneslice(n)
   177  	}
   178  	n = 0
   179  	for len(t) > 0 {
   180  		r, k := charntorune(t)
   181  		t = t[k:]
   182  		a[n] = r
   183  		n++
   184  	}
   185  	return a
   186  }
   187  
   188  func slicerunetostring(buf *tmpBuf, a []rune) string {
   189  	if raceenabled && len(a) > 0 {
   190  		racereadrangepc(unsafe.Pointer(&a[0]),
   191  			uintptr(len(a))*unsafe.Sizeof(a[0]),
   192  			getcallerpc(unsafe.Pointer(&a)),
   193  			funcPC(slicerunetostring))
   194  	}
   195  	if msanenabled && len(a) > 0 {
   196  		msanread(unsafe.Pointer(&a[0]), uintptr(len(a))*unsafe.Sizeof(a[0]))
   197  	}
   198  	var dum [4]byte
   199  	size1 := 0
   200  	for _, r := range a {
   201  		size1 += runetochar(dum[:], r)
   202  	}
   203  	s, b := rawstringtmp(buf, size1+3)
   204  	size2 := 0
   205  	for _, r := range a {
   206  		// check for race
   207  		if size2 >= size1 {
   208  			break
   209  		}
   210  		size2 += runetochar(b[size2:], r)
   211  	}
   212  	return s[:size2]
   213  }
   214  
   215  type stringStruct struct {
   216  	str unsafe.Pointer
   217  	len int
   218  }
   219  
   220  // Variant with *byte pointer type for DWARF debugging.
   221  type stringStructDWARF struct {
   222  	str *byte
   223  	len int
   224  }
   225  
   226  func stringStructOf(sp *string) *stringStruct {
   227  	return (*stringStruct)(unsafe.Pointer(sp))
   228  }
   229  
   230  func intstring(buf *[4]byte, v int64) string {
   231  	var s string
   232  	var b []byte
   233  	if buf != nil {
   234  		b = buf[:]
   235  		s = slicebytetostringtmp(b)
   236  	} else {
   237  		s, b = rawstring(4)
   238  	}
   239  	n := runetochar(b, rune(v))
   240  	return s[:n]
   241  }
   242  
   243  // stringiter returns the index of the next
   244  // rune after the rune that starts at s[k].
   245  func stringiter(s string, k int) int {
   246  	if k >= len(s) {
   247  		// 0 is end of iteration
   248  		return 0
   249  	}
   250  
   251  	c := s[k]
   252  	if c < runeself {
   253  		return k + 1
   254  	}
   255  
   256  	// multi-char rune
   257  	_, n := charntorune(s[k:])
   258  	return k + n
   259  }
   260  
   261  // stringiter2 returns the rune that starts at s[k]
   262  // and the index where the next rune starts.
   263  func stringiter2(s string, k int) (int, rune) {
   264  	if k >= len(s) {
   265  		// 0 is end of iteration
   266  		return 0, 0
   267  	}
   268  
   269  	c := s[k]
   270  	if c < runeself {
   271  		return k + 1, rune(c)
   272  	}
   273  
   274  	// multi-char rune
   275  	r, n := charntorune(s[k:])
   276  	return k + n, r
   277  }
   278  
   279  // rawstring allocates storage for a new string. The returned
   280  // string and byte slice both refer to the same storage.
   281  // The storage is not zeroed. Callers should use
   282  // b to set the string contents and then drop b.
   283  func rawstring(size int) (s string, b []byte) {
   284  	p := mallocgc(uintptr(size), nil, flagNoScan|flagNoZero)
   285  
   286  	stringStructOf(&s).str = p
   287  	stringStructOf(&s).len = size
   288  
   289  	*(*slice)(unsafe.Pointer(&b)) = slice{p, size, size}
   290  
   291  	for {
   292  		ms := maxstring
   293  		if uintptr(size) <= uintptr(ms) || atomic.Casuintptr((*uintptr)(unsafe.Pointer(&maxstring)), uintptr(ms), uintptr(size)) {
   294  			return
   295  		}
   296  	}
   297  }
   298  
   299  // rawbyteslice allocates a new byte slice. The byte slice is not zeroed.
   300  func rawbyteslice(size int) (b []byte) {
   301  	cap := roundupsize(uintptr(size))
   302  	p := mallocgc(cap, nil, flagNoScan|flagNoZero)
   303  	if cap != uintptr(size) {
   304  		memclr(add(p, uintptr(size)), cap-uintptr(size))
   305  	}
   306  
   307  	*(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(cap)}
   308  	return
   309  }
   310  
   311  // rawruneslice allocates a new rune slice. The rune slice is not zeroed.
   312  func rawruneslice(size int) (b []rune) {
   313  	if uintptr(size) > _MaxMem/4 {
   314  		throw("out of memory")
   315  	}
   316  	mem := roundupsize(uintptr(size) * 4)
   317  	p := mallocgc(mem, nil, flagNoScan|flagNoZero)
   318  	if mem != uintptr(size)*4 {
   319  		memclr(add(p, uintptr(size)*4), mem-uintptr(size)*4)
   320  	}
   321  
   322  	*(*slice)(unsafe.Pointer(&b)) = slice{p, size, int(mem / 4)}
   323  	return
   324  }
   325  
   326  // used by cmd/cgo
   327  func gobytes(p *byte, n int) []byte {
   328  	if n == 0 {
   329  		return make([]byte, 0)
   330  	}
   331  	x := make([]byte, n)
   332  	memmove(unsafe.Pointer(&x[0]), unsafe.Pointer(p), uintptr(n))
   333  	return x
   334  }
   335  
   336  func gostring(p *byte) string {
   337  	l := findnull(p)
   338  	if l == 0 {
   339  		return ""
   340  	}
   341  	s, b := rawstring(l)
   342  	memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
   343  	return s
   344  }
   345  
   346  func gostringn(p *byte, l int) string {
   347  	if l == 0 {
   348  		return ""
   349  	}
   350  	s, b := rawstring(l)
   351  	memmove(unsafe.Pointer(&b[0]), unsafe.Pointer(p), uintptr(l))
   352  	return s
   353  }
   354  
   355  func index(s, t string) int {
   356  	if len(t) == 0 {
   357  		return 0
   358  	}
   359  	for i := 0; i < len(s); i++ {
   360  		if s[i] == t[0] && hasprefix(s[i:], t) {
   361  			return i
   362  		}
   363  	}
   364  	return -1
   365  }
   366  
   367  func contains(s, t string) bool {
   368  	return index(s, t) >= 0
   369  }
   370  
   371  func hasprefix(s, t string) bool {
   372  	return len(s) >= len(t) && s[:len(t)] == t
   373  }
   374  
   375  func atoi(s string) int {
   376  	n := 0
   377  	for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   378  		n = n*10 + int(s[0]) - '0'
   379  		s = s[1:]
   380  	}
   381  	return n
   382  }
   383  
   384  //go:nosplit
   385  func findnull(s *byte) int {
   386  	if s == nil {
   387  		return 0
   388  	}
   389  	p := (*[_MaxMem/2 - 1]byte)(unsafe.Pointer(s))
   390  	l := 0
   391  	for p[l] != 0 {
   392  		l++
   393  	}
   394  	return l
   395  }
   396  
   397  func findnullw(s *uint16) int {
   398  	if s == nil {
   399  		return 0
   400  	}
   401  	p := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(s))
   402  	l := 0
   403  	for p[l] != 0 {
   404  		l++
   405  	}
   406  	return l
   407  }
   408  
   409  var maxstring uintptr = 256 // a hint for print
   410  
   411  //go:nosplit
   412  func gostringnocopy(str *byte) string {
   413  	ss := stringStruct{str: unsafe.Pointer(str), len: findnull(str)}
   414  	s := *(*string)(unsafe.Pointer(&ss))
   415  	for {
   416  		ms := maxstring
   417  		if uintptr(len(s)) <= ms || atomic.Casuintptr(&maxstring, ms, uintptr(len(s))) {
   418  			break
   419  		}
   420  	}
   421  	return s
   422  }
   423  
   424  func gostringw(strw *uint16) string {
   425  	var buf [8]byte
   426  	str := (*[_MaxMem/2/2 - 1]uint16)(unsafe.Pointer(strw))
   427  	n1 := 0
   428  	for i := 0; str[i] != 0; i++ {
   429  		n1 += runetochar(buf[:], rune(str[i]))
   430  	}
   431  	s, b := rawstring(n1 + 4)
   432  	n2 := 0
   433  	for i := 0; str[i] != 0; i++ {
   434  		// check for race
   435  		if n2 >= n1 {
   436  			break
   437  		}
   438  		n2 += runetochar(b[n2:], rune(str[i]))
   439  	}
   440  	b[n2] = 0 // for luck
   441  	return s[:n2]
   442  }