OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / go-wire / doc.go
1 /*
2 go-wire is our custom codec package for serializing and deserializing
3 data and structures as binary and JSON blobs.
4
5 In order to get started with go-wire we need to:
6
7 1) Choose the receiving structure for deserializing.
8 It MUST be an interface{} and during registration it MUST be
9 wrapped as a struct for example
10
11     struct { Receiver }{}
12
13 2) Decide the IDs for the respective types that we'll be dealing with.
14 We shall call these the concrete types.
15
16 3) Register the receiving structure as well as each of the concrete types.
17 Typically do this in the init function so that it gets run before other functions are invoked
18     
19
20   func init() {
21     wire.RegisterInterface(
22         struct { Receiver }{},
23         wire.ConcreteType{&bcMessage{}, 0x01},
24         wire.ConcreteType{&bcResponse{}, 0x02},
25         wire.ConcreteType{&bcStatus{}, 0x03},
26     )
27   }
28
29   type bcMessage struct {
30     Content string
31     Height int
32   }
33
34   type bcResponse struct {
35     Status int
36     Message string 
37   }
38
39   type bcResponse struct {
40     Status int
41     Message string 
42   }
43
44
45 Encoding to binary is performed by invoking wire.WriteBinary. You'll need to provide
46 the data to be encoded/serialized as well as where to store it and storage for
47 the number of bytes written as well as any error encountered
48
49   var n int
50   var err error
51   buf := new(bytes.Buffer)
52   bm := &bcMessage{Message: "Tendermint", Height: 100}
53   wire.WriteBinary(bm, buf, &n, &err)
54
55 Decoding from binary is performed by invoking wire.ReadBinary. The data being decoded
56 has to be retrieved from the decoding receiver that we previously defined i.e. Receiver
57 for example
58
59   recv := wire.ReadBinary(struct{ Receiver }{}, buf, 0, &n, &err).(struct{ Receiver }).Receiver
60   decoded := recv.(*bcMessage)
61   fmt.Printf("Decoded: %#v\n", decoded)
62
63 Note that in the decoding example we used
64
65   struct { Receiver }{} --> .(struct{ Receiver }).Receiver
66
67 to receive the value. That correlates with the type that we registered in wire.RegisterInterface
68 */
69 package wire