Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Provide callback progress hooks for long copies.
Signed-off-by: Erik Hollensbe <github@hollensbe.org>
- Loading branch information
Erik Hollensbe
committed
Jan 20, 2017
1 parent
256e419
commit 672557f
Showing
4 changed files
with
83 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package streamcopy | ||
|
||
import ( | ||
"bufio" | ||
"io" | ||
"time" | ||
) | ||
|
||
const megaByte = float64(1024 * 1024) | ||
const readerSize = 32768 | ||
|
||
// WithProgress implements io.Copy with a buffered reader, then measures | ||
// reports to the offsetFunc with the count processed at the interval. | ||
// If io.EOF is not returned then the error is returned. Otherwise, it is nil. | ||
func WithProgress(writer io.Writer, reader io.Reader, interval time.Duration, offsetFunc func(uint64)) error { | ||
rd := bufio.NewReaderSize(reader, readerSize) | ||
|
||
count := uint64(0) | ||
buf := make([]byte, readerSize) | ||
t := time.Now() | ||
for { | ||
rn, err := rd.Read(buf) | ||
count += uint64(rn) | ||
|
||
if err == io.EOF { | ||
if rn > 0 { | ||
goto write | ||
} else { | ||
return nil | ||
} | ||
} | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if interval > 0 && offsetFunc != nil { | ||
if time.Since(t) > interval { | ||
offsetFunc(count) | ||
t = time.Now() | ||
} | ||
} | ||
|
||
write: | ||
_, werr := writer.Write(buf[:rn]) | ||
if werr != nil { | ||
return werr | ||
} | ||
|
||
if err == io.EOF { | ||
return nil | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters