2022-01-19 17:45:50 +00:00
|
|
|
// Package aghalg contains common generic algorithms and data structures.
|
2021-12-28 14:00:52 +00:00
|
|
|
//
|
|
|
|
// TODO(a.garipov): Update to use type parameters in Go 1.18.
|
2022-01-19 17:45:50 +00:00
|
|
|
package aghalg
|
2021-12-28 14:00:52 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
|
|
|
// comparable is an alias for interface{}. Values passed as arguments of this
|
|
|
|
// type alias must be comparable.
|
|
|
|
//
|
|
|
|
// TODO(a.garipov): Remove in Go 1.18.
|
|
|
|
type comparable = interface{}
|
|
|
|
|
2022-01-19 17:45:50 +00:00
|
|
|
// UniqChecker allows validating uniqueness of comparable items.
|
|
|
|
type UniqChecker map[comparable]int64
|
2021-12-28 14:00:52 +00:00
|
|
|
|
|
|
|
// Add adds a value to the validator. v must not be nil.
|
2022-01-19 17:45:50 +00:00
|
|
|
func (uc UniqChecker) Add(elems ...comparable) {
|
2021-12-28 14:00:52 +00:00
|
|
|
for _, e := range elems {
|
2022-01-19 17:45:50 +00:00
|
|
|
uc[e]++
|
2021-12-28 14:00:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-20 14:19:09 +00:00
|
|
|
// Merge returns a checker containing data from both uc and other.
|
2022-01-19 17:45:50 +00:00
|
|
|
func (uc UniqChecker) Merge(other UniqChecker) (merged UniqChecker) {
|
|
|
|
merged = make(UniqChecker, len(uc)+len(other))
|
|
|
|
for elem, num := range uc {
|
2021-12-28 14:00:52 +00:00
|
|
|
merged[elem] += num
|
|
|
|
}
|
|
|
|
|
|
|
|
for elem, num := range other {
|
|
|
|
merged[elem] += num
|
|
|
|
}
|
|
|
|
|
|
|
|
return merged
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate returns an error enumerating all elements that aren't unique.
|
|
|
|
// isBefore is an optional sorting function to make the error message
|
|
|
|
// deterministic.
|
2022-01-19 17:45:50 +00:00
|
|
|
func (uc UniqChecker) Validate(isBefore func(a, b comparable) (less bool)) (err error) {
|
2021-12-28 14:00:52 +00:00
|
|
|
var dup []comparable
|
2022-01-19 17:45:50 +00:00
|
|
|
for elem, num := range uc {
|
2021-12-28 14:00:52 +00:00
|
|
|
if num > 1 {
|
|
|
|
dup = append(dup, elem)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(dup) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if isBefore != nil {
|
|
|
|
sort.Slice(dup, func(i, j int) (less bool) {
|
|
|
|
return isBefore(dup[i], dup[j])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Errorf("duplicated values: %v", dup)
|
|
|
|
}
|
|
|
|
|
2022-01-19 17:45:50 +00:00
|
|
|
// IntIsBefore is a helper sort function for UniqChecker.Validate.
|
2021-12-28 14:00:52 +00:00
|
|
|
// a and b must be of type int.
|
|
|
|
func IntIsBefore(a, b comparable) (less bool) {
|
|
|
|
return a.(int) < b.(int)
|
|
|
|
}
|
|
|
|
|
2022-01-19 17:45:50 +00:00
|
|
|
// StringIsBefore is a helper sort function for UniqChecker.Validate.
|
2021-12-28 14:00:52 +00:00
|
|
|
// a and b must be of type string.
|
|
|
|
func StringIsBefore(a, b comparable) (less bool) {
|
|
|
|
return a.(string) < b.(string)
|
|
|
|
}
|