forked from FactomProject/FactomCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.go
More file actions
104 lines (80 loc) · 1.95 KB
/
binary.go
File metadata and controls
104 lines (80 loc) · 1.95 KB
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
package notaryapi
import (
"encoding"
"errors"
"bytes"
"encoding/binary"
//"encoding/hex"
"math/big"
)
type BinaryMarshallable interface {
encoding.BinaryMarshaler
encoding.BinaryUnmarshaler
MarshalledSize() uint64
}
func bigIntMarshalBinary(i *big.Int) (data []byte, err error) {
intd, err := i.GobEncode()
if err != nil { return }
size := len(intd)
if size > 255 { return nil, errors.New("Big int is too big") }
data = make([]byte, size+1)
data[0] = byte(size)
copy(data[1:], intd)
return
}
func bigIntMarshalledSize(i *big.Int) uint64 {
intd, err := i.GobEncode()
if err != nil { return 0 }
return uint64(1 + len(intd))
}
func bigIntUnmarshalBinary(data []byte) (retd []byte, i *big.Int, err error) {
size, data := uint8(data[0]), data[1:]
i = new(big.Int)
err, retd = i.GobDecode(data[:size]), data[size:]
return
}
type SimpleData struct {
Data []byte
}
func (d *SimpleData) MarshalBinary() ([]byte, error) {
return d.Data, nil
}
func (d *SimpleData) MarshalledSize() uint64 {
return uint64(len(d.Data))
}
func (d *SimpleData) UnmarshalBinary([]byte) error {
return errors.New("SimpleData cannot be unmarshalled")
}
type ByteArray []byte
func (ba ByteArray) Bytes() []byte {
newArray := make([]byte, len(ba))
copy(newArray, ba[:])
return newArray
}
func (ba ByteArray) SetBytes(newArray []byte) error {
copy(ba[:], newArray[:])
return nil
}
func (ba ByteArray) MarshalBinary() ([]byte, error) {
var buf bytes.Buffer
binary.Write(&buf, binary.BigEndian, uint64(len(ba)))
buf.Write(ba)
return buf.Bytes(), nil
}
func (ba ByteArray) MarshalledSize() uint64 {
return uint64(len(ba) + 1)
}
func (ba ByteArray) UnmarshalBinary([]byte) error {
count, data := binary.BigEndian.Uint64(ba[0:8]), ba[8:]
//SetBytes(data[:count])
copy(ba[:], data[:count])
return nil
}
func NewByteArray(newHash []byte) (*ByteArray, error) {
var sh ByteArray
err := sh.SetBytes(newHash)
if err != nil {
return nil, err
}
return &sh, err
}