1 package cm
2 3 // Option represents a Component Model [option<T>] type.
4 //
5 // [option<T>]: https://component-model.bytecodealliance.org/design/wit.html#options
6 type Option[T any] struct {
7 _ HostLayout
8 option[T]
9 }
10 11 // None returns an [Option] representing the none case,
12 // equivalent to the zero value.
13 func None[T any]() Option[T] {
14 return Option[T]{}
15 }
16 17 // Some returns an [Option] representing the some case.
18 func Some[T any](v T) Option[T] {
19 return Option[T]{
20 option: option[T]{
21 isSome: true,
22 some: v,
23 },
24 }
25 }
26 27 // option represents the internal representation of a Component Model option type.
28 // The first byte is a bool representing none or some,
29 // followed by storage for the associated type T.
30 type option[T any] struct {
31 _ HostLayout
32 isSome bool
33 some T
34 }
35 36 // None returns true if o represents the none case.
37 func (o *option[T]) None() bool {
38 return !o.isSome
39 }
40 41 // Some returns a non-nil *T if o represents the some case,
42 // or nil if o represents the none case.
43 func (o *option[T]) Some() *T {
44 if o.isSome {
45 return &o.some
46 }
47 return nil
48 }
49 50 // Value returns T if o represents the some case,
51 // or the zero value of T if o represents the none case.
52 // This does not have a pointer receiver, so it can be chained.
53 func (o option[T]) Value() T {
54 if !o.isSome {
55 var zero T
56 return zero
57 }
58 return o.some
59 }
60