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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package io2
  2. import (
  3. "io"
  4. "gitlink.org.cn/cloudream/common/utils/math2"
  5. )
  6. type lengthStream struct {
  7. src io.ReadCloser
  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. s.src.Close()
  41. return nil
  42. }
  43. func Length(str io.ReadCloser, length int64) io.ReadCloser {
  44. return &lengthStream{
  45. src: str,
  46. length: length,
  47. }
  48. }
  49. func MustLength(str io.ReadCloser, length int64) io.ReadCloser {
  50. return &lengthStream{
  51. src: str,
  52. length: length,
  53. must: true,
  54. }
  55. }