Home | History | Annotate | Download | only in strings
      1 // Copyright 2016 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 //go:noescape
      8 
      9 // indexShortStr returns the index of the first instance of sep in s,
     10 // or -1 if sep is not present in s.
     11 // indexShortStr requires 2 <= len(sep) <= shortStringLen
     12 func indexShortStr(s, sep string) int // ../runtime/asm_$GOARCH.s
     13 
     14 // supportsVX reports whether the vector facility is available.
     15 // indexShortStr must not be called if the vector facility is not
     16 // available.
     17 func supportsVX() bool // ../runtime/asm_s390x.s
     18 
     19 var shortStringLen = -1
     20 
     21 func init() {
     22 	if supportsVX() {
     23 		shortStringLen = 64
     24 	}
     25 }
     26 
     27 // Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
     28 func Index(s, substr string) int {
     29 	n := len(substr)
     30 	switch {
     31 	case n == 0:
     32 		return 0
     33 	case n == 1:
     34 		return IndexByte(s, substr[0])
     35 	case n == len(s):
     36 		if substr == s {
     37 			return 0
     38 		}
     39 		return -1
     40 	case n > len(s):
     41 		return -1
     42 	case n <= shortStringLen:
     43 		// Use brute force when s and substr both are small
     44 		if len(s) <= 64 {
     45 			return indexShortStr(s, substr)
     46 		}
     47 		c := substr[0]
     48 		i := 0
     49 		t := s[:len(s)-n+1]
     50 		fails := 0
     51 		for i < len(t) {
     52 			if t[i] != c {
     53 				// IndexByte skips 16/32 bytes per iteration,
     54 				// so it's faster than indexShortStr.
     55 				o := IndexByte(t[i:], c)
     56 				if o < 0 {
     57 					return -1
     58 				}
     59 				i += o
     60 			}
     61 			if s[i:i+n] == substr {
     62 				return i
     63 			}
     64 			fails++
     65 			i++
     66 			// Switch to indexShortStr when IndexByte produces too many false positives.
     67 			// Too many means more that 1 error per 8 characters.
     68 			// Allow some errors in the beginning.
     69 			if fails > (i+16)/8 {
     70 				r := indexShortStr(s[i:], substr)
     71 				if r >= 0 {
     72 					return r + i
     73 				}
     74 				return -1
     75 			}
     76 		}
     77 		return -1
     78 	}
     79 	return indexRabinKarp(s, substr)
     80 }
     81 
     82 // Count counts the number of non-overlapping instances of substr in s.
     83 // If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
     84 func Count(s, substr string) int {
     85 	return countGeneric(s, substr)
     86 }
     87