-
Notifications
You must be signed in to change notification settings - Fork 91
/
util.go
81 lines (66 loc) · 1.33 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
package jsonrpc
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"reflect"
"time"
)
type param struct {
data []byte // from unmarshal
v reflect.Value // to marshal
}
func (p *param) UnmarshalJSON(raw []byte) error {
p.data = make([]byte, len(raw))
copy(p.data, raw)
return nil
}
func (p *param) MarshalJSON() ([]byte, error) {
if p.v.Kind() == reflect.Invalid {
return p.data, nil
}
return json.Marshal(p.v.Interface())
}
// processFuncOut finds value and error Outs in function
func processFuncOut(funcType reflect.Type) (valOut int, errOut int, n int) {
errOut = -1 // -1 if not found
valOut = -1
n = funcType.NumOut()
switch n {
case 0:
case 1:
if funcType.Out(0) == errorType {
errOut = 0
} else {
valOut = 0
}
case 2:
valOut = 0
errOut = 1
if funcType.Out(1) != errorType {
panic("expected error as second return value")
}
default:
errstr := fmt.Sprintf("too many return values: %s", funcType)
panic(errstr)
}
return
}
type backoff struct {
minDelay time.Duration
maxDelay time.Duration
}
func (b *backoff) next(attempt int) time.Duration {
if attempt < 0 {
return b.minDelay
}
minf := float64(b.minDelay)
durf := minf * math.Pow(1.5, float64(attempt))
durf = durf + rand.Float64()*minf
delay := time.Duration(durf)
if delay > b.maxDelay {
return b.maxDelay
}
return delay
}