Skip to content

Commit

Permalink
Add sync.map and optimise
Browse files Browse the repository at this point in the history
  • Loading branch information
soujanyanmbri committed Jan 22, 2025
1 parent 62e8e79 commit 6f9d990
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
23 changes: 8 additions & 15 deletions internal/corazawaf/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ package corazawaf

import (
"fmt"
"hash/fnv"
"regexp"
"strconv"
"strings"
"sync"
"unsafe"
Expand Down Expand Up @@ -585,23 +587,14 @@ func (r *Rule) AddVariableNegation(v variables.RuleVariable, key string) error {
return nil
}

var transformationIDToName = []string{""}
var transformationNameToID = map[string]int{"": 0}
var transformationIDsLock = sync.Mutex{}
var transformationNameToID sync.Map

func transformationID(currentID int, transformationName string) int {
transformationIDsLock.Lock()
defer transformationIDsLock.Unlock()

currName := transformationIDToName[currentID]
nextName := fmt.Sprintf("%s+%s", currName, transformationName)
if id, ok := transformationNameToID[nextName]; ok {
return id
}

id := len(transformationIDToName)
transformationIDToName = append(transformationIDToName, nextName)
transformationNameToID[nextName] = id
nextName := strconv.Itoa(currentID) + "+" + transformationName
hasher := fnv.New64a()
hasher.Write([]byte(nextName))
id := int(hasher.Sum64())
transformationNameToID.LoadOrStore(id, nextName)

Check warning on line 597 in internal/corazawaf/rule.go

View check run for this annotation

Codecov / codecov/patch

internal/corazawaf/rule.go#L593-L597

Added lines #L593 - L597 were not covered by tests
return id
}

Expand Down
17 changes: 17 additions & 0 deletions internal/corazawaf/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,3 +616,20 @@ func TestExpandMacroAfterWholeRuleEvaluation(t *testing.T) {
t.Errorf("Expected ArgsGet-data, got %s", matchdata[0].Data())
}
}

func BenchmarkAddTransformationUnique(b *testing.B) {
transformation := func(input string) (string, bool, error) {
return "Test", true, nil
}
b.ResetTimer()
b.RunParallel(func(p *testing.PB) {
rule := NewRule()
for p.Next() {
transformationName := "transformation" + b.Name()
err := rule.AddTransformation(transformationName, transformation)
if err != nil {
b.Fatalf("Failed to add a transformation: %s", err.Error())
}
}
})
}

0 comments on commit 6f9d990

Please sign in to comment.