chan_reader.go 765 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package http
  2. import (
  3. "io"
  4. "github.com/v2ray/v2ray-core/common/alloc"
  5. )
  6. type ChanReader struct {
  7. stream <-chan *alloc.Buffer
  8. current *alloc.Buffer
  9. eof bool
  10. }
  11. func NewChanReader(stream <-chan *alloc.Buffer) *ChanReader {
  12. this := &ChanReader{
  13. stream: stream,
  14. }
  15. this.fill()
  16. return this
  17. }
  18. func (this *ChanReader) fill() {
  19. b, open := <-this.stream
  20. this.current = b
  21. if !open {
  22. this.eof = true
  23. this.current = nil
  24. }
  25. }
  26. func (this *ChanReader) Read(b []byte) (int, error) {
  27. if this.current == nil {
  28. this.fill()
  29. if this.eof {
  30. return 0, io.EOF
  31. }
  32. }
  33. nBytes := copy(b, this.current.Value)
  34. if nBytes == this.current.Len() {
  35. this.current.Release()
  36. this.current = nil
  37. } else {
  38. this.current.SliceFrom(nBytes)
  39. }
  40. return nBytes, nil
  41. }