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.

90 lines
1.9 KiB

9 years ago
9 years ago
  1. package common
  2. import (
  3. "bytes"
  4. "sort"
  5. )
  6. var (
  7. Zero256 = Word256{0}
  8. One256 = Word256{1}
  9. )
  10. type Word256 [32]byte
  11. func (w Word256) String() string { return string(w[:]) }
  12. func (w Word256) TrimmedString() string { return TrimmedString(w.Bytes()) }
  13. func (w Word256) Copy() Word256 { return w }
  14. func (w Word256) Bytes() []byte { return w[:] } // copied.
  15. func (w Word256) Prefix(n int) []byte { return w[:n] }
  16. func (w Word256) Postfix(n int) []byte { return w[32-n:] }
  17. func (w Word256) IsZero() bool {
  18. accum := byte(0)
  19. for _, byt := range w {
  20. accum |= byt
  21. }
  22. return accum == 0
  23. }
  24. func (w Word256) Compare(other Word256) int {
  25. return bytes.Compare(w[:], other[:])
  26. }
  27. func Uint64ToWord256(i uint64) Word256 {
  28. buf := [8]byte{}
  29. PutUint64BE(buf[:], i)
  30. return LeftPadWord256(buf[:])
  31. }
  32. func Int64ToWord256(i int64) Word256 {
  33. buf := [8]byte{}
  34. PutInt64BE(buf[:], i)
  35. return LeftPadWord256(buf[:])
  36. }
  37. func RightPadWord256(bz []byte) (word Word256) {
  38. copy(word[:], bz)
  39. return
  40. }
  41. func LeftPadWord256(bz []byte) (word Word256) {
  42. copy(word[32-len(bz):], bz)
  43. return
  44. }
  45. func Uint64FromWord256(word Word256) uint64 {
  46. buf := word.Postfix(8)
  47. return GetUint64BE(buf)
  48. }
  49. func Int64FromWord256(word Word256) int64 {
  50. buf := word.Postfix(8)
  51. return GetInt64BE(buf)
  52. }
  53. //-------------------------------------
  54. type Tuple256 struct {
  55. First Word256
  56. Second Word256
  57. }
  58. func (tuple Tuple256) Compare(other Tuple256) int {
  59. firstCompare := tuple.First.Compare(other.First)
  60. if firstCompare == 0 {
  61. return tuple.Second.Compare(other.Second)
  62. }
  63. return firstCompare
  64. }
  65. func Tuple256Split(t Tuple256) (Word256, Word256) {
  66. return t.First, t.Second
  67. }
  68. type Tuple256Slice []Tuple256
  69. func (p Tuple256Slice) Len() int { return len(p) }
  70. func (p Tuple256Slice) Less(i, j int) bool {
  71. return p[i].Compare(p[j]) < 0
  72. }
  73. func (p Tuple256Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  74. func (p Tuple256Slice) Sort() { sort.Sort(p) }