Skip to content

Commit 2c1e665

Browse files
committed
Use sync.OnceValue only on go1.21+
Signed-off-by: Kimmo Lehto <[email protected]>
1 parent 7ceb5b4 commit 2c1e665

File tree

3 files changed

+33
-11
lines changed

3 files changed

+33
-11
lines changed

lazy.go

Lines changed: 14 additions & 0 deletions
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

Lines changed: 19 additions & 0 deletions
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

Lines changed: 0 additions & 11 deletions
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)