From 9955eacf96083e14d90897e5fbf5f68a8f97d307 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Sat, 23 Mar 2024 17:49:56 +0100 Subject: [PATCH] v0.0.419 JsonOpt --- dataext/optional.go | 67 +++++++++++++++++++++++++++++++++++++++++++++ goextVersion.go | 4 +-- 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 dataext/optional.go diff --git a/dataext/optional.go b/dataext/optional.go new file mode 100644 index 0000000..b4667f7 --- /dev/null +++ b/dataext/optional.go @@ -0,0 +1,67 @@ +package dataext + +import ( + "encoding/json" + "errors" +) + +type JsonTwoWayMarshal interface { + json.Marshaler + json.Unmarshaler +} + +type JsonOpt[T JsonTwoWayMarshal] struct { + isSet bool + value T +} + +// 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 + } + + if m.value == nil { + return []byte("null"), nil + } + + return m.MarshalJSON() +} + +// 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") + } + + return m.value.UnmarshalJSON(data) +} + +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 +} diff --git a/goextVersion.go b/goextVersion.go index 70d8e5f..5df8ad4 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.418" +const GoextVersion = "0.0.419" -const GoextVersionTimestamp = "2024-03-20T09:42:06+0100" +const GoextVersionTimestamp = "2024-03-23T17:49:56+0100"