-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbool.go
More file actions
115 lines (99 loc) · 1.84 KB
/
bool.go
File metadata and controls
115 lines (99 loc) · 1.84 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package nulled
import (
"bytes"
"encoding/gob"
"encoding/json"
"net/url"
"strconv"
"gopkg.in/guregu/null.v4"
)
type Bool null.Bool
func NewBool(b bool, valid bool) Bool {
return Bool(null.NewBool(b, valid))
}
func BoolFrom(b bool) Bool {
return NewBool(b, true)
}
func BoolFromPtr(b *bool) Bool {
if b == nil {
return NewBool(false, false)
}
return NewBool(*b, true)
}
func (b Bool) ValueOrZero() bool {
if !b.Valid {
return false
}
return b.Bool
}
func (b Bool) EncodeValues(key string, v *url.Values) error {
if !b.Valid {
return nil
}
if b.Bool {
v.Set(key, "1")
} else {
v.Set(key, "0")
}
return nil
}
func (b Bool) MarshalJSON() ([]byte, error) {
if !b.Valid {
return []byte("null"), nil
}
return json.Marshal(b.Bool)
}
func (b *Bool) UnmarshalJSON(data []byte) error {
var bo null.Bool
if err := json.Unmarshal(data, &bo); err != nil {
b.Valid = false
return err
}
b.Bool = bo.Bool
b.Valid = bo.Valid
return nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (b *Bool) UnmarshalText(text []byte) error {
s := string(text)
if s == "" || s == "null" {
b.Valid = false
return nil
}
var err error
b.Bool, err = strconv.ParseBool(s)
if err != nil {
b.Valid = false
return err
}
b.Valid = true
return nil
}
func (b Bool) GobEncode() ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(b.Bool)
if err != nil {
return nil, err
}
err = enc.Encode(b.Valid)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (b *Bool) GobDecode(data []byte) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
err := dec.Decode(&b.Bool)
if err != nil {
return err
}
return dec.Decode(&b.Valid)
}
func (b Bool) NullValue() null.Bool {
if b.Valid {
return null.BoolFrom(b.Bool)
}
return null.NewBool(false, false)
}