chan_reader.go 802 B

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