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.

79 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) 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. word := Word256{}
  29. PutUint64(word[:], i)
  30. return word
  31. }
  32. func RightPadWord256(bz []byte) (word Word256) {
  33. copy(word[:], bz)
  34. return
  35. }
  36. func LeftPadWord256(bz []byte) (word Word256) {
  37. copy(word[32-len(bz):], bz)
  38. return
  39. }
  40. func Uint64FromWord256(word Word256) uint64 {
  41. return binary.LittleEndian.Uint64(word[:])
  42. }
  43. //-------------------------------------
  44. type Tuple256 struct {
  45. First Word256
  46. Second Word256
  47. }
  48. func (tuple Tuple256) Compare(other Tuple256) int {
  49. firstCompare := tuple.First.Compare(other.First)
  50. if firstCompare == 0 {
  51. return tuple.Second.Compare(other.Second)
  52. } else {
  53. return firstCompare
  54. }
  55. }
  56. func Tuple256Split(t Tuple256) (Word256, Word256) {
  57. return t.First, t.Second
  58. }
  59. type Tuple256Slice []Tuple256
  60. func (p Tuple256Slice) Len() int { return len(p) }
  61. func (p Tuple256Slice) Less(i, j int) bool {
  62. return p[i].Compare(p[j]) < 0
  63. }
  64. func (p Tuple256Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  65. func (p Tuple256Slice) Sort() { sort.Sort(p) }