forked from ziipin-server/niuhe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opint.go
63 lines (53 loc) · 966 Bytes
/
opint.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
package niuhe
import "strconv"
type OpInt struct {
value *int
store int
}
func (f *OpInt) Exists() bool {
return f.value != nil
}
func (f *OpInt) Value() (int, bool) {
if !f.Exists() {
return 0, false
}
return *f.value, true
}
func (f *OpInt) MustValue() int {
if v, exists := f.Value(); !exists {
panic("value not set")
} else {
return v
}
}
func (f *OpInt) ValueDefault(defaultValue int) int {
if v, exists := f.Value(); !exists {
return defaultValue
} else {
return v
}
}
func (f *OpInt) Set(value int) {
if !f.Exists() {
f.value = &f.store
}
f.store = value
}
func (f *OpInt) Clear() {
f.value = nil
}
func (f OpInt) MarshalJSON() ([]byte, error) {
if val, exists := f.Value(); exists {
return []byte(strconv.Itoa(val)), nil
} else {
return []byte("null"), nil
}
}
func (f *OpInt) UnmarshalJSON(bytes []byte) error {
val, err := strconv.Atoi(string(bytes))
if err != nil {
return err
}
f.Set(val)
return nil
}