-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry_value.go
57 lines (47 loc) · 1.03 KB
/
retry_value.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
package gokogeri
import (
"encoding/json"
"fmt"
"strconv"
)
var jsonFalse = []byte{'f', 'a', 'l', 's', 'e'}
var jsonTrue = []byte{'t', 'r', 'u', 'e'}
type retryValue struct {
ok bool
times int
}
// MarshalJSON implements json.Marshaler.
func (r retryValue) MarshalJSON() ([]byte, error) {
if !r.ok {
return jsonFalse, nil
}
if r.times > 0 {
return []byte(strconv.FormatInt(int64(r.times), 10)), nil
}
return jsonTrue, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (r *retryValue) UnmarshalJSON(b []byte) error {
if isJSONTrue(b) {
r.ok = true
return nil
}
if isJSONFalse(b) {
r.ok = false
return nil
}
var n int
err := json.Unmarshal(b, &n)
if err != nil {
return fmt.Errorf("decoding job retry value: %v", err)
}
r.ok = n > 0
r.times = n
return nil
}
func isJSONFalse(b []byte) bool {
return len(b) == 5 && b[0] == 'f' && b[1] == 'a' && b[2] == 'l' && b[3] == 's' && b[4] == 'e'
}
func isJSONTrue(b []byte) bool {
return len(b) == 4 && b[0] == 't' && b[1] == 'r' && b[2] == 'u' && b[3] == 'e'
}