mirror of
https://github.com/AdguardTeam/AdGuardHome.git
synced 2026-08-30 15:42:34 +00:00
Squashed commit of the following:
commit 9ca94b03ee255cf8810c72ffcf967ae348d796fd
Merge: 5516a95d0 44dfffc83
Author: Ainar Garipov <a.garipov@adguard.com>
Date: Fri Apr 24 15:44:56 2026 +0300
Merge branch 'master' into AGDNS-3945-imp-querylog
commit 5516a95d082dbe8acc85efb0833c63f7a7bde220
Author: Ainar Garipov <a.garipov@adguard.com>
Date: Thu Apr 23 17:10:12 2026 +0300
all: imp doc, names
commit 6e8ab1387a0d7e20cffca8dbc99f08a9acb440c1
Author: Ainar Garipov <a.garipov@adguard.com>
Date: Wed Apr 22 21:51:04 2026 +0300
all: imp go.mod, names, errors
commit 20f5e335c1f3c21d7cc6ec6dd57389507627ba3d
Author: Ainar Garipov <a.garipov@adguard.com>
Date: Wed Apr 22 21:02:13 2026 +0300
all: modernize code; imp querylog
67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
// Package aghalg contains common generic algorithms and data structures.
|
|
//
|
|
// TODO(a.garipov): Move parts of this into golibs.
|
|
package aghalg
|
|
|
|
import (
|
|
"cmp"
|
|
"fmt"
|
|
"slices"
|
|
)
|
|
|
|
// 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.
|
|
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 cmp.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)
|
|
}
|