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 package issue620
30
31 import (
32 "bytes"
33 "testing"
34
35 "github.com/gogo/protobuf/proto"
36 )
37
38 func TestEncodeShort(t *testing.T) {
39 exp := []byte{8, 10, 6, 66, 97, 114, 49, 50, 51}
40 s := "Bar123"
41 b1 := &Bar{Field1: &s}
42 bufProto := proto.NewBuffer(nil)
43
44 b2 := &BarFast{Field1: &s}
45 bufProtoFast := proto.NewBuffer(nil)
46
47 encodeMessageCheck(t, b1, b2, bufProto, bufProtoFast, exp)
48 }
49
50 func TestEncodeLong(t *testing.T) {
51 exp := []byte{8, 10, 6, 66, 97, 114, 49, 50, 51}
52 s := "Bar123"
53 b1 := &Bar{Field1: &s}
54 bufProto := proto.NewBuffer(make([]byte, 0, 480))
55 b2 := &BarFast{Field1: &s}
56 bufProtoFast := proto.NewBuffer(make([]byte, 0, 480))
57
58 encodeMessageCheck(t, b1, b2, bufProto, bufProtoFast, exp)
59 }
60
61 func TestEncodeDecode(t *testing.T) {
62 s := "Bar123"
63 bar := &BarFast{Field1: &s}
64 bufProtoFast := proto.NewBuffer(make([]byte, 0, 480))
65 err := bufProtoFast.EncodeMessage(bar)
66 errCheck(t, err)
67 dec := &BarFast{}
68 err = bufProtoFast.DecodeMessage(dec)
69 errCheck(t, err)
70 if !dec.Equal(bar) {
71 t.Errorf("Expect %+v got %+v after encode/decode", bar, dec)
72 }
73 }
74
75 func encodeMessageCheck(t *testing.T, b1, b2 proto.Message, bufProto, bufProtoFast *proto.Buffer, exp []byte) {
76 err := bufProto.EncodeMessage(b1)
77 errCheck(t, err)
78 err = bufProtoFast.EncodeMessage(b2)
79 errCheck(t, err)
80 checkEqual(t, exp, bufProto.Bytes())
81 checkEqual(t, exp, bufProtoFast.Bytes())
82
83 bufProto.Reset()
84 bufProtoFast.Reset()
85 expMore := make([]byte, 0, len(exp))
86 copy(expMore, exp)
87 for i := 0; i < 10; i++ {
88 err = bufProto.EncodeMessage(b1)
89 errCheck(t, err)
90 err = bufProtoFast.EncodeMessage(b2)
91 errCheck(t, err)
92 expMore = append(expMore, exp...)
93 checkEqual(t, expMore, bufProto.Bytes())
94 checkEqual(t, expMore, bufProtoFast.Bytes())
95 }
96
97 bufProto.Reset()
98 bufProtoFast.Reset()
99 err = bufProto.EncodeMessage(b1)
100 errCheck(t, err)
101 err = bufProtoFast.EncodeMessage(b2)
102 errCheck(t, err)
103 checkEqual(t, exp, bufProto.Bytes())
104 checkEqual(t, exp, bufProtoFast.Bytes())
105 }
106
107 func errCheck(t *testing.T, err error) {
108 t.Helper()
109 if err != nil {
110 t.Error(err.Error())
111 }
112 }
113
114 func checkEqual(t *testing.T, b1, b2 []byte) {
115 t.Helper()
116 if !bytes.Equal(b1, b2) {
117 t.Errorf("%v != %v\n", b1, b2)
118 }
119 }
120
View as plain text