hook-reader.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Minio Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2017 Minio, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package minio
  18. import "io"
  19. // hookReader hooks additional reader in the source stream. It is
  20. // useful for making progress bars. Second reader is appropriately
  21. // notified about the exact number of bytes read from the primary
  22. // source on each Read operation.
  23. type hookReader struct {
  24. source io.Reader
  25. hook io.Reader
  26. }
  27. // Seek implements io.Seeker. Seeks source first, and if necessary
  28. // seeks hook if Seek method is appropriately found.
  29. func (hr *hookReader) Seek(offset int64, whence int) (n int64, err error) {
  30. // Verify for source has embedded Seeker, use it.
  31. sourceSeeker, ok := hr.source.(io.Seeker)
  32. if ok {
  33. return sourceSeeker.Seek(offset, whence)
  34. }
  35. // Verify if hook has embedded Seeker, use it.
  36. hookSeeker, ok := hr.hook.(io.Seeker)
  37. if ok {
  38. return hookSeeker.Seek(offset, whence)
  39. }
  40. return n, nil
  41. }
  42. // Read implements io.Reader. Always reads from the source, the return
  43. // value 'n' number of bytes are reported through the hook. Returns
  44. // error for all non io.EOF conditions.
  45. func (hr *hookReader) Read(b []byte) (n int, err error) {
  46. n, err = hr.source.Read(b)
  47. if err != nil && err != io.EOF {
  48. return n, err
  49. }
  50. // Progress the hook with the total read bytes from the source.
  51. if _, herr := hr.hook.Read(b[:n]); herr != nil {
  52. if herr != io.EOF {
  53. return n, herr
  54. }
  55. }
  56. return n, err
  57. }
  58. // newHook returns a io.ReadSeeker which implements hookReader that
  59. // reports the data read from the source to the hook.
  60. func newHook(source, hook io.Reader) io.Reader {
  61. if hook == nil {
  62. return source
  63. }
  64. return &hookReader{source, hook}
  65. }