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.
13 // indexShortStr returns the index of the first instance of c in s, or -1 if c is not present in s.
14 // indexShortStr requires 2 <= len(c) <= shortStringLen
15 func indexShortStr(s
, c
string) int // ../runtime/asm_amd64.s
16 func countByte(s
string, c
byte) int // ../runtime/asm_amd64.s
18 var shortStringLen
int
28 // Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
29 func Index(s
, substr
string) int {
35 return IndexByte(s
, substr
[0])
43 case n
<= shortStringLen
:
44 // Use brute force when s and substr both are small
46 return indexShortStr(s
, substr
)
54 // IndexByte skips 16/32 bytes per iteration,
55 // so it's faster than indexShortStr.
56 o
:= IndexByte(t
[i
:], c
)
62 if s
[i
:i
+n
] == substr
{
67 // Switch to indexShortStr when IndexByte produces too many false positives.
68 // Too many means more that 1 error per 8 characters.
69 // Allow some errors in the beginning.
71 r
:= indexShortStr(s
[i
:], substr
)
81 hashss
, pow
:= hashStr(substr
)
83 for i
:= 0; i
< n
; i
++ {
84 h
= h
*primeRK
+ uint32(s
[i
])
86 if h
== hashss
&& s
[:n
] == substr
{
89 for i
:= n
; i
< len(s
); {
92 h
-= pow
* uint32(s
[i
-n
])
94 if h
== hashss
&& s
[i
-n
:i
] == substr
{
101 // Count counts the number of non-overlapping instances of substr in s.
102 // If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
103 func Count(s
, substr
string) int {
104 if len(substr
) == 1 && cpu
.X86
.HasPOPCNT
{
105 return countByte(s
, byte(substr
[0]))
107 return countGeneric(s
, substr
)