chan_reader.go 1002 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package io
  2. import (
  3. "io"
  4. "sync"
  5. "github.com/v2ray/v2ray-core/common/alloc"
  6. )
  7. type ChanReader struct {
  8. sync.Mutex
  9. stream Reader
  10. current *alloc.Buffer
  11. eof bool
  12. }
  13. func NewChanReader(stream Reader) *ChanReader {
  14. this := &ChanReader{
  15. stream: stream,
  16. }
  17. this.Fill()
  18. return this
  19. }
  20. // @Private
  21. func (this *ChanReader) Fill() {
  22. b, err := this.stream.Read()
  23. this.current = b
  24. if err != nil {
  25. this.eof = true
  26. this.current = nil
  27. }
  28. }
  29. func (this *ChanReader) Read(b []byte) (int, error) {
  30. if this.eof {
  31. return 0, io.EOF
  32. }
  33. this.Lock()
  34. defer this.Unlock()
  35. if this.current == nil {
  36. this.Fill()
  37. if this.eof {
  38. return 0, io.EOF
  39. }
  40. }
  41. nBytes := copy(b, this.current.Value)
  42. if nBytes == this.current.Len() {
  43. this.current.Release()
  44. this.current = nil
  45. } else {
  46. this.current.SliceFrom(nBytes)
  47. }
  48. return nBytes, nil
  49. }
  50. func (this *ChanReader) Release() {
  51. this.Lock()
  52. defer this.Unlock()
  53. this.eof = true
  54. this.current.Release()
  55. this.current = nil
  56. this.stream = nil
  57. }