feat: more efficient regexp use in parser

This commit is contained in:
James Houlahan
2020-08-17 17:31:31 +02:00
parent 6a7a77fc51
commit a2cf5374b9
3 changed files with 15 additions and 13 deletions

View File

@ -22,7 +22,7 @@ import "regexp"
type HandlerFunc func(*Part) error
type handler struct {
typeRegExp, dispRegExp string
typeRegExp, dispRegExp *regexp.Regexp
fn HandlerFunc
}
@ -31,7 +31,7 @@ func (h *handler) matchPart(p *Part) bool {
}
func (h *handler) matchType(p *Part) bool {
if h.typeRegExp == "" {
if h.typeRegExp == nil {
return false
}
@ -40,11 +40,11 @@ func (h *handler) matchType(p *Part) bool {
t = ""
}
return regexp.MustCompile(h.typeRegExp).MatchString(t)
return h.typeRegExp.MatchString(t)
}
func (h *handler) matchDisp(p *Part) bool {
if h.dispRegExp == "" {
if h.dispRegExp == nil {
return false
}
@ -53,5 +53,5 @@ func (h *handler) matchDisp(p *Part) bool {
disp = ""
}
return regexp.MustCompile(h.dispRegExp).MatchString(disp)
return h.dispRegExp.MatchString(disp)
}

View File

@ -37,13 +37,13 @@ type Visit func(*Part) (interface{}, error)
type VisitorRule func(*Part, Visit) (interface{}, error)
type visitorRule struct {
re string
re *regexp.Regexp
fn VisitorRule
}
func (v *Visitor) RegisterRule(contentTypeRegex string, fn VisitorRule) *Visitor {
v.rules = append(v.rules, &visitorRule{
re: contentTypeRegex,
re: regexp.MustCompile(contentTypeRegex),
fn: fn,
})
@ -69,7 +69,7 @@ func (v *Visitor) visit(p *Part) (interface{}, error) {
func (v *Visitor) getRuleForContentType(contentType string) *visitorRule {
for _, rule := range v.rules {
if regexp.MustCompile(rule.re).MatchString(contentType) {
if rule.re.MatchString(contentType) {
return rule
}
}

View File

@ -17,6 +17,8 @@
package parser
import "regexp"
type Walker struct {
root *Part
@ -56,7 +58,7 @@ func (w *Walker) RegisterDefaultHandler(fn HandlerFunc) *Walker {
func (w *Walker) RegisterContentTypeHandler(typeRegExp string, fn HandlerFunc) *Walker {
w.handlers = append(w.handlers, &handler{
typeRegExp: typeRegExp,
typeRegExp: regexp.MustCompile(typeRegExp),
fn: fn,
})
@ -65,7 +67,7 @@ func (w *Walker) RegisterContentTypeHandler(typeRegExp string, fn HandlerFunc) *
func (w *Walker) RegisterContentDispositionHandler(dispRegExp string, fn HandlerFunc) *Walker {
w.handlers = append(w.handlers, &handler{
dispRegExp: dispRegExp,
dispRegExp: regexp.MustCompile(dispRegExp),
fn: fn,
})
@ -73,9 +75,9 @@ func (w *Walker) RegisterContentDispositionHandler(dispRegExp string, fn Handler
}
func (w *Walker) getHandlerFunc(p *Part) HandlerFunc {
for _, hdl := range w.handlers {
if hdl.matchPart(p) {
return hdl.fn
for _, handler := range w.handlers {
if handler.matchPart(p) {
return handler.fn
}
}