forked from tendermint/go-amino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteslice.go
117 lines (102 loc) · 2.27 KB
/
byteslice.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package wire
import (
"io"
"math"
cmn "github.com/tendermint/tmlibs/common"
)
func WriteByteSlice(bz []byte, w io.Writer, n *int, err *error) {
WriteVarint(len(bz), w, n, err)
WriteTo(bz, w, n, err)
}
func ReadByteSlice(r io.Reader, lmt int, n *int, err *error) []byte {
length := ReadVarint(r, n, err)
if *err != nil {
return nil
}
if length < 0 {
*err = ErrBinaryReadInvalidLength
return nil
}
// check that length is less than the maximum slice size
if length > math.MaxInt32 {
*err = ErrBinaryReadOverflow
return nil
}
if lmt != 0 && lmt < cmn.MaxInt(length, *n+length) {
*err = ErrBinaryReadOverflow
return nil
}
/* if length == 0 {
return nil // zero value for []byte
}*/
buf := make([]byte, length)
ReadFull(buf, r, n, err)
return buf
}
func PutByteSlice(buf []byte, bz []byte) (n int, err error) {
n_, err := PutVarint(buf, len(bz))
if err != nil {
return 0, err
}
buf = buf[n_:]
n += n_
if len(buf) < len(bz) {
return 0, ErrBinaryWriteOverflow
}
copy(buf, bz)
return n + len(bz), nil
}
func GetByteSlice(buf []byte) (bz []byte, n int, err error) {
length, n_, err := GetVarint(buf)
if err != nil {
return nil, 0, err
}
buf = buf[n_:]
n += n_
if length < 0 {
return nil, 0, ErrBinaryReadInvalidLength
}
if len(buf) < length {
return nil, 0, ErrBinaryReadOverflow
}
buf2 := make([]byte, length)
copy(buf2, buf)
return buf2, n + length, nil
}
// Returns the total encoded size of a byteslice
func ByteSliceSize(bz []byte) int {
return UvarintSize(uint64(len(bz))) + len(bz)
}
//-----------------------------------------------------------------------------
func WriteByteSlices(bzz [][]byte, w io.Writer, n *int, err *error) {
WriteVarint(len(bzz), w, n, err)
for _, bz := range bzz {
WriteByteSlice(bz, w, n, err)
if *err != nil {
return
}
}
}
func ReadByteSlices(r io.Reader, lmt int, n *int, err *error) [][]byte {
length := ReadVarint(r, n, err)
if *err != nil {
return nil
}
if length < 0 {
*err = ErrBinaryReadInvalidLength
return nil
}
if lmt != 0 && lmt < cmn.MaxInt(length, *n+length) {
*err = ErrBinaryReadOverflow
return nil
}
bzz := make([][]byte, length)
for i := 0; i < length; i++ {
bz := ReadByteSlice(r, lmt, n, err)
if *err != nil {
return nil
}
bzz[i] = bz
}
return bzz
}