buffer.go 722 B

1234567891011121314151617181920212223242526272829303132333435
  1. package cmux
  2. import (
  3. "bytes"
  4. "io"
  5. )
  6. // bufferedReader is an optimized implementation of io.Reader that behaves like
  7. // ```
  8. // io.MultiReader(bytes.NewReader(buffer.Bytes()), io.TeeReader(source, buffer))
  9. // ```
  10. // without allocating.
  11. type bufferedReader struct {
  12. source io.Reader
  13. buffer *bytes.Buffer
  14. bufferRead int
  15. bufferSize int
  16. }
  17. func (s *bufferedReader) Read(p []byte) (int, error) {
  18. // Functionality of bytes.Reader.
  19. bn := copy(p, s.buffer.Bytes()[s.bufferRead:s.bufferSize])
  20. s.bufferRead += bn
  21. p = p[bn:]
  22. // Funtionality of io.TeeReader.
  23. sn, sErr := s.source.Read(p)
  24. if sn > 0 {
  25. if wn, wErr := s.buffer.Write(p[:sn]); wErr != nil {
  26. return bn + wn, wErr
  27. }
  28. }
  29. return bn + sn, sErr
  30. }