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. "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 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. buf := word.Postfix(8)
  41. return GetUint64BE(buf)
  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) }