-
Notifications
You must be signed in to change notification settings - Fork 0
/
growtree.go
75 lines (63 loc) · 1.35 KB
/
growtree.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
package ipdb
import (
"encoding/binary"
"errors"
"github.com/GreenYun/ipdb/iptree"
)
var (
errNotLeaf = errors.New("Not a Leaf at that position")
errNotNode = errors.New("Not a Node at that position")
)
// GrowTree return the root Node of the iptree.
func (d *IPDb) GrowTree() (*iptree.Node, error) {
node, err := d.getNode(d.startFrom)
if err != nil {
return nil, err
}
return node, nil
}
func (d *IPDb) getNode(offset uint32) (*iptree.Node, error) {
nodeCount := d.Metadata.NodeCount
if offset > nodeCount {
return nil, errNotNode
}
pos := offset * 8
leftOffset := binary.BigEndian.Uint32(d.Data[pos : pos+4])
pos += 4
rightOffset := binary.BigEndian.Uint32(d.Data[pos : pos+4])
node := new(iptree.Node)
var err error
if leftOffset >= nodeCount {
node.Left, err = d.getLeaf(leftOffset)
if err != nil {
return nil, err
}
} else {
node.Left, err = d.getNode(leftOffset)
if err != nil {
return nil, err
}
}
if rightOffset >= nodeCount {
node.Right, err = d.getLeaf(rightOffset)
if err != nil {
return nil, err
}
} else {
node.Right, err = d.getNode(rightOffset)
if err != nil {
return nil, err
}
}
return node, nil
}
func (d *IPDb) getLeaf(offset uint32) (*iptree.Leaf, error) {
data, err := d.GetRaw(offset)
if err != nil {
return nil, err
}
leaf := &iptree.Leaf{
Data: data,
}
return leaf, nil
}