-
Notifications
You must be signed in to change notification settings - Fork 4
/
example_value_test.go
79 lines (71 loc) · 1.38 KB
/
example_value_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ubjson_test
import (
"fmt"
"github.com/jmank88/ubjson"
)
// A CustomValue encodes itself as a fixed length object container.
type CustomValue struct {
Field1 string
FieldA int
}
func (c *CustomValue) UBJSONType() ubjson.Marker {
return ubjson.ObjectStartMarker
}
func (c *CustomValue) MarshalUBJSON(e *ubjson.Encoder) error {
o, err := e.ObjectLen(2)
if err != nil {
return err
}
if err := o.EncodeKey("Field1"); err != nil {
return err
}
if err := o.EncodeString(c.Field1); err != nil {
return err
}
if err := o.EncodeKey("FieldA"); err != nil {
return err
}
if err := o.EncodeInt(c.FieldA); err != nil {
return err
}
return o.End()
}
func (c *CustomValue) UnmarshalUBJSON(d *ubjson.Decoder) error {
o, err := d.Object()
if err != nil {
return err
}
for o.NextEntry() {
k, err := o.DecodeKey()
if err != nil {
return err
}
switch k {
case "Field1":
s, err := o.DecodeString()
if err != nil {
return err
}
c.Field1 = s
case "FieldA":
i, err := o.DecodeInt()
if err != nil {
return err
}
c.FieldA = i
}
}
return o.End()
}
func Example_customValue() {
v := &CustomValue{Field1: "test", FieldA: 42}
if b, err := ubjson.MarshalBlock(v); err != nil {
fmt.Println("error: " + err.Error())
} else {
fmt.Println(string(b))
}
// Output:
// [{][#][U][2]
// [U][6][Field1][S][U][4][test]
// [U][6][FieldA][U][42]
}