-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
86 lines (73 loc) · 1.76 KB
/
string.go
File metadata and controls
86 lines (73 loc) · 1.76 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package zed
import (
"github.com/ogen-go/ogen"
"regexp"
)
var _ Schema[string] = (*StringSchema)(nil)
var ruleMinLen = defineRule[string, uint64](
"minLen",
func(s string, u uint64) bool {
return len(s) >= int(u)
},
func(r *rule[string, uint64], schema *ogen.Schema) {
schema.SetMinLength(&r.value)
},
)
var ruleMaxLen = defineRule[string, uint64](
"maxLen",
func(s string, u uint64) bool {
return len(s) <= int(u)
},
func(r *rule[string, uint64], schema *ogen.Schema) {
schema.SetMaxLength(&r.value)
},
)
var rulePattern = defineRule[string, *regexp.Regexp](
"pattern",
func(s string, r *regexp.Regexp) bool {
return r.MatchString(s)
},
func(r *rule[string, *regexp.Regexp], schema *ogen.Schema) {
schema.SetPattern(r.value.String())
},
)
type StringSchema struct {
*baseSchema[string, string]
}
func newStrSchema(err string) *StringSchema {
return &StringSchema{
baseSchema: newBaseSchema[string, string](err),
}
}
func (s *StringSchema) MinLen(l uint64, err string) *StringSchema {
s.rules.add(ruleMinLen(l, err))
return s
}
func (s *StringSchema) MaxLen(l uint64, err string) *StringSchema {
s.rules.add(ruleMaxLen(l, err))
return s
}
func (s *StringSchema) Pattern(p string, err string) *StringSchema {
s.rules.add(rulePattern(regexp.MustCompile(p), err))
return s
}
func (s *StringSchema) Validate(v any, flags SchemaValidationFlag) (out string, e error) {
val, vOk := v.(string)
if !vOk {
e = s.err
return
}
e = s.rules.apply(val, flags.Has(AbortEarly))
out = val
return
}
func (s *StringSchema) ValidateGeneric(v any, flags SchemaValidationFlag) (any, error) {
return s.Validate(v, flags)
}
func (s *StringSchema) ToSchema() (os *ogen.Schema) {
os = ogen.String()
for _, r := range s.rules {
r.interceptSchema(os)
}
return
}