Skip to content

Commit

Permalink
transform/urlreplacers: Cache the next position of urlreplacer.prefix
Browse files Browse the repository at this point in the history
Improved performance due to `bytes.Index` repeated calls

Fixes #5942
  • Loading branch information
vazrupe authored and bep committed Aug 6, 2019
1 parent 02397e7 commit a843ca5
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions transform/urlreplacers/absurlreplacer.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,28 @@ type prefix struct {
disabled bool
b []byte
f func(l *absurllexer)

nextPos int
}

func (p *prefix) find(bs []byte, start int) bool {
if p.disabled {
return false
}

if p.nextPos == -1 {
idx := bytes.Index(bs[start:], p.b)

if idx == -1 {
p.disabled = true
// Find the closest match
return false
}

p.nextPos = start + idx + len(p.b)
}

return true
}

func newPrefixState() []*prefix {
Expand Down Expand Up @@ -179,35 +201,28 @@ func (l *absurllexer) replace() {
break
}

nextPos := -1

var match *prefix

for _, p := range prefixes {
if p.disabled {
if !p.find(l.content, l.pos) {
continue
}
idx := bytes.Index(l.content[l.pos:], p.b)

if idx == -1 {
p.disabled = true
// Find the closest match
} else if nextPos == -1 || idx < nextPos {
nextPos = idx
if match == nil || p.nextPos < match.nextPos {
match = p
}
}

if nextPos == -1 {
if match == nil {
// Done!
l.pos = contentLength
break
} else {
l.pos += nextPos + len(match.b)
l.pos = match.nextPos
match.nextPos = -1
match.f(l)
}
}

// Done!
if l.pos > l.start {
l.emit()
Expand Down

0 comments on commit a843ca5

Please sign in to comment.