-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.go
103 lines (85 loc) · 1.85 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
package extratypes
import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"strconv"
)
// Bool contain a boolean data that can be null, and also string
// on JSON and SQL, but value will be converted into bool type
type Bool struct {
sql.NullBool
Val bool `json:"val" toml:"val"`
Nil bool `json:"nil" toml:"nil"`
}
// Scan implements the Scanner interface.
func (b *Bool) Scan(value interface{}) error {
if value == nil {
b.Val = false
b.Nil = true
return nil
}
b.Nil = false
b.Val = asBool(value)
return nil
}
func (b Bool) String() string {
if b.Nil {
return "nil"
}
return strconv.FormatBool(b.Val)
}
// Value implements the driver Valuer interface.
func (b Bool) Value() (driver.Value, error) {
if b.Nil {
return nil, nil
}
return b.Val, nil
}
// MarshalJSON implement the Marshaler interface
func (b Bool) MarshalJSON() ([]byte, error) {
if b.Nil {
return json.Marshal(nil)
}
return json.Marshal(b.Val)
}
// UnmarshalJSON implement the un-Marshaler interface
func (b *Bool) UnmarshalJSON(buf []byte) error {
var v interface{}
err := json.Unmarshal(buf, &v)
if err != nil {
return err
}
if v == nil {
b.Nil = true
b.Val = false
return nil
}
b.Val = asBool(v)
return nil
}
// MarshalText implement Text Marshaller interface
func (b Bool) MarshalText() ([]byte, error) {
if b.Nil {
return []byte(""), nil
}
return asByteSlice(b.String()), nil
}
// UnmarshalText implement the text un-Marshaller interface
func (b *Bool) UnmarshalText(buf []byte) error {
if buf == nil || bytes.Compare(buf, []byte("")) == 0 ||
bytes.Compare(buf, []byte("null")) == 0 ||
bytes.Compare(buf, []byte("nil")) == 0 {
b.Nil = true
return nil
}
result, err := toType(buf, &b.Val)
if err != nil {
return err
}
fmt.Printf("buf: %s | result: %t | b.Val: %t\n", buf, result, b.Val)
b.Nil = result
return nil
}