From 13b65d51ffc9768464e8330fdb73b6febd7410af Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Sat, 30 Jul 2022 02:36:25 -0600 Subject: json: Implement a bunch of streaming JSON encoding/decoding --- lib/containers/optional.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'lib/containers') diff --git a/lib/containers/optional.go b/lib/containers/optional.go index 3055308..c0e7b32 100644 --- a/lib/containers/optional.go +++ b/lib/containers/optional.go @@ -4,7 +4,33 @@ package containers +import ( + "encoding/json" +) + type Optional[T any] struct { OK bool Val T } + +var ( + _ json.Marshaler = Optional[bool]{} + _ json.Unmarshaler = (*Optional[bool])(nil) +) + +func (o Optional[T]) MarshalJSON() ([]byte, error) { + if o.OK { + return json.Marshal(o.Val) + } else { + return []byte("null"), nil + } +} + +func (o *Optional[T]) UnmarshalJSON(dat []byte) error { + if string(dat) == "null" { + *o = Optional[T]{} + return nil + } + o.OK = true + return json.Unmarshal(dat, &o.Val) +} -- cgit v1.2.3-54-g00ecf