-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
82 lines (66 loc) · 1.13 KB
/
string.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
package nil
import (
"bytes"
"encoding/json"
)
// String holds data of nullable string.
type String struct {
valid bool
value string
}
// Nil
func (s String) Nil() bool {
return !s.valid
}
// Value
func (s String) Value() string {
return s.value
}
// String
func (s String) String() string {
if !s.valid {
return "nil"
}
return s.value
}
// MarshalJSON
func (s String) MarshalJSON() ([]byte, error) {
if !s.valid {
return []byte("null"), nil
}
return json.Marshal(s.value)
}
// UnmarshalJSON
func (s *String) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
*s = String{}
return nil
}
var res string
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
*s = String{value: res, valid: true}
return nil
}
// NewNilString creates new nil string value.
func NewNilString() String {
return String{
valid: false,
value: "",
}
}
// NewString creates new nil string value.
func NewString(value string) String {
return String{
valid: true,
value: value,
}
}
func FromStringPtr(value *string) String {
if value == nil {
return NewNilString()
}
return NewString(*value)
}