/
h256.go
100 lines (85 loc) · 1.82 KB
/
h256.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package smt
import (
"bytes"
"github.com/dotbitHQ/das-lib/common"
)
type H256 []byte
func H256Zero() H256 {
zero := make(H256, 32)
return zero
}
func (h *H256) String() string {
return common.Bytes2Hex(*h)
}
func (h *H256) IsZero() bool {
zero := H256Zero()
if bytes.Compare(*h, zero) == 0 {
return true
}
return false
}
func (h *H256) SetBit(height byte) {
bytePos := height / 8
bitPos := height % 8
(*h)[bytePos] |= 1 << bitPos
}
func (h *H256) CopyBits(height byte) *H256 {
target := H256Zero()
startByte := height / ByteSize
copy(target[startByte:], (*h)[startByte:])
remain := height % ByteSize
if remain > 0 {
target[startByte] &= 0b11111111 << remain
}
return &target
}
func (h *H256) CopyBits2(height byte) *H256 {
target := H256Zero()
startByte := height / ByteSize
copy(target[startByte:], (*h)[startByte:])
for i := startByte * 8; i < height; i++ {
target.ClearBit(i)
}
return &target
}
func (h *H256) ClearBit(height byte) {
bytePos := height / 8
bitPos := height % 8
(*h)[bytePos] &= ^(1 << bitPos)
}
func (h *H256) ParentPath(height byte) *H256 {
if height == 255 {
tmp := H256Zero()
return &tmp
} else {
return h.CopyBits(height + 1)
}
}
func (h *H256) IsRight(height byte) bool {
return h.GetBit(height)
}
func (h *H256) GetBit(height byte) bool {
bytePos := height / 8
bitPos := height % 8
return (((*h)[bytePos] >> bitPos) & 1) != 0
}
func (h *H256) ForkHeight(key *H256) byte {
for i := 0; i <= MaxU8; i++ {
height := byte(i)
if h.GetBit(height) != key.GetBit(height) {
return height
}
}
return 0
}
// qsort
type SortH256 []H256
func (s SortH256) Len() int { return len(s) }
func (s SortH256) Less(i, j int) bool {
if res := bytes.Compare(s[i], s[j]); res > 0 {
return false
} else {
return true
}
}
func (s SortH256) Swap(i, j int) { s[i], s[j] = s[j], s[i] }