github.com/liujq9674git/golang-src-1.7@v0.0.0-20230517174348-17f6ec47f3f8/src/strings/strings_amd64.go (about)

     1  // Copyright 2015 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 strings
     6  
     7  // indexShortStr returns the index of the first instance of c in s, or -1 if c is not present in s.
     8  // indexShortStr requires 2 <= len(c) <= shortStringLen
     9  func indexShortStr(s, c string) int // ../runtime/asm_$GOARCH.s
    10  const shortStringLen = 31
    11  
    12  // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
    13  func Index(s, sep string) int {
    14  	n := len(sep)
    15  	switch {
    16  	case n == 0:
    17  		return 0
    18  	case n == 1:
    19  		return IndexByte(s, sep[0])
    20  	case n <= shortStringLen:
    21  		return indexShortStr(s, sep)
    22  	case n == len(s):
    23  		if sep == s {
    24  			return 0
    25  		}
    26  		return -1
    27  	case n > len(s):
    28  		return -1
    29  	}
    30  	// Rabin-Karp search
    31  	hashsep, pow := hashStr(sep)
    32  	var h uint32
    33  	for i := 0; i < n; i++ {
    34  		h = h*primeRK + uint32(s[i])
    35  	}
    36  	if h == hashsep && s[:n] == sep {
    37  		return 0
    38  	}
    39  	for i := n; i < len(s); {
    40  		h *= primeRK
    41  		h += uint32(s[i])
    42  		h -= pow * uint32(s[i-n])
    43  		i++
    44  		if h == hashsep && s[i-n:i] == sep {
    45  			return i - n
    46  		}
    47  	}
    48  	return -1
    49  }