-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc.go
51 lines (45 loc) · 1.18 KB
/
func.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package constraints
// ValidatorFunc is an adapter to allow use of ordinary functions
// as a validator in constraints.
type ValidatorFunc[ValueT any] func(i ValueT) bool
// Func creates a constraint from a validator function.
//
// A good example is for defining a constraint to ensure that provided
// string is a valid UTF8-encoded string:
//
// import "unicode/utf8"
//
// var mustUTF8 = Func("valid UTF-8", utf8.ValidString)
//
// Or regular expression string matcher:
//
// var usernamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9]+$`)
// var usernameConstraint = Func("username", usernamePattern.MatchString)
func Func[
ValueT any,
](desc string, fn func(v ValueT) bool) Constraint[ValueT] {
return &constraintFunc[ValueT]{
negate: false,
desc: desc,
fn: fn,
}
}
var (
_ Constraint[int64] = &constraintFunc[int64]{}
_ Constraint[int64] = constraintFunc[int64]{}
)
type constraintFunc[ValueT any] struct {
negate bool
desc string
fn ValidatorFunc[ValueT]
}
func (c constraintFunc[ValueT]) ConstraintDescription() string {
return c.desc
}
func (c constraintFunc[ValueT]) IsValid(v ValueT) bool {
result := c.fn(v)
if c.negate {
return !result
}
return result
}