...
Run Format

Source file src/strings/strings_amd64.go

Documentation: strings

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

View as plain text