This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemory.go
92 lines (77 loc) · 1.83 KB
/
memory.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
package mmbot
import (
"fmt"
"os"
"reflect"
"strings"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
)
const (
LEVELDB_PATH = "mmbot.ldb"
)
type Memory struct {
db *leveldb.DB
}
func NewMemory() (*Memory, error) {
storage := os.Getenv("LEVELDB_PATH")
if storage == "" {
storage = LEVELDB_PATH
}
db, err := leveldb.OpenFile(storage, nil)
if err != nil {
return nil, err
}
return &Memory{db}, nil
}
func (m *Memory) Get(plugin Plugin, key string) (string, error) {
ns_key := fmt.Sprintf("%s:%s", m.namespace(plugin), key)
if val, err := m.db.Get([]byte(ns_key), nil); err != nil {
return "", err
} else {
return string(val), nil
}
}
func (m *Memory) Put(plugin Plugin, key string, val string) error {
ns_key := fmt.Sprintf("%s:%s", m.namespace(plugin), key)
if err := m.db.Put([]byte(ns_key), []byte(val), nil); err != nil {
return err
} else {
return nil
}
}
func (m *Memory) Del(plugin Plugin, key string) (string, error) {
var val string
if tmp, err := m.Get(plugin, key); err != nil {
return "", err
} else {
val = tmp
}
ns_key := fmt.Sprintf("%s:%s", m.namespace(plugin), key)
if err := m.db.Delete([]byte(ns_key), nil); err != nil {
return "", err
} else {
return val, nil
}
}
func (m *Memory) List(plugin Plugin) (map[string]string, error) {
list := map[string]string{}
ns_prefix := fmt.Sprintf("%s:", m.namespace(plugin))
iter := m.db.NewIterator(util.BytesPrefix([]byte(ns_prefix)), nil)
for iter.Next() {
ns_key := iter.Key()
key := ns_key[len(ns_prefix):]
val := iter.Value()
list[string(key)] = string(val)
}
iter.Release()
if err := iter.Error(); err != nil {
return nil, err
} else {
return list, nil
}
}
func (m *Memory) namespace(plugin Plugin) string {
namespace := reflect.TypeOf(plugin).String()
return strings.ToUpper(namespace)
}