-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpersistentmap.go
125 lines (104 loc) · 2.53 KB
/
persistentmap.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package persistentmap
import (
"fmt"
"log"
"github.com/boltdb/bolt"
)
const (
MapBucket = "map"
)
type SerializeFunc func(interface{}) []byte
type DeserializeFunc func([]byte) interface{}
type PersistentMap struct {
db *bolt.DB
name string
serializer SerializeFunc
deserializer DeserializeFunc
}
func NewPersistentMap(filename string) *PersistentMap {
db, err := bolt.Open(filename, 0600, nil)
if err != nil {
log.Fatal(err)
}
db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucket([]byte(MapBucket))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
return &PersistentMap{db: db, name: MapBucket}
}
func NewPersistentMapWithSerialization(filename string, serializer SerializeFunc, deserializer DeserializeFunc) *PersistentMap {
m := NewPersistentMap(filename)
m.serializer = serializer
m.deserializer = deserializer
return m
}
func (m *PersistentMap) SerializeAndSet(key string, obj interface{}) {
m.Set(key, m.serializer(obj))
}
func (m *PersistentMap) GetAndDeserialize(key string) interface{} {
return m.deserializer(m.Get(key))
}
func (m *PersistentMap) Set(key string, data []byte) {
m.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(m.name))
err := b.Put([]byte(key), data)
return err
})
}
func (m *PersistentMap) Get(key string) []byte {
returnValue := []byte{}
m.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(m.name))
returnValue = b.Get([]byte(key))
return nil
})
return returnValue
}
func (m *PersistentMap) Close() {
m.db.Close()
}
func (m *PersistentMap) Delete(key string) {
m.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(m.name))
err := b.Delete([]byte(key))
return err
})
}
type Tuple struct {
Key string
Value []byte
}
func (m *PersistentMap) IterationChannel() chan Tuple {
returnChan := make(chan Tuple)
go func() {
m.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(m.name))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
var aux = make([]byte, len(v))
copy(aux, v)
returnChan <- Tuple{string(k), aux}
}
close(returnChan)
return nil
})
}()
return returnChan
}
type DeserializedTuple struct {
Key string
Value interface{}
}
func (m *PersistentMap) IterationDeserializedChannel() chan DeserializedTuple {
returnChan := make(chan DeserializedTuple)
go func() {
for tuple := range m.IterationChannel() {
returnChan <- DeserializedTuple{tuple.Key, m.deserializer(tuple.Value)}
}
close(returnChan)
}()
return returnChan
}