summaryrefslogtreecommitdiff
path: root/lib/containers/optional.go
blob: 5bb7bb65964d19784cf98440451a53caca73d233 (plain)
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
// Copyright (C) 2022-2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

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 []byte("null"), nil
	}
	return json.Marshal(o.Val)
}

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)
}