-
Notifications
You must be signed in to change notification settings - Fork 0
/
whiskey.go
89 lines (71 loc) · 1.36 KB
/
whiskey.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
package whiskey
import (
"github.com/PathDNA/atoms"
"github.com/itsmontoya/rbt"
"github.com/missionMeteora/toolkit/errors"
)
const (
// ErrInvalidKey is returned when an invalid key is presented
ErrInvalidKey = errors.Error("invalid key")
)
const (
bucketPrefix = '_'
)
// New will return a new DB
func New(dir, name string) (dbp *DB, err error) {
var db DB
if db.w, err = rbt.NewMMAP(dir, name+".wdb", 1024); err != nil {
return
}
if db.s, err = rbt.NewMMAP(dir, name+".scratch.wdb", 1024); err != nil {
return
}
dbp = &db
return
}
// DB represents a database
type DB struct {
mux atoms.RWMux
w *rbt.Tree
// Scratch disk
s *rbt.Tree
rtxn *Txn
wtxn *Txn
}
// Read will return a read transaction
func (db *DB) Read(fn TxnFn) (err error) {
var txn Txn
txn.r = db.w
db.mux.Read(func() {
err = fn(&txn)
})
txn.r = nil
txn.kbuf = nil
return
}
// Update will return an update transaction
func (db *DB) Update(fn TxnFn) (err error) {
var txn Txn
txn.r = db.w
txn.w = db.s
db.mux.Update(func() {
defer db.s.Reset()
if err = fn(&txn); err != nil {
return
}
err = txn.flush()
})
txn.r = nil
txn.w = nil
txn.kbuf = nil
return
}
// Close will close an instance of DB
func (db *DB) Close() (err error) {
var errs errors.ErrorList
db.mux.Update(func() {
errs.Push(db.w.Close())
errs.Push(db.s.Close())
})
return errs.Err()
}