mirror of
https://github.com/restic/restic.git
synced 2026-09-26 14:00:29 +00:00
Move PreallocateFile to fs package
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func PreallocateFile(wr *os.File, size int64) error {
|
||||
// try contiguous first
|
||||
fst := unix.Fstore_t{
|
||||
Flags: unix.F_ALLOCATECONTIG | unix.F_ALLOCATEALL,
|
||||
Posmode: unix.F_PEOFPOSMODE,
|
||||
Offset: 0,
|
||||
Length: size,
|
||||
}
|
||||
err := unix.FcntlFstore(wr.Fd(), unix.F_PREALLOCATE, &fst)
|
||||
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// just take preallocation in any form, but still ask for everything
|
||||
fst.Flags = unix.F_ALLOCATEALL
|
||||
err = unix.FcntlFstore(wr.Fd(), unix.F_PREALLOCATE, &fst)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func PreallocateFile(wr *os.File, size int64) error {
|
||||
if size <= 0 {
|
||||
return nil
|
||||
}
|
||||
// int fallocate(int fd, int mode, off_t offset, off_t len)
|
||||
// use mode = 0 to also change the file size
|
||||
return unix.Fallocate(int(wr.Fd()), 0, 0, size)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !linux && !darwin
|
||||
// +build !linux,!darwin
|
||||
|
||||
package fs
|
||||
|
||||
import "os"
|
||||
|
||||
func PreallocateFile(wr *os.File, size int64) error {
|
||||
// Maybe truncate can help?
|
||||
// Windows: This calls SetEndOfFile which preallocates space on disk
|
||||
return wr.Truncate(size)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/test"
|
||||
)
|
||||
|
||||
func TestPreallocate(t *testing.T) {
|
||||
for _, i := range []int64{0, 1, 4096, 1024 * 1024} {
|
||||
t.Run(strconv.FormatInt(i, 10), func(t *testing.T) {
|
||||
dirpath := test.TempDir(t)
|
||||
|
||||
flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
|
||||
wr, err := os.OpenFile(path.Join(dirpath, "test"), flags, 0600)
|
||||
test.OK(t, err)
|
||||
defer func() {
|
||||
test.OK(t, wr.Close())
|
||||
}()
|
||||
|
||||
err = PreallocateFile(wr, i)
|
||||
if err == syscall.ENOTSUP {
|
||||
t.SkipNow()
|
||||
}
|
||||
test.OK(t, err)
|
||||
|
||||
fi, err := wr.Stat()
|
||||
test.OK(t, err)
|
||||
|
||||
efi := ExtendedStat(fi)
|
||||
test.Assert(t, efi.Size == i || efi.Blocks > 0, "Preallocated size of %v, got size %v block %v", i, efi.Size, efi.Blocks)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user