Skip to content

Commit

Permalink
Use sync.OnceValue only on go1.21+
Browse files Browse the repository at this point in the history
Signed-off-by: Kimmo Lehto <[email protected]>
  • Loading branch information
kke committed Jun 13, 2024
1 parent 7ceb5b4 commit 2c1e665
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 11 deletions.
14 changes: 14 additions & 0 deletions lazy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//go:build go1.21

package validator

import (
"regexp"
"sync"
)

func lazyRegexCompile(str string) func() *regexp.Regexp {
return sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile(str)
})
}
19 changes: 19 additions & 0 deletions lazy_compat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//go:build !go1.21

package validator

import (
"regexp"
"sync"
)

func lazyRegexCompile(str string) func() *regexp.Regexp {
var regex *regexp.Regexp
var once sync.Once
return func() *regexp.Regexp {
once.Do(func() {
regex = regexp.MustCompile(str)
})
return regex
}
}
11 changes: 0 additions & 11 deletions regexes.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
package validator

import (
"regexp"
"sync"
)

const (
alphaRegexString = "^[a-zA-Z]+$"
alphaNumericRegexString = "^[a-zA-Z0-9]+$"
Expand Down Expand Up @@ -79,12 +74,6 @@ const (
spicedbTypeRegexString = "^([a-z][a-z0-9_]{1,61}[a-z0-9]/)?[a-z][a-z0-9_]{1,62}[a-z0-9]$"
)

func lazyRegexCompile(str string) func() *regexp.Regexp {
return sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile(str)
})
}

var (
alphaRegex = lazyRegexCompile(alphaRegexString)
alphaNumericRegex = lazyRegexCompile(alphaNumericRegexString)
Expand Down

0 comments on commit 2c1e665

Please sign in to comment.