Skip to content

Commit

Permalink
fix: compile regex pattern redundantly when parsing kafka version(#2662)
Browse files Browse the repository at this point in the history
Signed-off-by: qshuai <[email protected]>
  • Loading branch information
qshuai committed Oct 8, 2023
1 parent 44f6db5 commit 5521b99
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,11 @@ var (
}
)

var (
validKafkaVersion1 = regexp.MustCompile(`^0\.\d+\.\d+\.\d+$`)
validKafkaVersion2 = regexp.MustCompile(`^\d+\.\d+\.\d+$`)
)

// ParseKafkaVersion parses and returns kafka version or error from a string
func ParseKafkaVersion(s string) (KafkaVersion, error) {
if len(s) < 5 {
Expand All @@ -288,18 +293,18 @@ func ParseKafkaVersion(s string) (KafkaVersion, error) {
var major, minor, veryMinor, patch uint
var err error
if s[0] == '0' {
err = scanKafkaVersion(s, `^0\.\d+\.\d+\.\d+$`, "0.%d.%d.%d", [3]*uint{&minor, &veryMinor, &patch})
err = scanKafkaVersion(s, validKafkaVersion1, "0.%d.%d.%d", [3]*uint{&minor, &veryMinor, &patch})
} else {
err = scanKafkaVersion(s, `^\d+\.\d+\.\d+$`, "%d.%d.%d", [3]*uint{&major, &minor, &veryMinor})
err = scanKafkaVersion(s, validKafkaVersion2, "%d.%d.%d", [3]*uint{&major, &minor, &veryMinor})
}
if err != nil {
return DefaultVersion, err
}
return newKafkaVersion(major, minor, veryMinor, patch), nil
}

func scanKafkaVersion(s string, pattern string, format string, v [3]*uint) error {
if !regexp.MustCompile(pattern).MatchString(s) {
func scanKafkaVersion(s string, pattern *regexp.Regexp, format string, v [3]*uint) error {
if !pattern.MatchString(s) {
return fmt.Errorf("invalid version `%s`", s)
}
_, err := fmt.Sscanf(s, format, v[0], v[1], v[2])
Expand Down

0 comments on commit 5521b99

Please sign in to comment.