Skip to content

Commit 1296417

Browse files
committed
encoding: Add Gob encoding.
Signed-off-by: Simarpreet Singh <simar@linux.com>
1 parent 00290f0 commit 1296417

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

encoding/codec.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@ type Codec interface {
77

88
var (
99
JSON = JSONCodec{}
10+
Gob = GobCodec{}
1011
)

encoding/gob.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package encoding
2+
3+
import (
4+
"bytes"
5+
"encoding/gob"
6+
)
7+
8+
type GobCodec struct{}
9+
10+
func (c GobCodec) Marshal(v interface{}) ([]byte, error) {
11+
var b bytes.Buffer
12+
encoder := gob.NewEncoder(&b)
13+
if err := encoder.Encode(v); err != nil {
14+
return nil, err
15+
}
16+
return b.Bytes(), nil
17+
}
18+
19+
func (c GobCodec) Unmarshal(data []byte, v interface{}) error {
20+
r := bytes.NewReader(data)
21+
decoder := gob.NewDecoder(r)
22+
return decoder.Decode(v)
23+
}

encoding/gob_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package encoding
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
var tsBytes = []byte{0x30, 0xff, 0x81, 0x3, 0x1, 0x1, 0xa, 0x74, 0x65, 0x73, 0x74,
10+
0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x1, 0xff, 0x82, 0x0, 0x1, 0x3, 0x1, 0x3,
11+
0x46, 0x6f, 0x6f, 0x1, 0xc, 0x0, 0x1, 0x3, 0x42, 0x61, 0x72, 0x1, 0x8, 0x0,
12+
0x1, 0x3, 0x42, 0x61, 0x7a, 0x1, 0x4, 0x0, 0x0, 0x0, 0x15, 0xff, 0x82, 0x1,
13+
0x9, 0x66, 0x6f, 0x6f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x1, 0xfe, 0x45,
14+
0x40, 0x1, 0xff, 0xf6, 0x0}
15+
16+
var ts = testStruct{
17+
Foo: "foostring",
18+
Bar: 42.0,
19+
Baz: 123,
20+
}
21+
22+
func TestGobCodec_Marshal(t *testing.T) {
23+
gc := GobCodec{}
24+
data, err := gc.Marshal(testStruct{
25+
Foo: "foostring",
26+
Bar: 42.0,
27+
Baz: 123,
28+
})
29+
assert.NoError(t, err)
30+
assert.Equal(t, tsBytes, data)
31+
}
32+
33+
func TestGobCodec_Unmarshal(t *testing.T) {
34+
gc := GobCodec{}
35+
var data testStruct
36+
assert.NoError(t, gc.Unmarshal(tsBytes, &data))
37+
assert.Equal(t, ts, data)
38+
}

0 commit comments

Comments
 (0)