-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.go
86 lines (69 loc) · 1.29 KB
/
segment.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
package gobitcask
import (
"errors"
"os"
"path"
)
type Segment struct {
f *os.File
id string
readOnly bool
}
func OpenSegment(dir, id string) (*Segment, error) {
filePath := path.Join(dir, id)
f, err := os.OpenFile(filePath, os.O_RDONLY, 0755)
if err != nil {
return nil, err
}
return &Segment{
f: f,
id: id,
readOnly: true,
}, nil
}
func NewSegment(dir, id string) (*Segment, error) {
filePath := path.Join(dir, id)
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return nil, err
}
return &Segment{
f: f,
id: id,
}, nil
}
func (s *Segment) Read(offset, n int) ([]byte, error) {
b := make([]byte, n)
_, err := s.f.ReadAt(b, int64(offset))
if err != nil {
return nil, err
}
return b, nil
}
func (s *Segment) Write(offset int, b []byte) error {
if s.readOnly {
return errors.New("can't write to read-only segment")
}
_, err := s.f.WriteAt(b, int64(offset))
if err != nil {
return err
}
return nil
}
func (s *Segment) GetOffset() (int, error) {
info, err := s.f.Stat()
if err != nil {
return 0, err
}
return int(info.Size()), nil
}
func (s *Segment) GetID() string {
return s.id
}
func (s *Segment) Close() error {
err := s.f.Sync()
if err != nil {
return err
}
return s.f.Close()
}