github.com/goplusjs/gopherjs@v1.2.6-0.20211206034512-f187917453b8/compiler/natives/src/strings/strings.go (about)

     1  // +build js
     2  
     3  package strings
     4  
     5  import (
     6  	"unicode/utf8"
     7  
     8  	"github.com/gopherjs/gopherjs/js"
     9  )
    10  
    11  func IndexByte(s string, c byte) int {
    12  	return js.InternalObject(s).Call("indexOf", js.Global.Get("String").Call("fromCharCode", c)).Int()
    13  }
    14  
    15  func Index(s, sep string) int {
    16  	return js.InternalObject(s).Call("indexOf", js.InternalObject(sep)).Int()
    17  }
    18  
    19  func LastIndex(s, sep string) int {
    20  	return js.InternalObject(s).Call("lastIndexOf", js.InternalObject(sep)).Int()
    21  }
    22  
    23  func Count(s, sep string) int {
    24  	n := 0
    25  	// special cases
    26  	switch {
    27  	case len(sep) == 0:
    28  		return utf8.RuneCountInString(s) + 1
    29  	case len(sep) > len(s):
    30  		return 0
    31  	case len(sep) == len(s):
    32  		if sep == s {
    33  			return 1
    34  		}
    35  		return 0
    36  	}
    37  
    38  	for {
    39  		pos := Index(s, sep)
    40  		if pos == -1 {
    41  			break
    42  		}
    43  		n++
    44  		s = s[pos+len(sep):]
    45  	}
    46  	return n
    47  }
    48  
    49  func (b *Builder) String() string {
    50  	// Upstream Builder.String relies on package unsafe. We can't do that.
    51  	// TODO: It's possible that the entire strings.Builder API can be implemented
    52  	//       more efficiently for GOARCH=js specifically (avoid using []byte, instead
    53  	//       use a String directly; or some JavaScript string builder API if one exists).
    54  	//       But this is more work, defer doing it until there's a need shown via profiling,
    55  	//       and there are benchmarks available (see https://github.com/golang/go/issues/18990#issuecomment-352068533).
    56  	return string(b.buf)
    57  }
    58  
    59  func (b *Builder) copyCheck() {
    60  	if b.addr == nil {
    61  		// Upstream copyCheck uses noescape, which performs unsafe.Pointer manipulation.
    62  		// We can't do that, so skip it. See https://github.com/golang/go/commit/484586c81a0196e42ac52f651bc56017ca454280.
    63  		b.addr = b
    64  	} else if b.addr != b {
    65  		panic("strings: illegal use of non-zero Builder copied by value")
    66  	}
    67  }