Skip to content

Commit

Permalink
faster SanitizeNameV2 (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuval-k authored Apr 24, 2024
1 parent 1707727 commit ba2c462
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
23 changes: 10 additions & 13 deletions kubeutils/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/md5"
"fmt"
"strings"
"unicode"
)

// use SanitizeNameV2
Expand All @@ -28,23 +29,19 @@ func SanitizeName(name string) string {
}

func SanitizeNameV2(name string) string {
name = strings.Replace(name, "*", "-", -1)
name = strings.Replace(name, "/", "-", -1)
name = strings.Replace(name, ".", "-", -1)
name = strings.Replace(name, "[", "", -1)
name = strings.Replace(name, "]", "", -1)
name = strings.Replace(name, ":", "-", -1)
name = strings.Replace(name, "_", "-", -1)
name = strings.Replace(name, " ", "-", -1)
name = strings.Replace(name, "\n", "", -1)
name = strings.Replace(name, "\"", "", -1)
name = strings.Replace(name, "'", "", -1)
name = strings.Map(func(r rune) rune {
switch r {
case '*', '/', '.', ':', '_', ' ':
return '-'
case '[', ']', '\n', '"', '\'':
return -1
}
return unicode.ToLower(r)
}, name)
if len(name) > 63 {
hash := md5.Sum([]byte(name))
name = fmt.Sprintf("%s-%x", name[:31], hash)
name = name[:63]
}
name = strings.Replace(name, ".", "-", -1)
name = strings.ToLower(name)
return name
}
15 changes: 15 additions & 0 deletions kubeutils/util_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package kubeutils

import (
"time"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gmeasure"
)

var _ = Describe("sanitize name", func() {
Expand Down Expand Up @@ -47,4 +50,16 @@ var _ = Describe("sanitize name", func() {
Entry("301a's", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-c73301b7b71679067b02cff4cdc5e70"),
)
It("SanitizeNameV2 efficiently", Serial, Label("measurement"), func() {
experiment := gmeasure.NewExperiment("Repaginating Books")
AddReportEntry(experiment.Name, experiment)

experiment.Sample(func(idx int) {
experiment.MeasureDuration("repagination", func() {
for i := 0; i < 1000; i++ {
SanitizeNameV2("sub []_---]_9da02_--_2")
}
})
}, gmeasure.SamplingConfig{N: 200, Duration: time.Minute})
})
})

0 comments on commit ba2c462

Please sign in to comment.