2014-06-05 02:33:50 -07:00
|
|
|
package binary
|
|
|
|
|
|
|
|
import (
|
2014-07-01 14:50:24 -07:00
|
|
|
"bytes"
|
|
|
|
"crypto/sha256"
|
2015-06-09 23:17:19 -04:00
|
|
|
"github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160"
|
2014-06-05 02:33:50 -07:00
|
|
|
)
|
|
|
|
|
2015-06-17 00:16:58 -04:00
|
|
|
// THESE PANICS ARE SANITY CHECKS
|
|
|
|
|
2014-12-09 18:49:04 -08:00
|
|
|
func BinaryBytes(o interface{}) []byte {
|
|
|
|
w, n, err := new(bytes.Buffer), new(int64), new(error)
|
|
|
|
WriteBinary(o, w, n, err)
|
|
|
|
if *err != nil {
|
2015-04-12 17:46:16 -07:00
|
|
|
panic(*err)
|
2014-10-04 19:16:49 -07:00
|
|
|
}
|
2014-12-09 18:49:04 -08:00
|
|
|
return w.Bytes()
|
2014-06-05 02:33:50 -07:00
|
|
|
}
|
|
|
|
|
2015-01-05 14:04:42 -08:00
|
|
|
func JSONBytes(o interface{}) []byte {
|
|
|
|
w, n, err := new(bytes.Buffer), new(int64), new(error)
|
|
|
|
WriteJSON(o, w, n, err)
|
|
|
|
if *err != nil {
|
2015-04-12 17:46:16 -07:00
|
|
|
panic(*err)
|
2015-01-05 14:04:42 -08:00
|
|
|
}
|
|
|
|
return w.Bytes()
|
|
|
|
}
|
|
|
|
|
2014-06-05 02:33:50 -07:00
|
|
|
// NOTE: does not care about the type, only the binary representation.
|
2014-12-09 18:49:04 -08:00
|
|
|
func BinaryEqual(a, b interface{}) bool {
|
2014-07-01 14:50:24 -07:00
|
|
|
aBytes := BinaryBytes(a)
|
|
|
|
bBytes := BinaryBytes(b)
|
|
|
|
return bytes.Equal(aBytes, bBytes)
|
2014-06-05 02:33:50 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// NOTE: does not care about the type, only the binary representation.
|
2014-12-09 18:49:04 -08:00
|
|
|
func BinaryCompare(a, b interface{}) int {
|
2014-07-01 14:50:24 -07:00
|
|
|
aBytes := BinaryBytes(a)
|
|
|
|
bBytes := BinaryBytes(b)
|
|
|
|
return bytes.Compare(aBytes, bBytes)
|
2014-06-05 02:33:50 -07:00
|
|
|
}
|
|
|
|
|
2015-07-10 12:15:46 -07:00
|
|
|
// NOTE: only use this if you need 32 bytes.
|
2014-12-09 18:49:04 -08:00
|
|
|
func BinarySha256(o interface{}) []byte {
|
|
|
|
hasher, n, err := sha256.New(), new(int64), new(error)
|
|
|
|
WriteBinary(o, hasher, n, err)
|
|
|
|
if *err != nil {
|
2015-04-12 17:46:16 -07:00
|
|
|
panic(*err)
|
2014-12-09 18:49:04 -08:00
|
|
|
}
|
|
|
|
return hasher.Sum(nil)
|
|
|
|
}
|
|
|
|
|
2015-07-10 12:15:46 -07:00
|
|
|
// NOTE: The default hash function is Ripemd160.
|
2014-12-09 18:49:04 -08:00
|
|
|
func BinaryRipemd160(o interface{}) []byte {
|
|
|
|
hasher, n, err := ripemd160.New(), new(int64), new(error)
|
|
|
|
WriteBinary(o, hasher, n, err)
|
|
|
|
if *err != nil {
|
2015-04-12 17:46:16 -07:00
|
|
|
panic(*err)
|
2014-07-01 14:50:24 -07:00
|
|
|
}
|
2014-09-03 19:21:19 -07:00
|
|
|
return hasher.Sum(nil)
|
2014-06-05 02:33:50 -07:00
|
|
|
}
|