-
Notifications
You must be signed in to change notification settings - Fork 4
/
binary.go
58 lines (51 loc) · 1.11 KB
/
binary.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
package protokit
import (
"io"
"github.com/insolar/assured-ledger/ledger-core/vanilla/throw"
)
func BinaryProtoSize(n int) int {
if n > 0 {
return n + 1
}
return n
}
func BinaryMarshalTo(b []byte, allowEmpty bool, marshalTo func([]byte) (int, error)) (int, error) {
if len(b) == 0 {
return marshalTo(nil)
}
b[0] = BinaryMarker
switch n, err := marshalTo(b[1:]); {
case err != nil:
return 0, err
case !allowEmpty && n == 0:
return 0, nil
default:
return n + 1, nil
}
}
func BinaryMarshalToSizedBuffer(b []byte, allowEmpty bool, marshalToSizedBuffer func([]byte) (int, error)) (int, error) {
switch n, err := marshalToSizedBuffer(b[1:]); {
case err != nil:
return 0, err
case !allowEmpty && n == 0:
return 0, nil
default:
n++
i := len(b) - n
if i < 0 {
return 0, io.ErrShortBuffer
}
b[i] = BinaryMarker
return n, nil
}
}
func BinaryUnmarshal(b []byte, unmarshal func([]byte) error) error {
if len(b) == 0 {
return unmarshal(nil)
}
if b[0] != BinaryMarker {
return throw.FailHere("expected binary marker")
}
return unmarshal(b[1:])
}
const ExplicitEmptyBinaryProtoSize = 1