This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
wrapped_encoding.go
82 lines (64 loc) · 1.63 KB
/
wrapped_encoding.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
81
82
package encoding
import (
"io"
)
func NewWrappedValueEncoding(encoding ValueEncoding, byteEncodings ...ByteArrayEncoding) ValueEncoding {
return &chainValueEncoding{
encoding: encoding,
byteEncoding: NewChainByteArrayEncoding(byteEncodings...),
}
}
type chainValueEncoding struct {
encoding ValueEncoding
byteEncoding ByteArrayEncoding
}
func (e chainValueEncoding) Encode(data interface{}) ([]byte, error) {
enc, err := e.encoding.Encode(data)
if err != nil {
return nil, err
}
return e.byteEncoding.Encode(enc)
}
func (e chainValueEncoding) Decode(enc []byte, data interface{}) error {
dec, err := e.byteEncoding.Decode(enc)
if err != nil {
return err
}
return e.encoding.Decode(dec, data)
}
func NewWrappedStreamEncoding(encoding StreamEncoding, byteEncodings ...ByteStreamEncoding) StreamEncoding {
return &chainStreamEncoding{
encoding: encoding,
byteEncoding: NewChainByteStreamEncoding(byteEncodings...),
}
}
type chainStreamEncoding struct {
encoding StreamEncoding
byteEncoding ByteStreamEncoding
}
func (e chainStreamEncoding) StreamEncode(data interface{}, w io.Writer) error {
bw, err := e.byteEncoding.StreamEncode(w)
if err != nil {
return err
}
if err := e.encoding.StreamEncode(data, bw); err != nil {
return err
}
if err := bw.Close(); err != nil {
return err
}
return nil
}
func (e chainStreamEncoding) StreamDecode(r io.Reader, data interface{}) error {
br, err := e.byteEncoding.StreamDecode(r)
if err != nil {
return err
}
if err := e.encoding.StreamDecode(br, data); err != nil {
return err
}
if err := br.Close(); err != nil {
return err
}
return nil
}