preallocate.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. package fileutil
  15. import (
  16. "io"
  17. "os"
  18. )
  19. // Preallocate tries to allocate the space for given
  20. // file. This operation is only supported on linux by a
  21. // few filesystems (btrfs, ext4, etc.).
  22. // If the operation is unsupported, no error will be returned.
  23. // Otherwise, the error encountered will be returned.
  24. func Preallocate(f *os.File, sizeInBytes int64, extendFile bool) error {
  25. if sizeInBytes == 0 {
  26. // fallocate will return EINVAL if length is 0; skip
  27. return nil
  28. }
  29. if extendFile {
  30. return preallocExtend(f, sizeInBytes)
  31. }
  32. return preallocFixed(f, sizeInBytes)
  33. }
  34. func preallocExtendTrunc(f *os.File, sizeInBytes int64) error {
  35. curOff, err := f.Seek(0, io.SeekCurrent)
  36. if err != nil {
  37. return err
  38. }
  39. size, err := f.Seek(sizeInBytes, io.SeekEnd)
  40. if err != nil {
  41. return err
  42. }
  43. if _, err = f.Seek(curOff, io.SeekStart); err != nil {
  44. return err
  45. }
  46. if sizeInBytes > size {
  47. return nil
  48. }
  49. return f.Truncate(sizeInBytes)
  50. }