Skip to content

Commit d0c89ea

Browse files
committed
Add sync.map and optimise
1 parent 62e8e79 commit d0c89ea

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

Diff for: internal/corazawaf/rule.go

+8-15
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ package corazawaf
55

66
import (
77
"fmt"
8+
"hash/fnv"
89
"regexp"
10+
"strconv"
911
"strings"
1012
"sync"
1113
"unsafe"
@@ -585,23 +587,14 @@ func (r *Rule) AddVariableNegation(v variables.RuleVariable, key string) error {
585587
return nil
586588
}
587589

588-
var transformationIDToName = []string{""}
589-
var transformationNameToID = map[string]int{"": 0}
590-
var transformationIDsLock = sync.Mutex{}
590+
var transformationNameToID sync.Map
591591

592592
func transformationID(currentID int, transformationName string) int {
593-
transformationIDsLock.Lock()
594-
defer transformationIDsLock.Unlock()
595-
596-
currName := transformationIDToName[currentID]
597-
nextName := fmt.Sprintf("%s+%s", currName, transformationName)
598-
if id, ok := transformationNameToID[nextName]; ok {
599-
return id
600-
}
601-
602-
id := len(transformationIDToName)
603-
transformationIDToName = append(transformationIDToName, nextName)
604-
transformationNameToID[nextName] = id
593+
nextName := strconv.Itoa(currentID) + "+" + transformationName
594+
hasher := fnv.New64a()
595+
hasher.Write([]byte(nextName))
596+
id := int(hasher.Sum64())
597+
transformationNameToID.LoadOrStore(id, nextName)
605598
return id
606599
}
607600

Diff for: internal/corazawaf/rule_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,23 @@ func TestAddTransformation(t *testing.T) {
384384
}
385385
}
386386

387+
func BenchmarkAddTransformationUnique(b *testing.B) {
388+
transformation := func(input string) (string, bool, error) {
389+
return "Test", true, nil
390+
}
391+
b.ResetTimer()
392+
b.RunParallel(func(p *testing.PB) {
393+
rule := NewRule()
394+
for p.Next() {
395+
transformationName := "transformation" + b.Name()
396+
err := rule.AddTransformation(transformationName, transformation)
397+
if err != nil {
398+
b.Fatalf("Failed to add a transformation: %s", err.Error())
399+
}
400+
}
401+
})
402+
}
403+
387404
func TestAddTransformationEmpty(t *testing.T) {
388405
rule := NewRule()
389406
transformationName := ""

0 commit comments

Comments
 (0)