-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathserialize.go
48 lines (45 loc) · 942 Bytes
/
serialize.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
package btree
import (
"bufio"
"github.com/golang/protobuf/proto"
"io/ioutil"
"os"
)
// Marshal btree to disk
func (t *Btree) Marshal(filename string) error {
fd, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_SYNC, 0644)
if err != nil {
return err
}
defer fd.Close()
fb := bufio.NewWriter(fd)
data, err := proto.Marshal(&t.BtreeMetadata)
if err != nil {
return err
}
_, err = fb.Write(data)
if err != nil {
return err
}
return fb.Flush()
}
// Unmarshal btree from disk
func Unmarshal(filename string) (*Btree, error) {
tree := &Btree{
dupnodelist: make(map[int64]int),
opChan: make(chan *treeOperation),
}
fd, err := os.Open(filename)
if err != nil {
return tree, err
}
defer fd.Close()
dataRecord, err := ioutil.ReadAll(fd)
if err != nil {
return tree, err
}
tree.BtreeMetadata = BtreeMetadata{}
proto.Unmarshal(dataRecord, &tree.BtreeMetadata)
go tree.run()
return tree, err
}