forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
null_int.go
74 lines (60 loc) · 1.22 KB
/
null_int.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
package types
import (
"encoding/json"
"fmt"
"strconv"
)
// NullInt is a wrapper around integer values that can be null or an integer.
// Use IsSet to check if the value is provided, instead of checking against 0.
type NullInt struct {
IsSet bool
Value int
}
// ParseStringValue is used to parse a user provided flag argument.
func (n *NullInt) ParseStringValue(val string) error {
if val == "" {
return nil
}
intVal, err := strconv.Atoi(val)
if err != nil {
return err
}
n.Value = intVal
n.IsSet = true
return nil
}
// ParseIntValue is used to parse a user provided *int argument.
func (n *NullInt) ParseIntValue(val *int) {
if val == nil {
n.IsSet = false
n.Value = 0
return
}
n.Value = *val
n.IsSet = true
}
func (n *NullInt) UnmarshalJSON(rawJSON []byte) error {
var value json.Number
err := json.Unmarshal(rawJSON, &value)
if err != nil {
return err
}
if value.String() == "" {
n.Value = 0
n.IsSet = false
return nil
}
valueInt, err := strconv.Atoi(value.String())
if err != nil {
return err
}
n.Value = valueInt
n.IsSet = true
return nil
}
func (n NullInt) MarshalJSON() ([]byte, error) {
if n.IsSet {
return []byte(fmt.Sprint(n.Value)), nil
}
return []byte("null"), nil
}