-
Notifications
You must be signed in to change notification settings - Fork 0
/
aghalg.go
89 lines (74 loc) · 2.06 KB
/
aghalg.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Package aghalg contains common generic algorithms and data structures.
//
// TODO(a.garipov): Move parts of this into golibs.
package aghalg
import (
"fmt"
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
)
// Coalesce returns the first non-zero value. It is named after function
// COALESCE in SQL. If values or all its elements are empty, it returns a zero
// value.
//
// T is comparable, because Go currently doesn't have a comparableWithZeroValue
// constraint.
//
// TODO(a.garipov): Think of ways to merge with [CoalesceSlice].
func Coalesce[T comparable](values ...T) (res T) {
var zero T
for _, v := range values {
if v != zero {
return v
}
}
return zero
}
// CoalesceSlice returns the first non-zero value. It is named after function
// COALESCE in SQL. If values or all its elements are empty, it returns nil.
//
// TODO(a.garipov): Think of ways to merge with [Coalesce].
func CoalesceSlice[E any, S []E](values ...S) (res S) {
for _, v := range values {
if v != nil {
return v
}
}
return nil
}
// UniqChecker allows validating uniqueness of comparable items.
//
// TODO(a.garipov): The Ordered constraint is only really necessary in Validate.
// Consider ways of making this constraint comparable instead.
type UniqChecker[T constraints.Ordered] map[T]int64
// Add adds a value to the validator. v must not be nil.
func (uc UniqChecker[T]) Add(elems ...T) {
for _, e := range elems {
uc[e]++
}
}
// Merge returns a checker containing data from both uc and other.
func (uc UniqChecker[T]) Merge(other UniqChecker[T]) (merged UniqChecker[T]) {
merged = make(UniqChecker[T], len(uc)+len(other))
for elem, num := range uc {
merged[elem] += num
}
for elem, num := range other {
merged[elem] += num
}
return merged
}
// Validate returns an error enumerating all elements that aren't unique.
func (uc UniqChecker[T]) Validate() (err error) {
var dup []T
for elem, num := range uc {
if num > 1 {
dup = append(dup, elem)
}
}
if len(dup) == 0 {
return nil
}
slices.Sort(dup)
return fmt.Errorf("duplicated values: %v", dup)
}