Skip to content

Commit

Permalink
Matcher intf use new buf method
Browse files Browse the repository at this point in the history
  • Loading branch information
zix99 committed Jan 12, 2025
1 parent 6e4243b commit 28c28a2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
3 changes: 2 additions & 1 deletion pkg/matchers/intf.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ type Factory interface {

// A non-thread-safe matcher that can be used to find matches
type Matcher interface {
FindSubmatchIndex(b []byte) []int
FindSubmatchIndexDst(b []byte, dst []int) []int
MatchBufSize() int
SubexpNameTable() map[string]int
}
8 changes: 6 additions & 2 deletions pkg/matchers/simple.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ func (s *AlwaysMatch) CreateInstance() Matcher {
return s
}

func (s *AlwaysMatch) FindSubmatchIndex(b []byte) []int {
return []int{0, len(b)}
func (s *AlwaysMatch) FindSubmatchIndexDst(b []byte, dst []int) []int {
return append(dst, 0, len(b))
}

func (s *AlwaysMatch) MatchBufSize() int {
return 2
}

func (s *AlwaysMatch) SubexpNameTable() map[string]int {
Expand Down
24 changes: 22 additions & 2 deletions pkg/matchers/simple_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ func TestSimpleMatcherAndFactory(t *testing.T) {

assert.Empty(t, inst.SubexpNameTable())

assert.Equal(t, []int{0, 0}, inst.FindSubmatchIndex([]byte{}))
assert.Equal(t, []int{0, 2}, inst.FindSubmatchIndex([]byte("hi")))
assert.Equal(t, []int{0, 0}, inst.FindSubmatchIndexDst([]byte{}, nil))
assert.Equal(t, []int{0, 2}, inst.FindSubmatchIndexDst([]byte("hi"), nil))

buf := make([]int, 0, inst.MatchBufSize())
assert.Equal(t, []int{0, 2}, inst.FindSubmatchIndexDst([]byte("hi"), buf))
}

func TestNoAlloc(t *testing.T) {
b := testing.Benchmark(BenchmarkSimpleMatcher)
assert.Zero(t, b.AllocedBytesPerOp())
assert.Zero(t, b.AllocsPerOp())
}

// BenchmarkSimpleMatcher-4 251675946 4.761 ns/op 0 B/op 0 allocs/op
func BenchmarkSimpleMatcher(b *testing.B) {
m := ToFactory(&AlwaysMatch{}).CreateInstance()
d := []byte("hi")
buf := make([]int, 0, m.MatchBufSize())

for i := 0; i < b.N; i++ {
m.FindSubmatchIndexDst(d, buf)
}
}

0 comments on commit 28c28a2

Please sign in to comment.