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.

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