This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.go
91 lines (79 loc) · 2.06 KB
/
util.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
package wire
import (
"bytes"
"crypto/sha256"
"encoding/json"
"golang.org/x/crypto/ripemd160"
cmn "github.com/tendermint/tmlibs/common"
)
func BinaryBytes(o interface{}) []byte {
w, n, err := new(bytes.Buffer), new(int), new(error)
WriteBinary(o, w, n, err)
if *err != nil {
cmn.PanicSanity(*err)
}
return w.Bytes()
}
// ptr: a pointer to the object to be filled
func ReadBinaryBytes(d []byte, ptr interface{}) error {
r, n, err := bytes.NewBuffer(d), new(int), new(error)
ReadBinaryPtr(ptr, r, len(d), n, err)
return *err
}
func JSONBytes(o interface{}) []byte {
w, n, err := new(bytes.Buffer), new(int), new(error)
WriteJSON(o, w, n, err)
if *err != nil {
cmn.PanicSanity(*err)
}
return w.Bytes()
}
// NOTE: inefficient
func JSONBytesPretty(o interface{}) []byte {
jsonBytes := JSONBytes(o)
var object interface{}
err := json.Unmarshal(jsonBytes, &object)
if err != nil {
cmn.PanicSanity(err)
}
jsonBytes, err = json.MarshalIndent(object, "", "\t")
if err != nil {
cmn.PanicSanity(err)
}
return jsonBytes
}
// ptr: a pointer to the object to be filled
func ReadJSONBytes(d []byte, ptr interface{}) (err error) {
ReadJSONPtr(ptr, d, &err)
return
}
// NOTE: does not care about the type, only the binary representation.
func BinaryEqual(a, b interface{}) bool {
aBytes := BinaryBytes(a)
bBytes := BinaryBytes(b)
return bytes.Equal(aBytes, bBytes)
}
// NOTE: does not care about the type, only the binary representation.
func BinaryCompare(a, b interface{}) int {
aBytes := BinaryBytes(a)
bBytes := BinaryBytes(b)
return bytes.Compare(aBytes, bBytes)
}
// NOTE: only use this if you need 32 bytes.
func BinarySha256(o interface{}) []byte {
hasher, n, err := sha256.New(), new(int), new(error)
WriteBinary(o, hasher, n, err)
if *err != nil {
cmn.PanicSanity(*err)
}
return hasher.Sum(nil)
}
// NOTE: The default hash function is Ripemd160.
func BinaryRipemd160(o interface{}) []byte {
hasher, n, err := ripemd160.New(), new(int), new(error)
WriteBinary(o, hasher, n, err)
if *err != nil {
cmn.PanicSanity(*err)
}
return hasher.Sum(nil)
}