preallocate.go 1.4 KB

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