blob: 26ec49487522d25e6d96c20f986b04a4880fca7a (
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
36
37
38
39
40
41
42
43
44
45
46
47
48
|
// 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
}
func OptionalValue[T any](val T) Optional[T] {
return Optional[T]{
OK: true,
Val: val,
}
}
func OptionalNil[T any]() Optional[T] {
return Optional[T]{
OK: false,
}
}
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)
}
|