summaryrefslogtreecommitdiff
path: root/lib/util/generic.go
blob: 688272401168de49ce48a4eac72e0b76750d5ee6 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package util

import (
	"sort"
	"sync"

	"golang.org/x/exp/constraints"
)

func InSlice[T comparable](needle T, haystack []T) bool {
	for _, straw := range haystack {
		if needle == straw {
			return true
		}
	}
	return false
}

func RemoveAllFromSlice[T comparable](haystack []T, needle T) []T {
	for i, straw := range haystack {
		if needle == straw {
			return append(
				haystack[:i],
				RemoveAllFromSlice(haystack[i+1:], needle)...)
		}
	}
	return haystack
}

func RemoveAllFromSliceFunc[T any](haystack []T, f func(T) bool) []T {
	for i, straw := range haystack {
		if f(straw) {
			return append(
				haystack[:i],
				RemoveAllFromSliceFunc(haystack[i+1:], f)...)
		}
	}
	return haystack
}

func ReverseSlice[T any](slice []T) {
	for i := 0; i < len(slice)/2; i++ {
		j := (len(slice) - 1) - i
		slice[i], slice[j] = slice[j], slice[i]
	}
}

func Max[T constraints.Ordered](a, b T) T {
	if a > b {
		return a
	}
	return b
}

func Min[T constraints.Ordered](a, b T) T {
	if a < b {
		return a
	}
	return b
}

func MapKeys[K comparable, V any](m map[K]V) []K {
	ret := make([]K, 0, len(m))
	for k := range m {
		ret = append(ret, k)
	}
	return ret
}

func SortSlice[T constraints.Ordered](slice []T) {
	sort.Slice(slice, func(i, j int) bool {
		return slice[i] < slice[j]
	})
}

func SortedMapKeys[K constraints.Ordered, V any](m map[K]V) []K {
	ret := MapKeys(m)
	SortSlice(ret)
	return ret
}

func CmpUint[T constraints.Unsigned](a, b T) int {
	switch {
	case a < b:
		return -1
	case a == b:
		return 0
	default:
		return 1
	}
}

type SyncMap[K comparable, V any] struct {
	inner sync.Map
}

func (m *SyncMap[K, V]) Delete(key K) { m.inner.Delete(key) }
func (m *SyncMap[K, V]) Load(key K) (value V, ok bool) {
	_value, ok := m.inner.Load(key)
	if ok {
		value = _value.(V)
	}
	return value, ok
}
func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
	_value, ok := m.inner.LoadAndDelete(key)
	if ok {
		value = _value.(V)
	}
	return value, ok
}
func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
	_actual, loaded := m.inner.LoadOrStore(key, value)
	actual = _actual.(V)
	return actual, loaded
}
func (m *SyncMap[K, V]) Range(f func(key K, value V) bool) {
	m.inner.Range(func(key, value any) bool {
		return f(key.(K), value.(V))
	})
}
func (m *SyncMap[K, V]) Store(key K, value V) { m.inner.Store(key, value) }