-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathutils.go
More file actions
270 lines (216 loc) · 5.08 KB
/
utils.go
File metadata and controls
270 lines (216 loc) · 5.08 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package do
import (
"context"
"crypto/rand"
"fmt"
"io"
"reflect"
"sync"
)
//
// This file could be replaced with a dependency on a library like samber/lo, but I wanted to keep the dependencies to a minimum.
//
func empty[T any]() (t T) {
return t
}
func deepEmpty[T any]() T {
var o T
t := reflect.TypeOf(o)
v := deepEmptyMakeValue(t) // reflect.Value with the desired shape
return v.Interface().(T) //nolint:errcheck,forcetypeassert
}
func deepEmptyMakeValue(t reflect.Type) reflect.Value {
// Base case: not a pointer -> just zero of this type.
if t.Kind() != reflect.Ptr {
return reflect.Zero(t)
}
// Recursive case: pointer -> allocate pointer, set its Elem to the
// recursively-constructed zero value of the element type.
elem := deepEmptyMakeValue(t.Elem())
p := reflect.New(t.Elem())
p.Elem().Set(elem)
return p
}
func must0(err error) {
if err != nil {
panic(err)
}
}
func must1[A any](a A, err error) A {
if err != nil {
panic(err)
}
return a
}
func keys[K comparable, V any](in map[K]V) []K {
result := make([]K, 0, len(in))
for k := range in {
result = append(result, k)
}
return result
}
func flatten[T any](collection [][]T) []T {
totalLen := 0
for i := range collection {
totalLen += len(collection[i])
}
result := make([]T, 0, totalLen)
for i := range collection {
result = append(result, collection[i]...)
}
return result
}
func mAp[T any, R any](collection []T, iteratee func(T, int) R) []R {
result := make([]R, len(collection))
for i, item := range collection {
result[i] = iteratee(item, i)
}
return result
}
func typeIsAssignable[T, AssignTo any]() bool {
_, ok := any((*T)(nil)).(*AssignTo)
return ok
}
func filter[V any](collection []V, predicate func(item V, index int) bool) []V {
result := make([]V, 0, len(collection))
for i, item := range collection {
if predicate(item, i) {
result = append(result, item)
}
}
return result
}
func reverseSlice[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func orderedUniq[V comparable](in []V) []V {
out := []V{}
present := map[V]struct{}{}
for _, v := range in {
if _, ok := present[v]; !ok {
out = append(out, v)
present[v] = struct{}{}
}
}
return out
}
func contains[T comparable](list []T, elem T) bool {
for _, v := range list {
if v == elem {
return true
}
}
return false
}
func coalesce[T comparable](v ...T) (result T) {
for _, e := range v {
if e != result {
result = e
break
}
}
return result
}
// https://gist.github.com/rkravchik/d9733e1d2d626188eb91df751471d739
func newUUID() (string, error) {
uuid := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, uuid)
if n != len(uuid) || err != nil {
return "", err
}
// variant bits; see section 4.1.1
uuid[8] = uuid[8]&^0xc0 | 0x80
// version 4 (pseudo-random); see section 4.1.3
uuid[6] = uuid[6]&^0xf0 | 0x40
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}
func newJobPool[R any](parallelism uint) *jobPool[R] {
return &jobPool[R]{
parallelism: parallelism,
jobs: make(chan func(), 1000), // 🤮 @TODO: change that
startOnce: sync.Once{},
stopOnce: sync.Once{},
}
}
type jobPool[R any] struct {
parallelism uint
jobs chan func()
startOnce sync.Once
stopOnce sync.Once
}
func (p *jobPool[R]) rpc(f func() R) <-chan R {
c := make(chan R, 1) // a single message will be sent before closing
p.jobs <- func() {
defer close(c)
c <- f()
}
return c
}
func (p *jobPool[R]) start() {
p.startOnce.Do(func() {
//nolint:gosec
for i := 0; i < int(p.parallelism); i++ {
go func() {
for job := range p.jobs {
job()
}
}()
}
})
}
func (p *jobPool[R]) stop() {
p.stopOnce.Do(func() {
close(p.jobs)
})
}
func raceWithTimeout(ctx context.Context, fn func(context.Context) error) error {
_, ok := ctx.Deadline()
if !ok {
return fn(ctx)
}
err := make(chan error, 1)
go func() {
err <- fn(ctx)
}()
select {
case e := <-err:
return e
case <-ctx.Done():
return fmt.Errorf("%w: %s", ErrHealthCheckTimeout, ctx.Err()) //nolint:errorlint
}
}
// Previously, we used to perform check like this:
// _, ok := any(empty[Initial]()).(Alias)
// But it was not working when Initial was an interface, so we now
// use reflection to check if Initial implements Alias.
func genericCanCastToGeneric[From any, To any]() bool {
var from From
anyFrom := any(from)
if anyFrom == nil { // check for interface by reflect
typeFrom := reflect.TypeOf(&from).Elem()
typeTo := reflect.TypeOf((*To)(nil)).Elem()
toInterface := typeTo.Kind() == reflect.Interface
return toInterface && typeFrom.Implements(typeTo)
}
_, ok := anyFrom.(To)
return ok
}
func typeCanCastToGeneric[To any](fromType reflect.Type) bool {
toType := reflect.TypeOf((*To)(nil)).Elem()
return typeCanCastToType(fromType, toType)
}
func typeCanCastToType(fromType reflect.Type, toType reflect.Type) bool {
if fromType == nil {
return false
}
if fromType == toType {
return true
}
// Check assignable
if fromType.AssignableTo(toType) {
return true
}
return false
}