feature: added io.Copy progress listener

master
amorozov 2024-06-29 00:33:08 +03:00
parent f043233031
commit b6c6436cee
1 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,37 @@
package progress
import "io"
type WriteProgressCallback func(uint64, uint64)
type WriteProgressListener struct {
BytesWritten uint64
ProgressCallback WriteProgressCallback
}
func (self *WriteProgressListener) Write(p []byte) (int, error) {
n := len(p)
newTotal := self.BytesWritten + uint64(n)
if self.ProgressCallback != nil {
self.ProgressCallback(self.BytesWritten, newTotal)
}
self.BytesWritten = newTotal
return n, nil
}
func (self *WriteProgressListener) WrapReader(reader io.Reader) io.Reader {
return io.TeeReader(reader, self)
}
func NewProgressListener(callback WriteProgressCallback) *WriteProgressListener {
return &WriteProgressListener{
BytesWritten: 0,
ProgressCallback: callback,
}
}
func WrapReader(reader io.Reader, callback WriteProgressCallback) io.Reader {
return NewProgressListener(callback).WrapReader(reader)
}