-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.go
More file actions
99 lines (87 loc) · 1.48 KB
/
Copy pathblock.go
File metadata and controls
99 lines (87 loc) · 1.48 KB
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
package Buffermanager
import (
"io"
"os"
"sync"
)
type block struct {
filename string
blockid uint16
isDirty bool
pin bool
Data []byte
next *block
prev *block // double linked list
sync.Mutex
}
// operations
// set dirty page
func (b *block) setDirty() {
b.isDirty = true
}
// set pin block
func (b *block) setPin() {
b.pin = true
}
// unset pin block
func (b *block) setUnPin() {
b.pin = false
}
// release the lock of reading block
func (b *block) finishRead() {
b.Unlock()
return
}
//reset the block
func (b *block) reset() {
b.isDirty = false
b.pin = false
}
// init the block
func (b *block) init(filename string, bid uint16) {
b.filename = filename
b.blockid = bid
}
// read the file
func (b *block) read() error {
if b.isDirty {
return b.flush()
}
file, err := os.Open(b.filename)
if err != nil {
return nil
}
defer file.Close()
if err != nil {
return err
}
bid64 := int64(b.blockid)
_, err = file.Seek(bid64*blockSize, 0)
if err != nil {
return err
}
_, err = io.ReadFull(file, b.Data)
if err != nil {
return err
}
return err
}
// read back and flush
func (b *block) flush() error {
if !b.isDirty {
return nil
}
file, err := os.OpenFile(b.filename, os.O_WRONLY, 0666) // read and write
defer file.Close()
if err != nil {
return err
}
bid64 := int64(b.blockid)
_, err = file.Seek(bid64*blockSize, 0) // _ is a placeholder
if err != nil {
return err
}
_, err = file.Write(b.Data)
b.isDirty = false
return err
}