-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathsyntax_validator.go
70 lines (60 loc) · 1.93 KB
/
syntax_validator.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
63
64
65
66
67
68
69
70
package iotago
import (
"github.com/iotaledger/hive.go/constraints"
"github.com/iotaledger/hive.go/ierrors"
)
// ElementValidationFunc is a func that, given the index of a slice element and the element itself
// runs syntactical validations and returns an error if it fails.
type ElementValidationFunc[T any] func(index int, next T) error
// An ElementValidationFunc that checks lexical order and uniqueness based on the Compare implementation.
func LexicalOrderAndUniquenessValidator[T constraints.Comparable[T]]() ElementValidationFunc[T] {
var prev *T
var prevIndex int
return func(index int, next T) error {
if prev == nil {
prev = &next
prevIndex = index
} else {
switch (*prev).Compare(next) {
case 1:
return ierrors.WithMessagef(ErrArrayValidationOrderViolatesLexicalOrder, "element %d should have been before element %d", index, prevIndex)
case 0:
return ierrors.WithMessagef(ErrArrayValidationViolatesUniqueness, "element %d and element %d are duplicates", index, prevIndex)
}
prev = &next
prevIndex = index
}
return nil
}
}
// SliceValidator iterates over a slice and calls elementValidationFunc on each element,
// returning the first error it encounters, if any.
func SliceValidator[T any](
slice []T,
elementValidationFuncs ...ElementValidationFunc[T],
) error {
for i, element := range slice {
for _, f := range elementValidationFuncs {
if err := f(i, element); err != nil {
return err
}
}
}
return nil
}
// SliceValidatorMapper iterates over a slice and calls elementValidationFunc on each element,
// after mapping it with mapper and returning the first error it encounters, if any.
func SliceValidatorMapper[U, T any](
slice []U,
mapper func(U) T,
elementValidationFuncs ...ElementValidationFunc[T],
) error {
for i, element := range slice {
for _, f := range elementValidationFuncs {
if err := f(i, mapper(element)); err != nil {
return err
}
}
}
return nil
}