-
Notifications
You must be signed in to change notification settings - Fork 0
/
qstore.go
84 lines (71 loc) · 1.53 KB
/
qstore.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
package qstore
import (
"github.com/pkg/errors"
"os"
"strings"
"sync"
)
type Qstore interface {
//write
OpenTx(key string) (*Tx, error)
//read
Read(key string, idx uint64) ([]byte, error)
//readbatch
ReadBatch(key string, idx uint64, len int) ([]byte, error)
}
type qstore struct {
dir string
keyQueue *sync.Map // key is string(dirkey),value is *diskQueue
opt *Options
}
type Options struct {
NoSync bool
Mmap bool
FileMaxSize int64
}
var defaultFileMaxSize = 1024 * 1024 * 1024
func NewQstore(dir string, opt *Options) (Qstore, error) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return nil, err
}
if !strings.HasSuffix(dir, "/") {
dir += "/"
}
if opt == nil {
opt = &Options{
FileMaxSize: int64(defaultFileMaxSize),
}
}
return &qstore{
dir: dir,
keyQueue: &sync.Map{},
opt: opt,
}, nil
}
func (q *qstore) OpenTx(key string) (t *Tx, err error) {
dq, load := q.keyQueue.Load(q.dirkey(key))
if !load {
dq, err = newDiskQueue(q.dir, key, q.opt)
if err != nil {
return
}
q.keyQueue.Store(q.dirkey(key), dq)
}
t = &Tx{dq: dq.(*diskQueue)}
return
}
func (q *qstore) Read(key string, idx uint64) ([]byte, error) {
return q.ReadBatch(key, idx, 1)
}
func (q *qstore) ReadBatch(key string, idx uint64, len int) ([]byte, error) {
key = q.dirkey(key)
queue, load := q.keyQueue.Load(key)
if !load {
return nil, errors.New("no key!")
}
return queue.(*diskQueue).read(idx, idx+uint64(len))
}
func (q *qstore) dirkey(key string) string {
return q.dir + key
}