-
Notifications
You must be signed in to change notification settings - Fork 1
/
min_len.go
61 lines (50 loc) · 1.37 KB
/
min_len.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
56
57
58
59
60
61
// Copyright (c) 2023-2024 Onur Cinar.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// https://github.com/cinar/checker
package v2
import (
"reflect"
"strconv"
)
const (
// nameMinLen is the name of the minimum length check.
nameMinLen = "min-len"
)
var (
// ErrMinLen indicates that the value's length is less than the specified minimum.
ErrMinLen = NewCheckError("NOT_MIN_LEN")
)
// MinLen checks if the length of the given value (string, slice, or map) is at least n.
// Returns an error if the length is less than n.
func MinLen[T any](n int) CheckFunc[T] {
return func(value T) (T, error) {
v, ok := any(value).(reflect.Value)
if !ok {
v = reflect.ValueOf(value)
}
v = reflect.Indirect(v)
if v.Len() < n {
return value, newMinLenError(n)
}
return value, nil
}
}
// makeMinLen creates a minimum length check function from a string parameter.
// Panics if the parameter cannot be parsed as an integer.
func makeMinLen(params string) CheckFunc[reflect.Value] {
n, err := strconv.Atoi(params)
if err != nil {
panic("unable to parse min length")
}
return MinLen[reflect.Value](n)
}
// newMinLenError creates a new minimum length error with the given minimum value.
func newMinLenError(n int) error {
return NewCheckErrorWithData(
ErrMinLen.Code,
map[string]interface{}{
"min": n,
},
)
}