-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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 which contains a backported (non-generic) version of sync.OnceValue. Signed-off-by: Kimmo Lehto <[email protected]>
- Loading branch information
Showing
3 changed files
with
60 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
//go:build !go1.21 | ||
|
||
package validator | ||
|
||
import ( | ||
"regexp" | ||
"sync" | ||
) | ||
|
||
// Copied and adapted from go1.21 stdlib's sync.OnceValue for backwards compatibility: | ||
// OnceValue returns a function that invokes f only once and returns the value | ||
// returned by f. The returned function may be called concurrently. | ||
// | ||
// If f panics, the returned function will panic with the same value on every call. | ||
func onceValue(f func() *regexp.Regexp) func() *regexp.Regexp { | ||
var ( | ||
once sync.Once | ||
valid bool | ||
p any | ||
result *regexp.Regexp | ||
) | ||
g := func() { | ||
defer func() { | ||
p = recover() | ||
if !valid { | ||
panic(p) | ||
} | ||
}() | ||
result = f() | ||
f = nil | ||
valid = true | ||
} | ||
return func() *regexp.Regexp { | ||
once.Do(g) | ||
if !valid { | ||
panic(p) | ||
} | ||
return result | ||
} | ||
} | ||
|
||
func lazyRegexCompile(str string) func() *regexp.Regexp { | ||
return onceValue(func() *regexp.Regexp { | ||
return regexp.MustCompile(str) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters