-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathstring.go
101 lines (83 loc) · 1.83 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Code generated by 'go generate'
package optional
import (
"encoding/json"
"errors"
)
// String is an optional string.
type String struct {
value *string
}
// NewString creates an optional.String from a string.
func NewString(v string) String {
return String{&v}
}
// NewStringFromPtr creates an optional.String from a string pointer.
func NewStringFromPtr(v *string) String {
if v == nil {
return String{}
}
return NewString(*v)
}
// Set sets the string value.
func (s *String) Set(v string) {
s.value = &v
}
// ToPtr returns a *string of the value or nil if not present.
func (s String) ToPtr() *string {
if !s.Present() {
return nil
}
v := *s.value
return &v
}
// Get returns the string value or an error if not present.
func (s String) Get() (string, error) {
if !s.Present() {
var zero string
return zero, errors.New("value not present")
}
return *s.value, nil
}
// MustGet returns the string value or panics if not present.
func (s String) MustGet() string {
if !s.Present() {
panic("value not present")
}
return *s.value
}
// Present returns whether or not the value is present.
func (s String) Present() bool {
return s.value != nil
}
// OrElse returns the string value or a default value if the value is not present.
func (s String) OrElse(v string) string {
if s.Present() {
return *s.value
}
return v
}
// If calls the function f with the value if the value is present.
func (s String) If(fn func(string)) {
if s.Present() {
fn(*s.value)
}
}
func (s String) MarshalJSON() ([]byte, error) {
if s.Present() {
return json.Marshal(s.value)
}
return json.Marshal(nil)
}
func (s *String) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
s.value = nil
return nil
}
var value string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
s.value = &value
return nil
}