-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidatorsmap.go
More file actions
62 lines (58 loc) · 1.29 KB
/
validatorsmap.go
File metadata and controls
62 lines (58 loc) · 1.29 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
package keycheck
type (
validatorEntry[T any] struct {
id string
status Status
validator func(a T) (bool, error)
}
validatorsMap[T any] struct {
entries []validatorEntry[T]
index map[string]int
}
)
func (vm validatorsMap[T]) Get(id string) (Status, func(a T) (bool, error), bool) {
if vm.index == nil {
return Status{}, nil, false
}
i, ok := vm.index[id]
if !ok {
return Status{}, nil, false
}
d := vm.entries[i]
return d.status, d.validator, true
}
func (vm *validatorsMap[T]) Set(status Status, fn func(a T) (bool, error)) {
if vm.index == nil {
vm.index = map[string]int{}
}
if i, ok := vm.index[status.ID]; ok {
vm.entries[i].id = status.ID
vm.entries[i].status = status
vm.entries[i].validator = fn
return
}
vm.entries = append(vm.entries, validatorEntry[T]{
id: status.ID,
status: status,
validator: fn,
})
vm.index[status.ID] = len(vm.entries) - 1
}
func (vm *validatorsMap[T]) Del(id string) bool {
if vm.index == nil {
return false
}
i, ok := vm.index[id]
if !ok {
return false
}
delete(vm.index, id)
last := len(vm.entries) - 1
copy(vm.entries[i:], vm.entries[i+1:])
vm.entries[last] = validatorEntry[T]{}
vm.entries = vm.entries[:last]
for j := i; j < len(vm.entries); j++ {
vm.index[vm.entries[j].id] = j
}
return true
}