-
Notifications
You must be signed in to change notification settings - Fork 0
/
empty_check.go
62 lines (54 loc) · 1.58 KB
/
empty_check.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
62
package dyntpl
// EmptyCheckFn describes empty check helper func signature.
type EmptyCheckFn func(ctx *Ctx, val any) bool
type EmptyCheckTuple struct {
docgen
fn EmptyCheckFn
}
var (
// Registry of empty check helpers.
emptyCheckRegistry = map[string]int{}
emptyCheckBuf []EmptyCheckTuple
)
// RegisterEmptyCheckFn registers new empty check helper.
func RegisterEmptyCheckFn(name string, cond EmptyCheckFn) *EmptyCheckTuple {
if idx, ok := emptyCheckRegistry[name]; ok && idx >= 0 && idx < len(emptyCheckBuf) {
return &emptyCheckBuf[idx]
}
emptyCheckBuf = append(emptyCheckBuf, EmptyCheckTuple{
docgen: docgen{name: name},
fn: cond,
})
idx := len(emptyCheckBuf) - 1
emptyCheckRegistry[name] = idx
return &emptyCheckBuf[idx]
}
// RegisterEmptyCheckFnNS registers new empty check helper.
func RegisterEmptyCheckFnNS(namespace, name string, cond EmptyCheckFn) *EmptyCheckTuple {
if len(namespace) > 0 {
name = namespace + "::" + name
}
return RegisterEmptyCheckFn(name, cond)
}
// GetEmptyCheckFn gets empty check helper from the registry.
func GetEmptyCheckFn(name string) EmptyCheckFn {
if idx, ok := emptyCheckRegistry[name]; ok && idx >= 0 && idx < len(emptyCheckBuf) {
return emptyCheckBuf[idx].fn
}
return nil
}
// EmptyCheck tries to apply all known helpers over the val.
//
// First acceptable helper will break next attempts.
func EmptyCheck(ctx *Ctx, val any) bool {
if val == nil {
return true
}
for i := 0; i < len(emptyCheckBuf); i++ {
if emptyCheckBuf[i].fn(ctx, val) {
return true
}
}
return false
}
var _, _ = GetEmptyCheckFn, RegisterEmptyCheckFnNS