You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

11 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
  1. package binary
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "github.com/tendermint/tendermint/Godeps/_workspace/src/code.google.com/p/go.crypto/ripemd160"
  6. )
  7. // THESE PANICS ARE SANITY CHECKS
  8. func BinaryBytes(o interface{}) []byte {
  9. w, n, err := new(bytes.Buffer), new(int64), new(error)
  10. WriteBinary(o, w, n, err)
  11. if *err != nil {
  12. panic(*err)
  13. }
  14. return w.Bytes()
  15. }
  16. func JSONBytes(o interface{}) []byte {
  17. w, n, err := new(bytes.Buffer), new(int64), new(error)
  18. WriteJSON(o, w, n, err)
  19. if *err != nil {
  20. panic(*err)
  21. }
  22. return w.Bytes()
  23. }
  24. // NOTE: does not care about the type, only the binary representation.
  25. func BinaryEqual(a, b interface{}) bool {
  26. aBytes := BinaryBytes(a)
  27. bBytes := BinaryBytes(b)
  28. return bytes.Equal(aBytes, bBytes)
  29. }
  30. // NOTE: does not care about the type, only the binary representation.
  31. func BinaryCompare(a, b interface{}) int {
  32. aBytes := BinaryBytes(a)
  33. bBytes := BinaryBytes(b)
  34. return bytes.Compare(aBytes, bBytes)
  35. }
  36. // NOTE: only use this if you need 32 bytes.
  37. func BinarySha256(o interface{}) []byte {
  38. hasher, n, err := sha256.New(), new(int64), new(error)
  39. WriteBinary(o, hasher, n, err)
  40. if *err != nil {
  41. panic(*err)
  42. }
  43. return hasher.Sum(nil)
  44. }
  45. // NOTE: The default hash function is Ripemd160.
  46. func BinaryRipemd160(o interface{}) []byte {
  47. hasher, n, err := ripemd160.New(), new(int64), new(error)
  48. WriteBinary(o, hasher, n, err)
  49. if *err != nil {
  50. panic(*err)
  51. }
  52. return hasher.Sum(nil)
  53. }