-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.go
98 lines (86 loc) · 1.79 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Package util contains various general utility functions used
// throughout the project.
package util
import (
"crypto/md5"
"encoding/base64"
"math/rand"
"time"
)
var (
rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
)
// WrapError wraps error types to create compound error chains
func WrapError(text string, err error) error {
return wrappedError{
text: text,
inner: err,
}
}
type wrappedError struct {
text string
inner error
}
func (e wrappedError) Error() string {
text := e.text
if e.inner != nil {
text += ": " + e.inner.Error()
}
return text
}
// Waterfall executes a slice of functions until the first error returned. This
// error, if any, is returned to the caller.
func Waterfall(fns ...func() error) (err error) {
for _, fn := range fns {
err = fn()
if err != nil {
break
}
}
return
}
// HashBuffer computes a base64 MD5 hash from a buffer
func HashBuffer(buf []byte) string {
hash := md5.Sum(buf)
return base64.RawStdEncoding.EncodeToString(hash[:])
}
// CloneBytes creates a copy of b
func CloneBytes(b []byte) []byte {
cp := make([]byte, len(b))
copy(cp, b)
return cp
}
// Return a random integer N such that a <= N <= b.
func PseudoRandInt(a, b int) int {
d := b - a + 1
if d <= 0 {
return 0
}
n := rnd.Intn(d)
return n + a
}
type Task func() error
func runAsyncTasks(tasks []Task) (err error) {
ch := make(chan error)
for _, task := range tasks {
go func(task Task) {
ch <- task()
}(task)
}
for range tasks {
if err = <-ch; err != nil {
return
}
}
return
}
// Run tasks in the specified order. Exit on first error.
// Inspired by https://github.com/OverZealous/run-sequence
func RunTasks(tasks [][]Task) (err error) {
for _, asyncTasks := range tasks {
if err = runAsyncTasks(asyncTasks); err != nil {
return
}
}
return
}