Repository navigation
Expand file tree
/
Copy pathbool.go
More file actions
101 lines (90 loc) · 1.98 KB
/
Copy pathbool.go
File metadata and controls
101 lines (90 loc) · 1.98 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
package opt
import (
"errors"
"fmt"
)
// Bool is a nullable bool with optimized JSON and Text marshaling.
type Bool struct {
Option[bool]
}
// NewBool creates a Bool with the given value and validity.
func NewBool(b, valid bool) Bool {
return Bool{New(b, valid)}
}
// BoolFrom creates a Bool that is always valid.
func BoolFrom(b bool) Bool {
return Bool{From(b)}
}
// BoolFromPtr creates a Bool from a pointer. Nil results in null.
func BoolFromPtr(b *bool) Bool {
return Bool{FromPtr(b)}
}
// BoolOrNull creates a valid Bool if b is true, null if false.
// Use BoolFrom(false) when false is an explicit value, not absence.
func BoolOrNull(b bool) Bool {
return NewBool(b, b)
}
// Equal reports whether two Bools are equal.
func (b Bool) Equal(other Bool) bool {
return Equal(b.Option, other.Option)
}
// MarshalJSON implements json.Marshaler.
func (b Bool) MarshalJSON() ([]byte, error) {
if !b.Valid {
return jsonNull, nil
}
if b.V {
return []byte("true"), nil
}
return []byte("false"), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (b *Bool) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return errors.New("opt: empty JSON input")
}
switch data[0] {
case 'n':
b.Valid = false
return nil
case 't':
b.V = true
b.Valid = true
return nil
case 'f':
b.V = false
b.Valid = true
return nil
default:
return fmt.Errorf("opt: cannot unmarshal %s into Bool", string(data))
}
}
// MarshalText implements encoding.TextMarshaler.
func (b Bool) MarshalText() ([]byte, error) {
if !b.Valid {
return []byte{}, nil
}
if b.V {
return []byte("true"), nil
}
return []byte("false"), nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (b *Bool) UnmarshalText(text []byte) error {
str := string(text)
switch str {
case "", strNull:
b.Valid = false
return nil
case strTrue:
b.V = true
b.Valid = true
return nil
case strFalse:
b.V = false
b.Valid = true
return nil
default:
return fmt.Errorf("opt: invalid Bool text: %q", str)
}
}