blob: c0e7b321336bd045ac91f4bfeb873793068cdf84 (
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
|
// Copyright (C) 2022 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 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)
}
|