ioutils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /*
  15. Copyright 2015 The Kubernetes Authors.
  16. Licensed under the Apache License, Version 2.0 (the "License");
  17. you may not use this file except in compliance with the License.
  18. You may obtain a copy of the License at
  19. http://www.apache.org/licenses/LICENSE-2.0
  20. Unless required by applicable law or agreed to in writing, software
  21. distributed under the License is distributed on an "AS IS" BASIS,
  22. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. See the License for the specific language governing permissions and
  24. limitations under the License.
  25. */
  26. package ioutils
  27. import "io"
  28. // LimitWriter is a copy of the standard library ioutils.LimitReader,
  29. // applied to the writer interface.
  30. // LimitWriter returns a Writer that writes to w
  31. // but stops with EOF after n bytes.
  32. // The underlying implementation is a *LimitedWriter.
  33. func LimitWriter(w io.Writer, n int64) io.Writer { return &LimitedWriter{w, n} }
  34. // A LimitedWriter writes to W but limits the amount of
  35. // data returned to just N bytes. Each call to Write
  36. // updates N to reflect the new amount remaining.
  37. // Write returns EOF when N <= 0 or when the underlying W returns EOF.
  38. type LimitedWriter struct {
  39. W io.Writer // underlying writer
  40. N int64 // max bytes remaining
  41. }
  42. func (l *LimitedWriter) Write(p []byte) (n int, err error) {
  43. if l.N <= 0 {
  44. return 0, io.ErrShortWrite
  45. }
  46. truncated := false
  47. if int64(len(p)) > l.N {
  48. p = p[0:l.N]
  49. truncated = true
  50. }
  51. n, err = l.W.Write(p)
  52. l.N -= int64(n)
  53. if err == nil && truncated {
  54. err = io.ErrShortWrite
  55. }
  56. return
  57. }