Debian Codegraph @

vendor/github.com/coreos/etcd/pkg/fileutil/preallocate.go

raw
1 // Copyright 2015 The etcd Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package fileutil
16
17 import (
18 "io"
19 "os"
20 )
21
22 // Preallocate tries to allocate the space for given
23 // file. This operation is only supported on linux by a
24 // few filesystems (btrfs, ext4, etc.).
25 // If the operation is unsupported, no error will be returned.
26 // Otherwise, the error encountered will be returned.
27 func Preallocate(f *os.File, sizeInBytes int64, extendFile bool) error {
28 if sizeInBytes == 0 {
29 // fallocate will return EINVAL if length is 0; skip
30 return nil
31 }
32 if extendFile {
33 return preallocExtend(f, sizeInBytes)
34 }
35 return preallocFixed(f, sizeInBytes)
36 }
37
38 func preallocExtendTrunc(f *os.File, sizeInBytes int64) error {
39 curOff, err := f.Seek(0, io.SeekCurrent)
40 if err != nil {
41 return err
42 }
43 size, err := f.Seek(sizeInBytes, io.SeekEnd)
44 if err != nil {
45 return err
46 }
47 if _, err = f.Seek(curOff, io.SeekStart); err != nil {
48 return err
49 }
50 if sizeInBytes > size {
51 return nil
52 }
53 return f.Truncate(sizeInBytes)
54 }