You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

length.go 1.1 kB

1 year ago
1 year ago
1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package io2
  2. import (
  3. "io"
  4. "gitlink.org.cn/cloudream/common/utils/math2"
  5. )
  6. type lengthStream struct {
  7. src io.Reader
  8. length int64
  9. readLength int64
  10. must bool
  11. err error
  12. }
  13. func (s *lengthStream) Read(buf []byte) (int, error) {
  14. if s.err != nil {
  15. return 0, s.err
  16. }
  17. bufLen := math2.Min(s.length-s.readLength, int64(len(buf)))
  18. rd, err := s.src.Read(buf[:bufLen])
  19. if err == nil {
  20. s.readLength += int64(rd)
  21. if s.readLength == s.length {
  22. s.err = io.EOF
  23. }
  24. return rd, nil
  25. }
  26. if err == io.EOF {
  27. s.readLength += int64(rd)
  28. if s.readLength < s.length && s.must {
  29. s.err = io.ErrUnexpectedEOF
  30. return rd, io.ErrUnexpectedEOF
  31. }
  32. s.err = io.EOF
  33. return rd, io.EOF
  34. }
  35. s.err = err
  36. return 0, err
  37. }
  38. func (s *lengthStream) Close() error {
  39. s.err = io.ErrClosedPipe
  40. return nil
  41. }
  42. func Length(str io.Reader, length int64) io.ReadCloser {
  43. return &lengthStream{
  44. src: str,
  45. length: length,
  46. }
  47. }
  48. func MustLength(str io.Reader, length int64) io.ReadCloser {
  49. return &lengthStream{
  50. src: str,
  51. length: length,
  52. must: true,
  53. }
  54. }