|
| 1 | +package option |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/vmihailenco/msgpack/v5" |
| 5 | + "github.com/vmihailenco/msgpack/v5/msgpcode" |
| 6 | +) |
| 7 | + |
| 8 | +type Any struct { |
| 9 | + value any |
| 10 | + exists bool |
| 11 | +} |
| 12 | + |
| 13 | +func SomeAny(value any) Any { |
| 14 | + return Any{ |
| 15 | + value: value, |
| 16 | + exists: true, |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +func NoneAny() Any { |
| 21 | + return Any{ |
| 22 | + exists: false, |
| 23 | + value: zero[any](), |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func (o Any) IsSome() bool { |
| 28 | + return o.exists |
| 29 | +} |
| 30 | + |
| 31 | +func (o Any) IsZero() bool { |
| 32 | + return !o.exists |
| 33 | +} |
| 34 | + |
| 35 | +func (o Any) IsNil() bool { |
| 36 | + return o.IsZero() |
| 37 | +} |
| 38 | + |
| 39 | +func (o Any) Get() (any, bool) { |
| 40 | + return o.value, o.exists |
| 41 | +} |
| 42 | + |
| 43 | +func (o Any) MustGet() any { |
| 44 | + if !o.exists { |
| 45 | + panic("optional value is not set!") |
| 46 | + } |
| 47 | + return o.value |
| 48 | +} |
| 49 | + |
| 50 | +func (o Any) Unwrap() any { |
| 51 | + return o.value |
| 52 | +} |
| 53 | + |
| 54 | +func (o Any) UnwrapOr(defaultValue func() any) any { |
| 55 | + if o.exists { |
| 56 | + return o.value |
| 57 | + } |
| 58 | + |
| 59 | + return defaultValue() |
| 60 | +} |
| 61 | + |
| 62 | +func (o Any) EncodeMsgpack(encoder *msgpack.Encoder) error { |
| 63 | + if o.exists { |
| 64 | + return newEncodeError("Any", encodeAny(encoder, o.value)) |
| 65 | + } |
| 66 | + |
| 67 | + return newEncodeError("Any", encoder.EncodeNil()) |
| 68 | +} |
| 69 | + |
| 70 | +func (o *Any) DecodeMsgpack(decoder *msgpack.Decoder) error { |
| 71 | + code, err := decoder.PeekCode() |
| 72 | + if err != nil { |
| 73 | + return newDecodeError("Any", err) |
| 74 | + } |
| 75 | + |
| 76 | + switch { |
| 77 | + case code == msgpcode.Nil: |
| 78 | + o.exists = false |
| 79 | + |
| 80 | + return newDecodeError("Any", decoder.Skip()) |
| 81 | + case checkBool(code): |
| 82 | + o.value, err = decodeAny(decoder) |
| 83 | + if err != nil { |
| 84 | + return newDecodeError("Any", err) |
| 85 | + } |
| 86 | + o.exists = true |
| 87 | + |
| 88 | + return err |
| 89 | + default: |
| 90 | + return newDecodeWithCodeError("Any", code) |
| 91 | + } |
| 92 | +} |
0 commit comments