-
Notifications
You must be signed in to change notification settings - Fork 1
/
disk.go
71 lines (64 loc) · 1.33 KB
/
disk.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
package buff
import (
"fmt"
"os"
"sync"
)
type DiskManager struct {
m *sync.Mutex
f *os.File
}
const (
PageSize = 4096
)
func NewDiskManager(filename string) *DiskManager {
file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
if err != nil {
panic(fmt.Sprintf("failed to open file %s", filename))
}
return &DiskManager{
m: &sync.Mutex{},
f: file,
}
}
func (d *DiskManager) WritePage(pageID int64, data []byte) error {
if len(data) != PageSize {
return fmt.Errorf("buffer provided must have size %d", PageSize)
}
d.m.Lock()
defer d.m.Unlock()
offset := pageID * PageSize
_, err := d.f.Seek(offset, 0)
if err != nil {
return err
}
written, err := d.f.Write(data)
if err != nil {
return err
}
if written != PageSize {
return fmt.Errorf("expect writtent byte %d, has %d", PageSize, written)
}
err = d.f.Sync()
return err
}
func (d *DiskManager) ReadPage(pageID int64, data []byte) error {
if len(data) != PageSize {
return fmt.Errorf("buffer provided must have size %d", PageSize)
}
d.m.Lock()
defer d.m.Unlock()
offset := pageID * PageSize
_, err := d.f.Seek(offset, 0)
if err != nil {
return err
}
readBytes, err := d.f.Read(data[:PageSize])
if err != nil {
return err
}
if readBytes != PageSize {
return fmt.Errorf("only read %d from file, expect %d", readBytes, PageSize)
}
return nil
}