forked from rosedblabs/mini-bitcask
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_file.go
81 lines (70 loc) · 1.63 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
package minidb
import (
"os"
"path/filepath"
)
const FileName = "minidb.data"
const MergeFileName = "minidb.data.merge"
// DBFile 数据文件定义
type DBFile struct {
File *os.File
Offset int64
}
func newInternal(fileName string) (*DBFile, error) {
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return nil, err
}
stat, err := os.Stat(fileName)
if err != nil {
return nil, err
}
return &DBFile{Offset: stat.Size(), File: file}, nil
}
// NewDBFile 创建一个新的数据文件
func NewDBFile(path string) (*DBFile, error) {
fileName := filepath.Join(path, FileName)
return newInternal(fileName)
}
// NewMergeDBFile 新建一个合并时的数据文件
func NewMergeDBFile(path string) (*DBFile, error) {
fileName := filepath.Join(path, MergeFileName)
return newInternal(fileName)
}
// Read 从 offset 处开始读取
func (df *DBFile) Read(offset int64) (e *Entry, err error) {
buf := make([]byte, entryHeaderSize)
if _, err = df.File.ReadAt(buf, offset); err != nil {
return
}
if e, err = Decode(buf); 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
}
// Write 写入 Entry
func (df *DBFile) Write(e *Entry) (err error) {
enc, err := e.Encode()
if err != nil {
return err
}
_, err = df.File.WriteAt(enc, df.Offset)
df.Offset += e.GetSize()
return
}