-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
73 lines (62 loc) · 1.69 KB
/
Copy pathstring.go
File metadata and controls
73 lines (62 loc) · 1.69 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
package opt
import (
"encoding/json"
"fmt"
)
// String is a nullable string with optimized JSON and Text marshaling.
type String struct {
Option[string]
}
// NewString creates a String with the given value and validity.
func NewString(s string, valid bool) String {
return String{New(s, valid)}
}
// StringFrom creates a String that is always valid.
func StringFrom(s string) String {
return String{From(s)}
}
// StringFromPtr creates a String from a pointer. Nil results in null.
func StringFromPtr(s *string) String {
return String{FromPtr(s)}
}
// StringOrNull creates a valid String if s is non-empty, null otherwise.
// Use StringFrom(s) when empty string is a meaningful value.
func StringOrNull(s string) String {
return NewString(s, s != "")
}
// Equal reports whether two Strings are equal (both null, or same value).
func (s String) Equal(other String) bool {
return Equal(s.Option, other.Option)
}
// MarshalJSON implements json.Marshaler.
func (s String) MarshalJSON() ([]byte, error) {
if !s.Valid {
return jsonNull, nil
}
return json.Marshal(s.V)
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *String) UnmarshalJSON(data []byte) error {
if len(data) > 0 && data[0] == 'n' {
s.Valid = false
return nil
}
if err := json.Unmarshal(data, &s.V); err != nil {
return fmt.Errorf("opt: couldn't unmarshal JSON: %w", err)
}
s.Valid = true
return nil
}
// MarshalText implements encoding.TextMarshaler.
func (s String) MarshalText() ([]byte, error) {
if !s.Valid {
return []byte{}, nil
}
return []byte(s.V), nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *String) UnmarshalText(text []byte) error {
s.V = string(text)
s.Valid = s.V != ""
return nil
}