-
Notifications
You must be signed in to change notification settings - Fork 40
/
bytes.go
72 lines (60 loc) · 1.51 KB
/
bytes.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
package codec
import (
"bytes"
"io"
"github.com/icon-project/goloop/common/log"
)
type bytesWrapper struct {
codecImpl
}
func (c bytesWrapper) Marshal(w io.Writer, v interface{}) error {
return c.NewEncoder(w).Encode(v)
}
func (c bytesWrapper) Unmarshal(r io.Reader, v interface{}) error {
return c.NewDecoder(r).Decode(v)
}
func (c bytesWrapper) MarshalToBytes(v interface{}) ([]byte, error) {
buf := bytes.NewBuffer(nil)
if err := c.NewEncoder(buf).Encode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (c bytesWrapper) UnmarshalFromBytes(b []byte, v interface{}) ([]byte, error) {
buf := bytes.NewBuffer(b)
if err := c.NewDecoder(buf).Decode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (c bytesWrapper) MustMarshalToBytes(v interface{}) []byte {
bs, err := c.MarshalToBytes(v)
if err != nil {
log.Panicf("MustMarshalToBytes() fails for object=%T err=%+v", v, err)
return nil
} else {
return bs
}
}
func (c bytesWrapper) MustUnmarshalFromBytes(b []byte, v interface{}) []byte {
bs, err := c.UnmarshalFromBytes(b, v)
if err != nil {
log.Panicf("MustUnmarshalFromBytes() fails for bytes=% x buffer=%T err=%+v", b, v, err)
return nil
} else {
return bs
}
}
type bytesWriter struct {
buf *[]byte
}
func (w bytesWriter) Write(bs []byte) (int, error) {
*w.buf = append(*w.buf, bs...)
return len(bs), nil
}
func (c bytesWrapper) NewEncoderBytes(b *[]byte) EncodeAndCloser {
if len(*b) > 0 {
*b = (*b)[:0]
}
return c.codecImpl.NewEncoder(&bytesWriter{b})
}