Home | History | Annotate | Download | only in 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 // +build !amd64,!s390x
      6 
      7 package strings
      8 
      9 // TODO: implements short string optimization on non amd64 platforms
     10 // and get rid of strings_amd64.go
     11 
     12 // Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
     13 func Index(s, substr string) int {
     14 	n := len(substr)
     15 	switch {
     16 	case n == 0:
     17 		return 0
     18 	case n == 1:
     19 		return IndexByte(s, substr[0])
     20 	case n == len(s):
     21 		if substr == s {
     22 			return 0
     23 		}
     24 		return -1
     25 	case n > len(s):
     26 		return -1
     27 	}
     28 	c := substr[0]
     29 	i := 0
     30 	t := s[:len(s)-n+1]
     31 	fails := 0
     32 	for i < len(t) {
     33 		if t[i] != c {
     34 			o := IndexByte(t[i:], c)
     35 			if o < 0 {
     36 				return -1
     37 			}
     38 			i += o
     39 		}
     40 		if s[i:i+n] == substr {
     41 			return i
     42 		}
     43 		i++
     44 		fails++
     45 		if fails >= 4+i>>4 && i < len(t) {
     46 			// See comment in ../bytes/bytes_generic.go.
     47 			j := indexRabinKarp(s[i:], substr)
     48 			if j < 0 {
     49 				return -1
     50 			}
     51 			return i + j
     52 		}
     53 	}
     54 	return -1
     55 }
     56 
     57 // Count counts the number of non-overlapping instances of substr in s.
     58 // If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
     59 func Count(s, substr string) int {
     60 	return countGeneric(s, substr)
     61 }
     62