-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.go
69 lines (51 loc) · 1.17 KB
/
utils.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
package helpers
import (
"bytes"
"reflect"
"time"
)
func IsMetadata(data interface{}) bool {
value := reflect.ValueOf(data).FieldByName("Key")
if !value.IsValid() {
return false
}
return bytes.HasPrefix(value.Bytes(), []byte(Prefix)) || bytes.HasPrefix(value.Bytes(), []byte(TxnPrefix))
}
func ChunkSlice[T any](slice []T, chunks int) [][]T {
maxChunkSize := ((len(slice) - 1) / chunks) + 1
numFullChunks := chunks - (maxChunkSize*chunks - len(slice))
result := make([][]T, chunks)
startIndex := 0
for i := 0; i < chunks; i++ {
endIndex := startIndex + maxChunkSize
if i >= numFullChunks {
endIndex--
}
result[i] = slice[startIndex:endIndex]
startIndex = endIndex
}
return result
}
func ChunkSliceWithSize[T any](slice []T, chunkSize int) [][]T {
var chunks [][]T
for i := 0; i < len(slice); i += chunkSize {
end := i + chunkSize
if end > len(slice) {
end = len(slice)
}
chunks = append(chunks, slice[i:end])
}
return chunks
}
func Retry(f func() error, attempts int, sleep time.Duration) (err error) {
for i := 0; i < attempts; i++ {
if i > 0 {
time.Sleep(sleep)
}
err = f()
if err == nil {
return nil
}
}
return err
}