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.

78 lines
1.6 KiB

  1. package common
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "sort"
  6. )
  7. var (
  8. Zero256 = Word256{0}
  9. One256 = Word256{1}
  10. )
  11. type Word256 [32]byte
  12. func (w Word256) String() string { return string(w[:]) }
  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) 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. word := Word256{}
  28. PutUint64(word[:], i)
  29. return word
  30. }
  31. func RightPadWord256(bz []byte) (word Word256) {
  32. copy(word[:], bz)
  33. return
  34. }
  35. func LeftPadWord256(bz []byte) (word Word256) {
  36. copy(word[32-len(bz):], bz)
  37. return
  38. }
  39. func Uint64FromWord256(word Word256) uint64 {
  40. return binary.LittleEndian.Uint64(word[:])
  41. }
  42. //-------------------------------------
  43. type Tuple256 struct {
  44. First Word256
  45. Second Word256
  46. }
  47. func (tuple Tuple256) Compare(other Tuple256) int {
  48. firstCompare := tuple.First.Compare(other.First)
  49. if firstCompare == 0 {
  50. return tuple.Second.Compare(other.Second)
  51. } else {
  52. return firstCompare
  53. }
  54. }
  55. func Tuple256Split(t Tuple256) (Word256, Word256) {
  56. return t.First, t.Second
  57. }
  58. type Tuple256Slice []Tuple256
  59. func (p Tuple256Slice) Len() int { return len(p) }
  60. func (p Tuple256Slice) Less(i, j int) bool {
  61. return p[i].Compare(p[j]) < 0
  62. }
  63. func (p Tuple256Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  64. func (p Tuple256Slice) Sort() { sort.Sort(p) }