-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.go
132 lines (111 loc) · 2.5 KB
/
bool.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
Copyright © Portalnesia <support@portalnesia.com>
*/
package nullable
import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.portalnesia.com/utils"
"reflect"
"gopkg.in/guregu/null.v4"
)
// Bool represents a bool that may be null or not
// present in json at all.
type Bool struct {
Present bool // Present is true if key is present in json
Valid bool // Valid is true if value is not null and valid bool
Data bool
}
func NewBool(data bool, presentValid ...bool) Bool {
d := Bool{Present: true, Valid: true, Data: data}
if len(presentValid) > 0 {
d.Present = presentValid[0]
d.Valid = false
if len(presentValid) > 1 {
d.Valid = presentValid[1]
}
}
return d
}
func NewBoolPtr(data bool, presentValid ...bool) *Bool {
d := NewBool(data, presentValid...)
return &d
}
func (d Bool) Null() null.Bool {
return null.NewBool(d.Data, d.Present && d.Valid)
}
func (d Bool) Ptr() *bool {
if d.Valid {
return &d.Data
}
return nil
}
// sql.Value interface
func (d *Bool) Scan(value interface{}) error {
d.Present = true
var i sql.NullBool
if err := i.Scan(value); err != nil {
return err
}
d.Valid = i.Valid
d.Data = i.Bool
return nil
}
// sql.Value interface
func (d Bool) Value() (driver.Value, error) {
if !d.Valid {
return nil, nil
}
return d.Data, nil
}
// MarshalJSON implements json.Marshaler interface.
func (i Bool) MarshalJSON() ([]byte, error) {
if !i.Present {
return []byte(`null`), nil
} else if !i.Valid {
return []byte("null"), nil
}
return json.Marshal(i.Data)
}
// UnmarshalJSON implements json.Marshaler interface.
func (b *Bool) UnmarshalJSON(data []byte) error {
b.Present = true
if bytes.Equal(data, []byte("null")) {
return nil
}
if err := json.Unmarshal(data, &b.Data); err != nil {
return nil
}
b.Valid = true
return nil
}
// MarshalBSON implements bson.Marshaler interface.
func (i Bool) MarshalBSON() ([]byte, error) {
if !i.Present {
return []byte(`null`), nil
} else if !i.Valid {
return []byte("null"), nil
}
_, byt, err := bson.MarshalValue(i.Data)
return byt, err
}
// UnmarshalBSON implements bson.Marshaler interface.
func (b *Bool) UnmarshalBSON(data []byte) error {
b.Present = true
if bytes.Equal(data, []byte("null")) {
return nil
}
if err := bson.Unmarshal(data, &b.Data); err != nil {
return nil
}
b.Valid = true
return nil
}
func (Bool) FiberConverter(value string) reflect.Value {
b := utils.IsTrue(value)
a := NewBool(b, true, true)
return reflect.ValueOf(a)
}