-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_file.go
117 lines (102 loc) · 2.16 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package mini_kv_db
import "os"
const FileName = "minikvdb.data"
const MergeFileName = "minikvdb.data.merge"
type DbFile struct {
File *os.File
Offset int64
}
//
// newInternal
// @Description: 新建一个文件
// @param fileName
// @return *DbFile
// @return error
//
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{File: file, Offset: stat.Size()}, nil
}
//
// NewDbFile
// @Description: 新建一个数据文件
// @param path
// @return *DbFile
// @return error
//
func NewDbFile(path string) (*DbFile, error) {
fileName := path + string(os.PathSeparator) + FileName
return newInternal(fileName)
}
//
// NewMergeDbFile
// @Description: 新建一个合并数据文件
// @param path
// @return *DbFile
// @return error
//
func NewMergeDbFile(path string) (*DbFile, error) {
fileName := path + string(os.PathSeparator) + MergeFileName
return newInternal(fileName)
}
//
// Read
// @Description: 读指定偏移位置的Entry
// @receiver df
// @param offset 偏移量
// @return entry
// @return err
//
func (df *DbFile) Read(offset int64) (entry *Entry, err error) {
buf := make([]byte, entryHeaderSize)
if _, err = df.File.ReadAt(buf, offset); err != nil {
return
}
if entry, err = Decode(buf); err != nil {
return
}
offset = offset + entryHeaderSize
if entry.KeySize > 0 {
key := make([]byte, entry.KeySize)
if _, err = df.File.ReadAt(key, offset); err != nil {
return
}
entry.Key = key
}
offset = offset + int64(entry.KeySize)
if entry.ValueSize > 0 {
value := make([]byte, entry.ValueSize)
_, err := df.File.ReadAt(value, offset)
if err != nil {
return nil, err
}
entry.Value = value
}
return entry, nil
}
//
// Write
// @Description: 把一个Entry写入数据文件
// @receiver df
// @param e
// @return err
//
func (df *DbFile) Write(e *Entry) (err error) {
encodeOne, err := e.Encode()
if err != nil {
return err
}
_, err = df.File.WriteAt(encodeOne, df.Offset)
if err != nil {
return
}
df.Offset = df.Offset + e.GetSize()
return
}