copy.go 593 B

12345678910111213141516171819202122232425
  1. package generic
  2. import (
  3. "io"
  4. )
  5. const bufSize = 4096
  6. // Copy ... a memory-optimized io.Copy function
  7. func Copy(dst io.Writer, src io.Reader) (written int64, err error) {
  8. // If the reader has a WriteTo method, use it to do the copy.
  9. // Avoids an allocation and a copy.
  10. if wt, ok := src.(io.WriterTo); ok {
  11. return wt.WriteTo(dst)
  12. }
  13. // Similarly, if the writer has a ReadFrom method, use it to do the copy.
  14. if rt, ok := dst.(io.ReaderFrom); ok {
  15. return rt.ReadFrom(src)
  16. }
  17. // fallback to standard io.CopyBuffer
  18. buf := make([]byte, bufSize)
  19. return io.CopyBuffer(dst, src, buf)
  20. }