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.8 KiB

  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) Copy() Word256 { return w }
  13. func (w Word256) Bytes() []byte { return w[:] } // copied.
  14. func (w Word256) Prefix(n int) []byte { return w[:n] }
  15. func (w Word256) Postfix(n int) []byte { return w[32-n:] }
  16. func (w Word256) IsZero() bool {
  17. accum := byte(0)
  18. for _, byt := range w {
  19. accum |= byt
  20. }
  21. return accum == 0
  22. }
  23. func (w Word256) Compare(other Word256) int {
  24. return bytes.Compare(w[:], other[:])
  25. }
  26. func Uint64ToWord256(i uint64) Word256 {
  27. buf := [8]byte{}
  28. PutUint64BE(buf[:], i)
  29. return LeftPadWord256(buf[:])
  30. }
  31. func Int64ToWord256(i int64) Word256 {
  32. buf := [8]byte{}
  33. PutInt64BE(buf[:], i)
  34. return LeftPadWord256(buf[:])
  35. }
  36. func RightPadWord256(bz []byte) (word Word256) {
  37. copy(word[:], bz)
  38. return
  39. }
  40. func LeftPadWord256(bz []byte) (word Word256) {
  41. copy(word[32-len(bz):], bz)
  42. return
  43. }
  44. func Uint64FromWord256(word Word256) uint64 {
  45. buf := word.Postfix(8)
  46. return GetUint64BE(buf)
  47. }
  48. func Int64FromWord256(word Word256) int64 {
  49. buf := word.Postfix(8)
  50. return GetInt64BE(buf)
  51. }
  52. //-------------------------------------
  53. type Tuple256 struct {
  54. First Word256
  55. Second Word256
  56. }
  57. func (tuple Tuple256) Compare(other Tuple256) int {
  58. firstCompare := tuple.First.Compare(other.First)
  59. if firstCompare == 0 {
  60. return tuple.Second.Compare(other.Second)
  61. } else {
  62. return firstCompare
  63. }
  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) }