-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmax_len.go
61 lines (50 loc) · 1.38 KB
/
max_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 (
// nameMaxLen is the name of the maximum length check.
nameMaxLen = "max-len"
)
var (
// ErrMaxLen indicates that the value's length is greater than the specified maximum.
ErrMaxLen = NewCheckError("NOT_MAX_LEN")
)
// MaxLen checks if the length of the given value (string, slice, or map) is at most n.
// Returns an error if the length is greater than n.
func MaxLen[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, newMaxLenError(n)
}
return value, nil
}
}
// makeMaxLen creates a maximum length check function from a string parameter.
// Panics if the parameter cannot be parsed as an integer.
func makeMaxLen(params string) CheckFunc[reflect.Value] {
n, err := strconv.Atoi(params)
if err != nil {
panic("unable to parse max length")
}
return MaxLen[reflect.Value](n)
}
// newMaxLenError creates a new maximum length error with the given maximum length.
func newMaxLenError(n int) error {
return NewCheckErrorWithData(
ErrMaxLen.Code,
map[string]interface{}{
"max": n,
},
)
}