-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_file.go
92 lines (77 loc) · 1.87 KB
/
db_file.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 gobitcask
import (
"os"
"path/filepath"
"sync"
)
type DBFile struct {
File *os.File
Offset int64
HeaderBufPool *sync.Pool
}
const FileName = "gobitcask.data"
const MergeFileName = "gobitcask.data.merge"
// create new DB file and return it
func newInternal(filePath string) (*DBFile, error) {
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
stat, err := os.Stat(filePath)
if err != nil {
return nil, err
}
// what's this?
pool := &sync.Pool{New: func() interface{} {
return make([]byte, entryHeaderSize)
}}
return &DBFile{Offset: stat.Size(), File: file, HeaderBufPool: pool}, nil
}
func NewDBFile(path string) (*DBFile, error) {
filePath := filepath.Join(path, FileName)
return newInternal(filePath)
}
func NewDBMergeFile(path string) (*DBFile, error) {
filePath := filepath.Join(path, MergeFileName)
return newInternal(filePath)
}
// write Entry to db file
func (df *DBFile) Write(e *Entry) (err error) {
enc, err := e.Encode()
if err != nil {
return nil
}
_, err = df.File.WriteAt(enc, df.Offset)
df.Offset += e.GetSize()
return
}
// read Entry from db file with offset
func (df *DBFile) Read(offset int64) (e *Entry, err error) {
// https://hackernoon.com/go-and-syncpool
buffer := df.HeaderBufPool.Get().([]byte)
defer df.HeaderBufPool.Put(buffer)
// check if we can read buffer from offset position
if _, err = df.File.ReadAt(buffer, offset); err != nil {
return
}
if e, err = Decode(buffer); err != nil {
return
}
offset += entryHeaderSize
if e.KeySize > 0 {
key := make([]byte, e.KeySize)
if _, err = df.File.ReadAt(key, offset); err != nil {
return
}
e.Key = key
}
offset += int64(e.KeySize)
if e.ValueSize > 0 {
value := make([]byte, e.ValueSize)
if _, err = df.File.ReadAt(value, offset); err != nil {
return
}
e.Value = value
}
return
}