2017-01-14 01:05:42 +01:00
|
|
|
// Copyright 2015 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2018-01-09 02:23:08 +01:00
|
|
|
// -build !amd64,!s390x,!arm64
|
2017-01-14 01:05:42 +01:00
|
|
|
|
|
|
|
package bytes
|
|
|
|
|
|
|
|
// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
|
|
|
|
func Index(s, sep []byte) int {
|
|
|
|
n := len(sep)
|
2018-01-09 02:23:08 +01:00
|
|
|
switch {
|
|
|
|
case n == 0:
|
2017-01-14 01:05:42 +01:00
|
|
|
return 0
|
2018-01-09 02:23:08 +01:00
|
|
|
case n == 1:
|
|
|
|
return IndexByte(s, sep[0])
|
|
|
|
case n == len(s):
|
|
|
|
if Equal(sep, s) {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return -1
|
|
|
|
case n > len(s):
|
2017-01-14 01:05:42 +01:00
|
|
|
return -1
|
|
|
|
}
|
|
|
|
c := sep[0]
|
|
|
|
i := 0
|
2018-01-09 02:23:08 +01:00
|
|
|
fails := 0
|
2017-01-14 01:05:42 +01:00
|
|
|
t := s[:len(s)-n+1]
|
|
|
|
for i < len(t) {
|
|
|
|
if t[i] != c {
|
|
|
|
o := IndexByte(t[i:], c)
|
|
|
|
if o < 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
i += o
|
|
|
|
}
|
|
|
|
if Equal(s[i:i+n], sep) {
|
|
|
|
return i
|
|
|
|
}
|
|
|
|
i++
|
2018-01-09 02:23:08 +01:00
|
|
|
fails++
|
|
|
|
if fails >= 4+i>>4 && i < len(t) {
|
|
|
|
// Give up on IndexByte, it isn't skipping ahead
|
|
|
|
// far enough to be better than Rabin-Karp.
|
|
|
|
// Experiments (using IndexPeriodic) suggest
|
|
|
|
// the cutover is about 16 byte skips.
|
|
|
|
// TODO: if large prefixes of sep are matching
|
|
|
|
// we should cutover at even larger average skips,
|
|
|
|
// because Equal becomes that much more expensive.
|
|
|
|
// This code does not take that effect into account.
|
|
|
|
j := indexRabinKarp(s[i:], sep)
|
|
|
|
if j < 0 {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
return i + j
|
|
|
|
}
|
2017-01-14 01:05:42 +01:00
|
|
|
}
|
|
|
|
return -1
|
|
|
|
}
|
2017-09-14 19:11:35 +02:00
|
|
|
|
|
|
|
// Count counts the number of non-overlapping instances of sep in s.
|
2018-01-09 02:23:08 +01:00
|
|
|
// If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
|
2017-09-14 19:11:35 +02:00
|
|
|
func Count(s, sep []byte) int {
|
|
|
|
return countGeneric(s, sep)
|
|
|
|
}
|