Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created July 3, 2019 03:00
Show Gist options
  • Save packrat386/16feafb69f85da25e6fbdc34372ef323 to your computer and use it in GitHub Desktop.
Save packrat386/16feafb69f85da25e6fbdc34372ef323 to your computer and use it in GitHub Desktop.
Dumb impl of `bytes.Index`
package index
func Index(s, sep []byte) int {
pos := 0
for {
if pos+len(sep) > len(s) {
return -1
}
if eql(s[pos:pos+len(sep)], sep) {
return pos
}
pos++
}
}
func eql(a, b []byte) bool {
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
package index
import (
"bytes"
"testing"
)
type BinOpTest struct {
a string
b string
i int
}
var indexTests = []BinOpTest{
{"", "", 0},
{"", "a", -1},
{"", "foo", -1},
{"fo", "foo", -1},
{"foo", "baz", -1},
{"foo", "foo", 0},
{"oofofoofooo", "f", 2},
{"oofofoofooo", "foo", 4},
{"barfoobarfoo", "foo", 3},
{"foo", "", 0},
{"foo", "o", 1},
{"abcABCabc", "A", 3},
// cases with one byte strings - test IndexByte and special case in Index()
{"", "a", -1},
{"x", "a", -1},
{"x", "x", 0},
{"abc", "a", 0},
{"abc", "b", 1},
{"abc", "c", 2},
{"abc", "x", -1},
{"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33},
{"foofyfoobarfoobar", "y", 4},
{"oooooooooooooooooooooo", "r", -1},
// test fallback to Rabin-Karp.
{"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
{"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
}
func TestIndex(t *testing.T) {
for _, tt := range indexTests {
a := []byte(tt.a)
b := []byte(tt.b)
pos := Index(a, b)
if pos != tt.i {
t.Errorf(`Index(%q, %q) = %v`, tt.a, tt.b, pos)
}
}
}
func TestIndexStdlib(t *testing.T) {
for _, tt := range indexTests {
a := []byte(tt.a)
b := []byte(tt.b)
pos := bytes.Index(a, b)
if pos != tt.i {
t.Errorf(`Index(%q, %q) = %v`, tt.a, tt.b, pos)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment