-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
blockfile_rw.go
86 lines (72 loc) · 1.89 KB
/
blockfile_rw.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package fsblkstorage
import (
"os"
"github.com/pkg/errors"
)
//// WRITER ////
type blockfileWriter struct {
filePath string
file *os.File
}
func newBlockfileWriter(filePath string) (*blockfileWriter, error) {
writer := &blockfileWriter{filePath: filePath}
return writer, writer.open()
}
func (w *blockfileWriter) truncateFile(targetSize int) error {
fileStat, err := w.file.Stat()
if err != nil {
return errors.Wrapf(err, "error truncating the file [%s] to size [%d]", w.filePath, targetSize)
}
if fileStat.Size() > int64(targetSize) {
w.file.Truncate(int64(targetSize))
}
return nil
}
func (w *blockfileWriter) append(b []byte, sync bool) error {
_, err := w.file.Write(b)
if err != nil {
return err
}
if sync {
return w.file.Sync()
}
return nil
}
func (w *blockfileWriter) open() error {
file, err := os.OpenFile(w.filePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
return errors.Wrapf(err, "error opening block file writer for file %s", w.filePath)
}
w.file = file
return nil
}
func (w *blockfileWriter) close() error {
return errors.WithStack(w.file.Close())
}
//// READER ////
type blockfileReader struct {
file *os.File
}
func newBlockfileReader(filePath string) (*blockfileReader, error) {
file, err := os.OpenFile(filePath, os.O_RDONLY, 0600)
if err != nil {
return nil, errors.Wrapf(err, "error opening block file reader for file %s", filePath)
}
reader := &blockfileReader{file}
return reader, nil
}
func (r *blockfileReader) read(offset int, length int) ([]byte, error) {
b := make([]byte, length)
_, err := r.file.ReadAt(b, int64(offset))
if err != nil {
return nil, errors.Wrapf(err, "error reading block file for offset %d and length %d", offset, length)
}
return b, nil
}
func (r *blockfileReader) close() error {
return errors.WithStack(r.file.Close())
}