OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / go-wire / util.go
1 package wire
2
3 import (
4         "bytes"
5         "crypto/sha256"
6         "encoding/json"
7
8         "golang.org/x/crypto/ripemd160"
9
10         cmn "github.com/tendermint/tmlibs/common"
11 )
12
13 func BinaryBytes(o interface{}) []byte {
14         w, n, err := new(bytes.Buffer), new(int), new(error)
15         WriteBinary(o, w, n, err)
16         if *err != nil {
17                 cmn.PanicSanity(*err)
18         }
19         return w.Bytes()
20 }
21
22 // ptr: a pointer to the object to be filled
23 func ReadBinaryBytes(d []byte, ptr interface{}) error {
24         r, n, err := bytes.NewBuffer(d), new(int), new(error)
25         ReadBinaryPtr(ptr, r, len(d), n, err)
26         return *err
27 }
28
29 func JSONBytes(o interface{}) []byte {
30         w, n, err := new(bytes.Buffer), new(int), new(error)
31         WriteJSON(o, w, n, err)
32         if *err != nil {
33                 cmn.PanicSanity(*err)
34         }
35         return w.Bytes()
36 }
37
38 // NOTE: inefficient
39 func JSONBytesPretty(o interface{}) []byte {
40         jsonBytes := JSONBytes(o)
41         var object interface{}
42         err := json.Unmarshal(jsonBytes, &object)
43         if err != nil {
44                 cmn.PanicSanity(err)
45         }
46         jsonBytes, err = json.MarshalIndent(object, "", "\t")
47         if err != nil {
48                 cmn.PanicSanity(err)
49         }
50         return jsonBytes
51 }
52
53 // ptr: a pointer to the object to be filled
54 func ReadJSONBytes(d []byte, ptr interface{}) (err error) {
55         ReadJSONPtr(ptr, d, &err)
56         return
57 }
58
59 // NOTE: does not care about the type, only the binary representation.
60 func BinaryEqual(a, b interface{}) bool {
61         aBytes := BinaryBytes(a)
62         bBytes := BinaryBytes(b)
63         return bytes.Equal(aBytes, bBytes)
64 }
65
66 // NOTE: does not care about the type, only the binary representation.
67 func BinaryCompare(a, b interface{}) int {
68         aBytes := BinaryBytes(a)
69         bBytes := BinaryBytes(b)
70         return bytes.Compare(aBytes, bBytes)
71 }
72
73 // NOTE: only use this if you need 32 bytes.
74 func BinarySha256(o interface{}) []byte {
75         hasher, n, err := sha256.New(), new(int), new(error)
76         WriteBinary(o, hasher, n, err)
77         if *err != nil {
78                 cmn.PanicSanity(*err)
79         }
80         return hasher.Sum(nil)
81 }
82
83 // NOTE: The default hash function is Ripemd160.
84 func BinaryRipemd160(o interface{}) []byte {
85         hasher, n, err := ripemd160.New(), new(int), new(error)
86         WriteBinary(o, hasher, n, err)
87         if *err != nil {
88                 cmn.PanicSanity(*err)
89         }
90         return hasher.Sum(nil)
91 }