-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcodec.go
80 lines (68 loc) · 1.35 KB
/
codec.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
80
package PaxiBFT
import (
"encoding/gob"
"encoding/json"
"io"
"github.com/salemmohammed/PaxiBFT/log"
)
// Codec interface provide methods for serialization and deserialization
// combines json and gob encoder decoder interface
type Codec interface {
Scheme() string
Encode(interface{})
Decode(interface{})
}
// NewCodec creates new codec object based on scheme, i.e. json and gob
func NewCodec(scheme string, rw io.ReadWriter) Codec {
switch scheme {
case "json":
return &codecJSON{
encoder: json.NewEncoder(rw),
decoder: json.NewDecoder(rw),
}
case "gob":
return &codecGOB{
encoder: gob.NewEncoder(rw),
decoder: gob.NewDecoder(rw),
}
}
return nil
}
type codecJSON struct {
encoder *json.Encoder
decoder *json.Decoder
}
func (j *codecJSON) Scheme() string {
return "json"
}
func (j *codecJSON) Encode(m interface{}) {
err := j.encoder.Encode(m)
if err != nil {
log.Error(err)
}
}
func (j *codecJSON) Decode(m interface{}) {
err := j.decoder.Decode(m)
if err != nil {
log.Error(err)
}
}
type codecGOB struct {
encoder *gob.Encoder
decoder *gob.Decoder
}
func (g *codecGOB) Scheme() string {
return "gob"
}
func (g *codecGOB) Encode(m interface{}) {
err := g.encoder.Encode(m)
if err != nil {
log.Error(err)
}
}
func (g *codecGOB) Decode(m interface{}) {
err := g.decoder.Decode(m)
if err != nil {
log.Error(err)
}
}