chan_reader.go 951 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, err := this.current.Read(b)
  42. if this.current.IsEmpty() {
  43. this.current.Release()
  44. this.current = nil
  45. }
  46. return nBytes, err
  47. }
  48. func (this *ChanReader) Release() {
  49. this.Lock()
  50. defer this.Unlock()
  51. this.eof = true
  52. this.current.Release()
  53. this.current = nil
  54. this.stream = nil
  55. }