-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsparsefile_common.go
131 lines (117 loc) · 2.31 KB
/
sparsefile_common.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package spgz
import (
"io"
"os"
)
const (
BUFSIZE = 32768
)
type Truncatable interface {
Truncate(size int64) error
}
type SparseFile interface {
io.ReadWriteSeeker
io.ReaderAt
io.WriterAt
io.Closer
Truncatable
PunchHole(offset, size int64) error
Sync() error
}
type SparseWriter struct {
SparseFile
}
type SparseFileWithFallback struct {
SparseFile
fallback bool
}
// NewSparseFileWithFallback creates a sparse file that will fall back to writing zeros if the first call to
// SparseFile.PunchHole() returns ErrPunchHoleNotSupported.
func NewSparseFileWithFallback(f *os.File) *SparseFileWithFallback {
return &SparseFileWithFallback{
SparseFile: NewSparseFile(f),
}
}
// NewSparseFileWithoutHolePunching creates a sparse file that will write zeros instead of calling SparseFile.PunchHole()
func NewSparseFileWithoutHolePunching(f *os.File) *SparseFileWithFallback {
return &SparseFileWithFallback{
SparseFile: NewSparseFile(f),
fallback: true,
}
}
func NewSparseWriter(f SparseFile) *SparseWriter {
return &SparseWriter{
SparseFile: f,
}
}
func (w *SparseWriter) Write(p []byte) (int, error) {
if IsBlockZero(p) {
offset, err := w.SparseFile.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
end, err := w.Seek(0, io.SeekEnd)
if err != nil {
return 0, err
}
l := int64(len(p))
if offset < end {
if offset+l < end {
err = w.PunchHole(offset, int64(len(p)))
if err != nil {
return 0, err
}
} else {
err = w.Truncate(offset)
if err != nil {
return 0, err
}
end = offset
}
}
offset += l
_, err = w.Seek(offset, io.SeekStart)
if err != nil {
return 0, err
}
if end < offset {
err = w.Truncate(offset)
if err != nil {
return 0, err
}
}
return len(p), nil
} else {
return w.SparseFile.Write(p)
}
}
func (f *SparseFileWithFallback) PunchHole(offset, size int64) error {
if !f.fallback {
err := f.SparseFile.PunchHole(offset, size)
if err != nil {
if err == ErrPunchHoleNotSupported {
f.fallback = true
} else {
return err
}
} else {
return nil
}
}
var buf [BUFSIZE]byte
for size > 0 {
var s int64
if size > BUFSIZE {
s = BUFSIZE
} else {
s = size
}
_, err := f.WriteAt(buf[:s], offset)
if err != nil {
return err
}
offset += s
size -= s
}
return nil
}