summaryrefslogtreecommitdiff
path: root/src/pkg/strings
diff options
context:
space:
mode:
authorRob Pike <r@golang.org>2009-11-18 19:23:08 -0800
committerRob Pike <r@golang.org>2009-11-18 19:23:08 -0800
commita1dec403e8dbcfb4efe93c34eadbb2b2e0b17dc3 (patch)
tree1fd5ff4b844c7f44464318cc686f3dce4ac76e3f /src/pkg/strings
parent44b150139b3597809cf41ae7a2eb9491e10254e9 (diff)
downloadgolang-a1dec403e8dbcfb4efe93c34eadbb2b2e0b17dc3.tar.gz
add bytes.IndexByte; common case we can make fast later.
also pick off the special case in strings.Index. don't want strings.IndexByte because the call site will very rarely need to allocate and we can handle the test in the code itself. bytes.IndexByte can avoid a common allocation. R=rsc CC=golang-dev http://codereview.appspot.com/156091
Diffstat (limited to 'src/pkg/strings')
-rw-r--r--src/pkg/strings/strings.go18
-rw-r--r--src/pkg/strings/strings_test.go9
2 files changed, 27 insertions, 0 deletions
diff --git a/src/pkg/strings/strings.go b/src/pkg/strings/strings.go
index 7ccfc5ca8..fb3070a1a 100644
--- a/src/pkg/strings/strings.go
+++ b/src/pkg/strings/strings.go
@@ -56,6 +56,15 @@ func Index(s, sep string) int {
return 0
}
c := sep[0];
+ if n == 1 {
+ // special case worth making fast
+ for i := 0; i < len(s); i++ {
+ if s[i] == c {
+ return i
+ }
+ }
+ return -1;
+ }
for i := 0; i+n <= len(s); i++ {
if s[i] == c && (n == 1 || s[i:i+n] == sep) {
return i
@@ -71,6 +80,15 @@ func LastIndex(s, sep string) int {
return len(s)
}
c := sep[0];
+ if n == 1 {
+ // special case worth making fast
+ for i := len(s) - 1; i >= 0; i-- {
+ if s[i] == c {
+ return i
+ }
+ }
+ return -1;
+ }
for i := len(s) - n; i >= 0; i-- {
if s[i] == c && (n == 1 || s[i:i+n] == sep) {
return i
diff --git a/src/pkg/strings/strings_test.go b/src/pkg/strings/strings_test.go
index 0073f0d0e..1171db224 100644
--- a/src/pkg/strings/strings_test.go
+++ b/src/pkg/strings/strings_test.go
@@ -46,6 +46,14 @@ var indexTests = []IndexTest{
IndexTest{"foo", "", 0},
IndexTest{"foo", "o", 1},
IndexTest{"abcABCabc", "A", 3},
+ // cases with one byte strings - test special case in Index()
+ IndexTest{"", "a", -1},
+ IndexTest{"x", "a", -1},
+ IndexTest{"x", "x", 0},
+ IndexTest{"abc", "a", 0},
+ IndexTest{"abc", "b", 1},
+ IndexTest{"abc", "c", 2},
+ IndexTest{"abc", "x", -1},
}
var lastIndexTests = []IndexTest{
@@ -54,6 +62,7 @@ var lastIndexTests = []IndexTest{
IndexTest{"", "foo", -1},
IndexTest{"fo", "foo", -1},
IndexTest{"foo", "foo", 0},
+ IndexTest{"foo", "f", 0},
IndexTest{"oofofoofooo", "f", 7},
IndexTest{"oofofoofooo", "foo", 7},
IndexTest{"barfoobarfoo", "foo", 9},