@@ -2,8 +2,6 @@ package sandbox
22
33import (
44 "bytes"
5- "errors"
6- "fmt"
75 "reflect"
86
97 "github.com/golang/protobuf/proto"
1311 protoIface = reflect .TypeOf ((* proto .Message )(nil )).Elem ()
1412)
1513
16- // MarshalMessages marshal protobuf message slice
17- func MarshalMessages (msgs interface {}) ([]byte , error ) {
18- if msgs == nil {
19- return nil , nil
20- }
21- value := reflect .ValueOf (msgs )
22- tp := value .Type ()
23- if tp .Kind () != reflect .Slice {
24- return nil , errors .New ("bad slice type" )
25- }
26- if ! tp .Elem ().Implements (protoIface ) {
27- return nil , errors .New ("elem of slice must be protobuf message" )
28- }
29- if value .Len () == 0 {
30- return nil , nil
31- }
32-
33- var buf proto.Buffer
34- buf .EncodeVarint (uint64 (value .Len ()))
35- for i := 0 ; i < value .Len (); i ++ {
36- msg := value .Index (i ).Interface ().(proto.Message )
37- err := buf .EncodeMessage (msg )
38- if err != nil {
39- return nil , err
40- }
41- }
42- return buf .Bytes (), nil
43- }
44-
45- // UnmsarshalMessages unmarshal protobuf messages to slice, x must be a pointer to message slice
46- func UnmsarshalMessages (p []byte , x interface {}) error {
47- if p == nil {
48- return nil
49- }
50- tp := reflect .TypeOf (x )
51- // x must be a pointer to message slice
52- if tp .Kind () != reflect .Ptr {
53- return errors .New ("must be slice ptr" )
54- }
55- tp = tp .Elem ()
56- if tp .Kind () != reflect .Slice {
57- return errors .New ("must be slice ptr" )
58- }
59- // element of slice must be proto.Message
60- if ! tp .Elem ().Implements (protoIface ) {
61- return errors .New ("elem of slice must be protobuf message" )
62- }
63- // element of slice must be ptr type
64- if tp .Elem ().Kind () != reflect .Ptr {
65- return errors .New ("elem of slice must be ptr type" )
66- }
67- // if tp is []*pb.TxInput then elemtp is pb.TxInput
68- elemtp := tp .Elem ().Elem ()
69- value := reflect .ValueOf (x ).Elem ()
70-
71- buf := proto .NewBuffer (p )
72- total , err := buf .DecodeVarint ()
73- if err != nil {
74- return fmt .Errorf ("error while read message length:%s" , err )
75- }
76-
77- value .Set (reflect .MakeSlice (tp , int (total ), int (total )))
78- for i := 0 ; i < int (total ); i ++ {
79- v := reflect .New (elemtp )
80- m := v .Interface ().(proto.Message )
81- err = buf .DecodeMessage (m )
82- if err != nil {
83- return fmt .Errorf ("error while unmsarshal message:%s" , err )
84- }
85- value .Index (i ).Set (v )
86- }
87- return nil
88- }
89-
9014func isMsgEqual (reqHead , reqIncome proto.Message ) bool {
9115 encodeHead , err := encodeMsg (reqHead )
9216 if err != nil {
0 commit comments