readcloser.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 ioutil
  15. import (
  16. "fmt"
  17. "io"
  18. )
  19. // ReaderAndCloser implements io.ReadCloser interface by combining
  20. // reader and closer together.
  21. type ReaderAndCloser struct {
  22. io.Reader
  23. io.Closer
  24. }
  25. var (
  26. ErrShortRead = fmt.Errorf("ioutil: short read")
  27. ErrExpectEOF = fmt.Errorf("ioutil: expect EOF")
  28. )
  29. // NewExactReadCloser returns a ReadCloser that returns errors if the underlying
  30. // reader does not read back exactly the requested number of bytes.
  31. func NewExactReadCloser(rc io.ReadCloser, totalBytes int64) io.ReadCloser {
  32. return &exactReadCloser{rc: rc, totalBytes: totalBytes}
  33. }
  34. type exactReadCloser struct {
  35. rc io.ReadCloser
  36. br int64
  37. totalBytes int64
  38. }
  39. func (e *exactReadCloser) Read(p []byte) (int, error) {
  40. n, err := e.rc.Read(p)
  41. e.br += int64(n)
  42. if e.br > e.totalBytes {
  43. return 0, ErrExpectEOF
  44. }
  45. if e.br < e.totalBytes && n == 0 {
  46. return 0, ErrShortRead
  47. }
  48. return n, err
  49. }
  50. func (e *exactReadCloser) Close() error {
  51. if err := e.rc.Close(); err != nil {
  52. return err
  53. }
  54. if e.br < e.totalBytes {
  55. return ErrShortRead
  56. }
  57. return nil
  58. }