goext/dataext/optional.go

76 lines
1.2 KiB
Go
Raw Normal View History

2024-03-23 17:49:56 +01:00
package dataext
import (
"encoding/json"
"errors"
)
2024-03-23 20:28:51 +01:00
type JsonOpt[T any] struct {
2024-03-23 17:49:56 +01:00
isSet bool
value T
}
2024-11-07 13:13:12 +01:00
func NewJsonOpt[T any](v T) JsonOpt[T] {
return JsonOpt[T]{isSet: true, value: v}
}
func EmptyJsonOpt[T any]() JsonOpt[T] {
return JsonOpt[T]{isSet: false}
}
2024-03-23 17:49:56 +01:00
// MarshalJSON returns m as the JSON encoding of m.
func (m JsonOpt[T]) MarshalJSON() ([]byte, error) {
if !m.isSet {
return []byte("null"), nil // actually this would be undefined - but undefined is not valid JSON
}
2024-03-23 18:01:41 +01:00
return json.Marshal(m.value)
2024-03-23 17:49:56 +01:00
}
// UnmarshalJSON sets *m to a copy of data.
func (m *JsonOpt[T]) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("JsonOpt: UnmarshalJSON on nil pointer")
}
2024-04-01 16:03:00 +02:00
m.isSet = true
2024-03-23 18:01:41 +01:00
return json.Unmarshal(data, &m.value)
2024-03-23 17:49:56 +01:00
}
func (m JsonOpt[T]) IsSet() bool {
return m.isSet
}
func (m JsonOpt[T]) IsUnset() bool {
return !m.isSet
}
func (m JsonOpt[T]) Value() (T, bool) {
if !m.isSet {
return *new(T), false
}
return m.value, true
}
func (m JsonOpt[T]) ValueOrNil() *T {
if !m.isSet {
return nil
}
return &m.value
}
func (m JsonOpt[T]) MustValue() T {
if !m.isSet {
panic("value not set")
}
return m.value
}
2024-09-25 21:43:41 +02:00
func (m JsonOpt[T]) IfSet(fn func(v T)) bool {
if !m.isSet {
return false
}
fn(m.value)
return true
}