Debian Codegraph @

opt/optional/opt.go

raw
1 // +build none
2
3 package optional
4
5 import (
6 "fmt"
7
8 "github.com/mailru/easyjson/jlexer"
9 "github.com/mailru/easyjson/jwriter"
10 )
11
12 // template type Optional(A)
13 type A int
14
15 // A 'gotemplate'-based type for providing optional semantics without using pointers.
16 type Optional struct {
17 V A
18 Defined bool
19 }
20
21 // Creates an optional type with a given value.
22 func OOptional(v A) Optional {
23 return Optional{V: v, Defined: true}
24 }
25
26 // Get returns the value or given default in the case the value is undefined.
27 func (v Optional) Get(deflt A) A {
28 if !v.Defined {
29 return deflt
30 }
31 return v.V
32 }
33
34 // MarshalEasyJSON does JSON marshaling using easyjson interface.
35 func (v Optional) MarshalEasyJSON(w *jwriter.Writer) {
36 if v.Defined {
37 w.Optional(v.V)
38 } else {
39 w.RawString("null")
40 }
41 }
42
43 // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface.
44 func (v *Optional) UnmarshalEasyJSON(l *jlexer.Lexer) {
45 if l.IsNull() {
46 l.Skip()
47 *v = Optional{}
48 } else {
49 v.V = l.Optional()
50 v.Defined = true
51 }
52 }
53
54 // MarshalJSON implements a standard json marshaler interface.
55 func (v Optional) MarshalJSON() ([]byte, error) {
56 w := jwriter.Writer{}
57 v.MarshalEasyJSON(&w)
58 return w.Buffer.BuildBytes(), w.Error
59 }
60
61 // UnmarshalJSON implements a standard json unmarshaler interface.
62 func (v *Optional) UnmarshalJSON(data []byte) error {
63 l := jlexer.Lexer{Data: data}
64 v.UnmarshalEasyJSON(&l)
65 return l.Error()
66 }
67
68 // IsDefined returns whether the value is defined, a function is required so that it can
69 // be used in an interface.
70 func (v Optional) IsDefined() bool {
71 return v.Defined
72 }
73
74 // String implements a stringer interface using fmt.Sprint for the value.
75 func (v Optional) String() string {
76 if !v.Defined {
77 return "<undefined>"
78 }
79 return fmt.Sprint(v.V)
80 }