This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
79 lines (62 loc) · 1.97 KB
/
load.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
package boltdbtoipldhamt
import (
hamtcontainer "github.com/simplecoincom/go-ipld-adl-hamt-container"
"github.com/simplecoincom/go-ipld-adl-hamt-container/storage"
"go.etcd.io/bbolt"
)
const rootNodeKey = "root"
type Loader struct {
db *bbolt.DB
storage storage.Storage
topLevelBuckets []string
rootTreeNode *TreeNode
rootHAMTContainer *hamtcontainer.HAMTContainer
}
func NewLoader(db *bbolt.DB, storage storage.Storage, topLevelBuckets []string) Loader {
return Loader{db, storage, topLevelBuckets, nil, nil}
}
func readBucket(loader *Loader, bucket *bbolt.Bucket, currentTreeNode *TreeNode) error {
return bucket.ForEach(func(k, v []byte) error {
if v == nil {
nestedBucket := bucket.Bucket(k)
hamtContainer, err := hamtcontainer.NewHAMTBuilder().Key(k).Storage(loader.storage).Build()
if err != nil {
return err
}
return readBucket(loader, nestedBucket, currentTreeNode.AddChild(hamtContainer))
}
hamtContainer := currentTreeNode.Data.(*hamtcontainer.HAMTContainer)
hamtContainer.Set(k, v)
return nil
})
}
func (l Loader) GetRootTreeNode() *TreeNode {
return l.rootTreeNode
}
func (l Loader) GetRootHAMTContainer() *hamtcontainer.HAMTContainer {
return l.rootHAMTContainer
}
func (l *Loader) LoadTree() error {
tx, err := l.db.Begin(false)
if err != nil {
return err
}
defer tx.Rollback()
l.rootHAMTContainer, err = hamtcontainer.NewHAMTBuilder().Key([]byte(rootNodeKey)).Storage(l.storage).Build()
if err != nil {
return err
}
l.rootTreeNode = NewTreeNode(l.rootHAMTContainer, nil)
for _, topLevelBucket := range l.topLevelBuckets {
nestedBucket := tx.Bucket([]byte(topLevelBucket))
nestedHAMTContainer, err := hamtcontainer.NewHAMTBuilder().Key([]byte(topLevelBucket)).Storage(l.storage).Build()
if err != nil {
return err
}
if err := readBucket(l, nestedBucket, l.rootTreeNode.AddChild(nestedHAMTContainer)); err != nil {
return err
}
}
TransverseTreeNode(l.rootTreeNode, nil)
return nil
}