Skip to content

Commit 61e16c9

Browse files
committed
Use sync.OnceValue only on go1.21+
sync.OnceValue was introduced in go1.21. Currently validator's go.mod states minimum go version to be go1.18. This commit moves the lazy regex initialization into its own file lazy.go and provides backwards compatibility using buildtags and the file lazy_compat.go. Signed-off-by: Kimmo Lehto <[email protected]>
1 parent 624b51d commit 61e16c9

File tree

3 files changed

+33
-11
lines changed

3 files changed

+33
-11
lines changed

lazy.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
//go:build go1.21
2+
3+
package validator
4+
5+
import (
6+
"regexp"
7+
"sync"
8+
)
9+
10+
func lazyRegexCompile(str string) func() *regexp.Regexp {
11+
return sync.OnceValue(func() *regexp.Regexp {
12+
return regexp.MustCompile(str)
13+
})
14+
}

lazy_compat.go

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//go:build !go1.21
2+
3+
package validator
4+
5+
import (
6+
"regexp"
7+
"sync"
8+
)
9+
10+
func lazyRegexCompile(str string) func() *regexp.Regexp {
11+
var regex *regexp.Regexp
12+
var once sync.Once
13+
return func() *regexp.Regexp {
14+
once.Do(func() {
15+
regex = regexp.MustCompile(str)
16+
})
17+
return regex
18+
}
19+
}

regexes.go

-11
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
package validator
22

3-
import (
4-
"regexp"
5-
"sync"
6-
)
7-
83
const (
94
alphaRegexString = "^[a-zA-Z]+$"
105
alphaNumericRegexString = "^[a-zA-Z0-9]+$"
@@ -79,12 +74,6 @@ const (
7974
spicedbTypeRegexString = "^([a-z][a-z0-9_]{1,61}[a-z0-9]/)?[a-z][a-z0-9_]{1,62}[a-z0-9]$"
8075
)
8176

82-
func lazyRegexCompile(str string) func() *regexp.Regexp {
83-
return sync.OnceValue(func() *regexp.Regexp {
84-
return regexp.MustCompile(str)
85-
})
86-
}
87-
8877
var (
8978
alphaRegex = lazyRegexCompile(alphaRegexString)
9079
alphaNumericRegex = lazyRegexCompile(alphaNumericRegexString)

0 commit comments

Comments
 (0)