-
Notifications
You must be signed in to change notification settings - Fork 250
/
util.go
80 lines (69 loc) · 1.65 KB
/
util.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
package util
import (
"sort"
"golang.org/x/exp/constraints"
)
// Zero returns the zero value of a type
func Zero[T any]() (_ T) {
return
}
// CopyMap creates a new map copying all key/values from its argument
func CopyMap[K comparable, V any](m map[K]V) map[K]V {
ret := make(map[K]V, len(m))
for k, v := range m {
ret[k] = v
}
return ret
}
// SortSlice is a generic version of sort.Slice
func SortSlice[T constraints.Ordered](s []T) {
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}
// Keys returns a slice with the keys in `m` in unspecified order
func Keys[K comparable, V any](m map[K]V) (ret []K) {
ret = make([]K, 0, len(m))
for k := range m {
ret = append(ret, k)
}
return
}
// SortedKeys returns a slice with the keys in `m` in sorted order
func SortedKeys[K constraints.Ordered, V any](m map[K]V) (ret []K) {
ret = Keys(m)
SortSlice(ret)
return
}
// Contains performs a linear search on `s` looking for `x`.
func Contains[T comparable](s []T, x T) bool {
for _, y := range s {
if x == y {
return true
}
}
return false
}
// RemoveIf retains only elements which are not selected by a predicate
// The slice is modified in place and (potentially a subset) is returned.
func RemoveIf[T any](s []T, p func(T) bool) []T {
i := 0
for _, x := range s {
if !p(x) {
s[i] = x
i++
}
}
return s[:i]
}
// IsBitSet tests if a single specific bit is set in a value
func IsBitSet[T constraints.Integer](x, b T) bool {
return x&b != Zero[T]()
}
// PopCount returns the number of "true" argument values.
func PopCount[T comparable](xs ...T) (ret uint) {
for _, x := range xs {
if x != Zero[T]() {
ret += 1
}
}
return
}