Skip to content

Commit

Permalink
formatPath perf opt attempt
Browse files Browse the repository at this point in the history
  • Loading branch information
attiss committed Jan 22, 2025
1 parent 896b164 commit 07c32d7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
19 changes: 10 additions & 9 deletions rules/matcher.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rules

import (
"reflect"
"regexp"
"strings"
)
Expand Down Expand Up @@ -124,26 +125,26 @@ func FormatWithAttributes(pattern string, m Attributes) string {

func formatPath(pattern string, m Attributes) (string, bool) {
allFound := true

paths := strings.Split(pattern, "/")
result := strings.Builder{}
for _, path := range paths {
reflect.ValueOf(&paths).Elem().SetCap(len(paths))

for i, path := range paths {
if len(path) == 0 {
continue
}
result.WriteString("/")

if strings.HasPrefix(path, ":") {
attr := m.GetAttribute(path[1:])
if attr == nil {
s := path
attr = &s
attr = &path
allFound = false
}
result.WriteString(*attr)
} else {
result.WriteString(path)
paths[i] = *attr
}
}
return result.String(), allFound

return strings.Join(paths, "/"), allFound
}

// Keep the bool return value, because it's tricky to check for null
Expand Down
40 changes: 40 additions & 0 deletions rules/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,43 @@ func TestNoRegex(t *testing.T) {
t.Fail()
}
}

func TestFormatPath(t *testing.T) {
testCases := []struct {
name string
pattern string
atttributes Attributes
result string
allFound bool
}{
{
"Happy path",
"/:region/test",
NewAttributes(map[string]string{"region": "region"}),
"/region/test",
true,
},
{
"Empty path",
"",
NewAttributes(map[string]string{"region": "region"}),
"",
true,
},
{
"Missing attribute",
"/:region/test",
NewAttributes(map[string]string{}),
"/:region/test",
false,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result, allFound := formatPath(tc.pattern, tc.atttributes)
assert.Equal(t, tc.result, result)
assert.Equal(t, tc.allFound, allFound)
})
}
}

0 comments on commit 07c32d7

Please sign in to comment.