sparse.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2019 Yunion
  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 fileutils
  15. import (
  16. "os"
  17. "yunion.io/x/pkg/errors"
  18. )
  19. type SparseFileWriter struct {
  20. *os.File
  21. needNul bool
  22. }
  23. func NewSparseFileWriter(f *os.File) *SparseFileWriter {
  24. w := &SparseFileWriter{
  25. File: f,
  26. }
  27. return w
  28. }
  29. func (w *SparseFileWriter) Write(d []byte) (int, error) {
  30. for _, b := range d {
  31. if b != 0 {
  32. w.needNul = false
  33. return w.File.Write(d)
  34. }
  35. }
  36. _, err := w.File.Seek(int64(len(d)), os.SEEK_CUR)
  37. if err != nil {
  38. return 0, err
  39. }
  40. w.needNul = true
  41. return len(d), nil
  42. }
  43. func (w *SparseFileWriter) PreClose() error {
  44. if w.needNul {
  45. if _, err := w.File.Seek(-1, os.SEEK_CUR); err != nil {
  46. return errors.Wrap(err, "seek back 1 byte")
  47. }
  48. if _, err := w.File.Write([]byte{0}); err != nil {
  49. return errors.Wrap(err, "write 1 nul byte")
  50. }
  51. w.needNul = false
  52. }
  53. return nil
  54. }
  55. func (w *SparseFileWriter) Close() (err error) {
  56. defer func() {
  57. err = w.File.Close()
  58. }()
  59. if err := w.PreClose(); err != nil {
  60. panic("BUG: call PreClose() and handle error: " + err.Error())
  61. }
  62. return
  63. }