@@ -12,6 +12,14 @@ import (
12
12
"go.opentelemetry.io/collector/confmap"
13
13
)
14
14
15
+ type flavor int
16
+
17
+ const (
18
+ noneFlavor flavor = 0
19
+ defaultFlavor flavor = 1
20
+ someFlavor flavor = 2
21
+ )
22
+
15
23
// Optional represents a value that may or may not be present.
16
24
// It supports two flavors for all types: Some(value) and None.
17
25
// It supports a third flavor for struct types: Default(defaultVal).
@@ -22,12 +30,9 @@ type Optional[T any] struct {
22
30
// value is the value of the Optional.
23
31
value T
24
32
25
- // hasValue indicates if the Optional has a value.
26
- hasValue bool
27
-
28
- // notNone is used to indicate that the Optional is not None.
29
- // This is used to differentiate between None and Default.
30
- notNone bool
33
+ // flavor indicates the flavor of the Optional.
34
+ // The zero value of flavor is noneFlavor.
35
+ flavor flavor
31
36
}
32
37
33
38
// deref a reflect.Type to its underlying type.
@@ -86,7 +91,7 @@ func Some[T any](value T) Optional[T] {
86
91
if err := assertNoEnabledField [T ](); err != nil {
87
92
panic (err )
88
93
}
89
- return Optional [T ]{value : value , hasValue : true , notNone : true }
94
+ return Optional [T ]{value : value , flavor : someFlavor }
90
95
}
91
96
92
97
// Default creates an Optional with a default value for unmarshaling.
@@ -99,7 +104,7 @@ func Default[T any](value T) Optional[T] {
99
104
if err != nil {
100
105
panic (err )
101
106
}
102
- return Optional [T ]{value : value , hasValue : false , notNone : true }
107
+ return Optional [T ]{value : value , flavor : defaultFlavor }
103
108
}
104
109
105
110
// None has no value. It has the same behavior as a nil pointer when unmarshaling.
@@ -117,7 +122,7 @@ func None[T any]() Optional[T] {
117
122
118
123
// HasValue checks if the Optional has a value.
119
124
func (o Optional [T ]) HasValue () bool {
120
- return o .hasValue
125
+ return o .flavor == someFlavor
121
126
}
122
127
123
128
// Get returns the value of the Optional.
@@ -146,7 +151,7 @@ func (o *Optional[T]) Unmarshal(conf *confmap.Conf) error {
146
151
return err
147
152
}
148
153
149
- if ! o . hasValue && ! o . notNone && conf .ToStringMap () == nil {
154
+ if o . flavor == noneFlavor && conf .ToStringMap () == nil {
150
155
// If the Optional is None and the configuration is nil, we do nothing.
151
156
// This replicates the behavior of unmarshaling into a field with a nil pointer.
152
157
return nil
@@ -156,6 +161,6 @@ func (o *Optional[T]) Unmarshal(conf *confmap.Conf) error {
156
161
return err
157
162
}
158
163
159
- o .hasValue = true
164
+ o .flavor = someFlavor
160
165
return nil
161
166
}
0 commit comments