2020-12-26 13:49:20 +00:00
|
|
|
package opt
|
|
|
|
|
2020-12-31 12:44:17 +00:00
|
|
|
import "fmt"
|
|
|
|
|
2020-12-26 13:49:20 +00:00
|
|
|
// String holds an optional string value.
|
|
|
|
type String struct {
|
|
|
|
value *string
|
|
|
|
}
|
|
|
|
|
2020-12-28 13:25:35 +00:00
|
|
|
// NullString represents an empty optional String.
|
2020-12-28 12:15:07 +00:00
|
|
|
var NullString = String{nil}
|
|
|
|
|
2020-12-26 13:49:20 +00:00
|
|
|
// NewString creates a new optional String with the given value.
|
|
|
|
func NewString(value string) String {
|
|
|
|
return String{&value}
|
|
|
|
}
|
|
|
|
|
2020-12-28 13:25:35 +00:00
|
|
|
// NewNotEmptyString creates a new optional String with the given value or
|
|
|
|
// returns NullString if the value is an empty string.
|
|
|
|
func NewNotEmptyString(value string) String {
|
|
|
|
if value == "" {
|
|
|
|
return NullString
|
|
|
|
} else {
|
|
|
|
return NewString(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-26 13:49:20 +00:00
|
|
|
// IsNull returns whether the optional String has no value.
|
|
|
|
func (s String) IsNull() bool {
|
|
|
|
return s.value == nil
|
|
|
|
}
|
|
|
|
|
2020-12-31 12:44:17 +00:00
|
|
|
// Or returns the receiver if it is not null, otherwise the given optional
|
|
|
|
// String.
|
|
|
|
func (s String) Or(other String) String {
|
|
|
|
if s.IsNull() {
|
|
|
|
return other
|
|
|
|
} else {
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// OrDefault returns the optional String value or the given default string if
|
|
|
|
// it is null.
|
2020-12-26 13:49:20 +00:00
|
|
|
func (s String) OrDefault(def string) string {
|
2020-12-31 12:44:17 +00:00
|
|
|
if s.IsNull() {
|
2020-12-26 13:49:20 +00:00
|
|
|
return def
|
|
|
|
} else {
|
|
|
|
return *s.value
|
|
|
|
}
|
|
|
|
}
|
2020-12-28 13:25:35 +00:00
|
|
|
|
|
|
|
// Unwrap returns the optional String value or an empty String if none is set.
|
|
|
|
func (s String) Unwrap() string {
|
|
|
|
return s.OrDefault("")
|
|
|
|
}
|
2020-12-28 15:00:48 +00:00
|
|
|
|
2020-12-31 12:44:17 +00:00
|
|
|
func (s String) Equal(other String) bool {
|
2021-01-16 13:13:57 +00:00
|
|
|
return s.value == other.value ||
|
|
|
|
(s.value != nil && other.value != nil && *s.value == *other.value)
|
2020-12-31 12:44:17 +00:00
|
|
|
}
|
|
|
|
|
2020-12-28 15:00:48 +00:00
|
|
|
func (s String) String() string {
|
|
|
|
return s.OrDefault("")
|
|
|
|
}
|
2020-12-31 12:44:17 +00:00
|
|
|
|
|
|
|
func (s String) MarshalJSON() ([]byte, error) {
|
|
|
|
return []byte(fmt.Sprintf(`"%v"`, s)), nil
|
|
|
|
}
|