preallocate.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 extendFile {
  26. return preallocExtend(f, sizeInBytes)
  27. }
  28. return preallocFixed(f, sizeInBytes)
  29. }
  30. func preallocExtendTrunc(f *os.File, sizeInBytes int64) error {
  31. curOff, err := f.Seek(0, io.SeekCurrent)
  32. if err != nil {
  33. return err
  34. }
  35. size, err := f.Seek(sizeInBytes, io.SeekEnd)
  36. if err != nil {
  37. return err
  38. }
  39. if _, err = f.Seek(curOff, io.SeekStart); err != nil {
  40. return err
  41. }
  42. if sizeInBytes > size {
  43. return nil
  44. }
  45. return f.Truncate(sizeInBytes)
  46. }