-
Notifications
You must be signed in to change notification settings - Fork 106
/
depth.go
40 lines (33 loc) · 883 Bytes
/
depth.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
package node
import (
"encoding/binary"
"unsafe"
)
// Depth determines the maximum length of the key in bits.
//
// maxKeyLengthInBits = 2^size_of(Depth)*8
type Depth uint16
// DepthSize is the size of Depth in bytes.
const DepthSize = int(unsafe.Sizeof(Depth(0)))
// ToBytes returns the number of bytes needed to fit given bits.
func (dt Depth) ToBytes() int {
size := dt / 8
if dt%8 != 0 {
size++
}
return int(size)
}
// MarshalBinary encodes a Depth into binary form.
func (dt Depth) MarshalBinary() []byte {
data := make([]byte, DepthSize)
binary.LittleEndian.PutUint16(data, uint16(dt))
return data
}
// UnmarshalBinary decodes a binary marshaled depth.
func (dt *Depth) UnmarshalBinary(data []byte) (int, error) {
if len(data) < DepthSize {
return 0, ErrMalformedNode
}
*dt = Depth(binary.LittleEndian.Uint16(data[0:DepthSize]))
return DepthSize, nil
}