tee.go 841 B

1234567891011121314151617181920212223242526272829303132333435
  1. package iox
  2. import "io"
  3. // LimitTeeReader returns a Reader that writes up to n bytes to w what it reads from r.
  4. // First n bytes reads from r performed through it are matched with
  5. // corresponding writes to w. There is no internal buffering -
  6. // the write must complete before the first n bytes read completes.
  7. // Any error encountered while writing is reported as a read error.
  8. func LimitTeeReader(r io.Reader, w io.Writer, n int64) io.Reader {
  9. return &limitTeeReader{r, w, n}
  10. }
  11. type limitTeeReader struct {
  12. r io.Reader
  13. w io.Writer
  14. n int64 // limit bytes remaining
  15. }
  16. func (t *limitTeeReader) Read(p []byte) (n int, err error) {
  17. n, err = t.r.Read(p)
  18. if n > 0 && t.n > 0 {
  19. limit := int64(n)
  20. if limit > t.n {
  21. limit = t.n
  22. }
  23. if n, err := t.w.Write(p[:limit]); err != nil {
  24. return n, err
  25. }
  26. t.n -= limit
  27. }
  28. return
  29. }