-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathone_of.go
55 lines (48 loc) · 1.32 KB
/
one_of.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
52
53
54
55
package constraints
import (
"fmt"
"strings"
)
// OneOf creates a Constraint which will declare a value as valid
// if it matches one of the options.
//
// API status: experimental
func OneOf[ValueT comparable](options ...ValueT) Constraint[ValueT] {
copies := make([]ValueT, len(options))
copy(copies, options)
return &oneOfConstraint[ValueT]{negate: false, options: options}
}
func NoneOf[ValueT comparable](options ...ValueT) Constraint[ValueT] {
copies := make([]ValueT, len(options))
copy(copies, options)
return &oneOfConstraint[ValueT]{negate: true, options: options}
}
// oneOfConstraint defines choice-based Constraint.
type oneOfConstraint[ValueT comparable] struct {
negate bool
options []ValueT
}
var (
_ Constraint[string] = oneOfConstraint[string]{}
)
// ConstraintDescription conforms constraints.Constraint interface.
func (c oneOfConstraint[ValueT]) ConstraintDescription() string {
var opts []string
for _, o := range c.options {
opts = append(opts, fmt.Sprintf("%v", o))
}
opt := "[" + strings.Join(opts, ", ") + "]"
if c.negate {
return fmt.Sprintf("none of %v", opt)
}
return fmt.Sprintf("one of %v", opt)
}
// IsValid conforms Constraint interface.
func (c oneOfConstraint[ValueT]) IsValid(v ValueT) bool {
for _, s := range c.options {
if s == v {
return !c.negate
}
}
return c.negate
}