-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathbitslice.go
59 lines (49 loc) · 1.2 KB
/
bitslice.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
package merkletree
import (
"encoding/binary"
"math/big"
)
func byteslice(h []byte, numBytes int, level int) ([]byte, uint32) {
start := numBytes * level
end := numBytes * (level + 1)
if start > len(h) {
start = len(h)
}
if end > len(h) {
end = len(h)
}
ret := h[start:end]
// Also map the returned byteslice to 0,1,2....2^numBytes
var tmp [4]byte
copy(tmp[(4-len(ret)):], ret)
index := binary.BigEndian.Uint32(tmp[:])
return ret, index
}
func bitslice(h []byte, numBits int, level int) (Prefix, uint32) {
if numBits%8 == 0 {
return byteslice(h, numBits/8, level)
}
// Set a begin and end bit index
begin := numBits * level
end := numBits * (level + 1)
// No sense in using the large tail of the string, just
// chop it off here.
b := h[:((end + 7) >> 3)]
z := big.NewInt(0).SetBytes(b)
z = z.Rsh(z, uint(len(b)*8-end))
modulus := big.NewInt(1)
modulus = modulus.Lsh(modulus, uint(end-begin))
z = z.Mod(z, modulus)
ret := z.Bytes()
padlen := (end+7-begin)/8 - len(ret)
pad := make([]byte, padlen)
ret = append(pad, ret...)
tmp := z.Int64()
var index uint32
if tmp >= 0 && tmp <= 0xffffffff {
index = uint32(tmp)
} else {
panic("should never happen")
}
return ret, index
}