Skip to content

Commit 1de4876

Browse files
author
New year
committed
addtypes: adding type Any for go-tarantool
1 parent d70dadd commit 1de4876

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

any_gen.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
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+
}

msgpack.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,11 @@ func decodeByte(decoder *msgpack.Decoder) (byte, error) {
167167
func encodeByte(encoder *msgpack.Encoder, b byte) error {
168168
return encoder.EncodeUint8(b) //nolint:wrapcheck
169169
}
170+
171+
func encodeAny(encoder *msgpack.Encoder, val any) error {
172+
return encoder.Encode(val)
173+
}
174+
175+
func decodeAny(decoder *msgpack.Decoder) (any, error) {
176+
return decoder.DecodeInterfaceLoose()
177+
}

0 commit comments

Comments
 (0)