File: strings_amd64.go

package info (click to toggle)
gcc-riscv64-unknown-elf 8.3.0.2019.08%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 680,956 kB
  • sloc: ansic: 3,237,715; cpp: 896,882; ada: 772,854; f90: 144,254; asm: 68,788; makefile: 67,456; sh: 29,743; exp: 28,045; objc: 15,273; fortran: 11,885; python: 7,369; pascal: 5,375; awk: 3,725; perl: 2,872; yacc: 316; xml: 311; ml: 285; lex: 198; haskell: 122
file content (90 lines) | stat: -rw-r--r-- 2,118 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 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.

// +build ignore

package strings

import "internal/cpu"

//go:noescape

// indexShortStr returns the index of the first instance of c in s, or -1 if c is not present in s.
// indexShortStr requires 2 <= len(c) <= shortStringLen
func indexShortStr(s, c string) int  // ../runtime/asm_amd64.s
func countByte(s string, c byte) int // ../runtime/asm_amd64.s

var shortStringLen int

func init() {
	if cpu.X86.HasAVX2 {
		shortStringLen = 63
	} else {
		shortStringLen = 31
	}
}

// Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.
func Index(s, substr string) int {
	n := len(substr)
	switch {
	case n == 0:
		return 0
	case n == 1:
		return IndexByte(s, substr[0])
	case n == len(s):
		if substr == s {
			return 0
		}
		return -1
	case n > len(s):
		return -1
	case n <= shortStringLen:
		// Use brute force when s and substr both are small
		if len(s) <= 64 {
			return indexShortStr(s, substr)
		}
		c := substr[0]
		i := 0
		t := s[:len(s)-n+1]
		fails := 0
		for i < len(t) {
			if t[i] != c {
				// IndexByte skips 16/32 bytes per iteration,
				// so it's faster than indexShortStr.
				o := IndexByte(t[i:], c)
				if o < 0 {
					return -1
				}
				i += o
			}
			if s[i:i+n] == substr {
				return i
			}
			fails++
			i++
			// Switch to indexShortStr when IndexByte produces too many false positives.
			// Too many means more that 1 error per 8 characters.
			// Allow some errors in the beginning.
			if fails > (i+16)/8 {
				r := indexShortStr(s[i:], substr)
				if r >= 0 {
					return r + i
				}
				return -1
			}
		}
		return -1
	}
	return indexRabinKarp(s, substr)
}

// Count counts the number of non-overlapping instances of substr in s.
// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
func Count(s, substr string) int {
	if len(substr) == 1 && cpu.X86.HasPOPCNT {
		return countByte(s, byte(substr[0]))
	}
	return countGeneric(s, substr)
}