-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsparse_unix.go
67 lines (55 loc) · 1.56 KB
/
sparse_unix.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
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
package sparsecat
import (
"errors"
"fmt"
"io"
"os"
"syscall"
)
const (
SEEK_DATA = 3
SEEK_HOLE = 4
)
// detectDataSection detects the start and end of the next section containing data. This
// skips any sparse sections. The implementation and supported filesystems are listed
// here https://man7.org/linux/man-pages/man2/lseek.2.html
func detectDataSection(file *os.File, offset int64) (start int64, end int64, err error) {
var syserr syscall.Errno
startOfData, err := file.Seek(offset, SEEK_DATA)
if errors.As(err, &syserr) {
if syserr == syscall.ENXIO {
return 0, 0, io.EOF
}
return 0, 0, fmt.Errorf("error seeking to data: %w", err)
}
if err != nil {
return 0, 0, fmt.Errorf("error seeking to data: %w", err)
}
endOfData, err := file.Seek(startOfData, SEEK_HOLE)
if errors.As(err, &syserr) {
if syserr == syscall.ENXIO {
return 0, 0, io.EOF
}
return 0, 0, fmt.Errorf("error seeking to hole: %w", err)
}
if err != nil {
return 0, 0, fmt.Errorf("error seeking to hole: %w", err)
}
return startOfData, endOfData, err
}
func supportsSeekHole(file *os.File) bool {
_, err := file.Seek(0, SEEK_DATA)
var syserr syscall.Errno
// when a file is completely empty SEEK_DATA fails with ENXIO indicating an EOF.
if errors.As(err, &syserr) {
if syserr == syscall.ENXIO {
return true
}
}
return err == nil
}
func SparseTruncate(file *os.File, size int64) error {
return file.Truncate(size)
}