Skip to content

Instantly share code, notes, and snippets.

@bokunodev
Last active December 3, 2020 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bokunodev/186486e184218d8b51f41869195c1569 to your computer and use it in GitHub Desktop.
Save bokunodev/186486e184218d8b51f41869195c1569 to your computer and use it in GitHub Desktop.
same as io.CopyBuffer from stdlib. except I add a cancellation channel and prioritize the allocated buffer over the io.ReadFrom and io.WriteTo interfaces.
package customio
import (
"errors"
"io"
)
var ErrCanceled = errors.New("operation canceled")
func CopyBuffer(dst io.Writer, src io.Reader, buf []byte, cancel chan struct{}) (written int64, err error) {
if buf == nil {
//allocated buffer has higer priority over io.ReadFrom and io.WriteTo interface.
if wt, ok := src.(io.WriterTo); ok {
return wt.WriteTo(dst)
}
if rt, ok := dst.(io.ReaderFrom); ok {
return rt.ReadFrom(src)
}
size := 32 * 1024
if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N {
if l.N < 1 {
size = 1
} else {
size = int(l.N)
}
}
buf = make([]byte, size)
}
loop:
for {
select {
case <-cancel:
err = ErrCanceled
break loop
default:
}
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment