2014-08-12 20:10:43 +04:00
|
|
|
package ioutils
|
|
|
|
|
|
|
|
import (
|
2015-03-30 00:17:23 +03:00
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/hex"
|
2014-08-12 20:10:43 +04:00
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type readCloserWrapper struct {
|
|
|
|
io.Reader
|
|
|
|
closer func() error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *readCloserWrapper) Close() error {
|
|
|
|
return r.closer()
|
|
|
|
}
|
|
|
|
|
2015-08-03 04:45:05 +03:00
|
|
|
// NewReadCloserWrapper returns a new io.ReadCloser.
|
2014-08-12 20:10:43 +04:00
|
|
|
func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
|
|
|
|
return &readCloserWrapper{
|
|
|
|
Reader: r,
|
|
|
|
closer: closer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-21 00:50:42 +04:00
|
|
|
type readerErrWrapper struct {
|
|
|
|
reader io.Reader
|
|
|
|
closer func()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *readerErrWrapper) Read(p []byte) (int, error) {
|
|
|
|
n, err := r.reader.Read(p)
|
|
|
|
if err != nil {
|
|
|
|
r.closer()
|
|
|
|
}
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
2015-08-03 04:45:05 +03:00
|
|
|
// NewReaderErrWrapper returns a new io.Reader.
|
2014-08-21 00:50:42 +04:00
|
|
|
func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader {
|
|
|
|
return &readerErrWrapper{
|
|
|
|
reader: r,
|
|
|
|
closer: closer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-08-03 04:45:05 +03:00
|
|
|
// HashData returns the sha256 sum of src.
|
2015-03-30 00:17:23 +03:00
|
|
|
func HashData(src io.Reader) (string, error) {
|
|
|
|
h := sha256.New()
|
|
|
|
if _, err := io.Copy(h, src); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
|
|
|
|
}
|
2015-05-17 12:07:48 +03:00
|
|
|
|
2015-08-03 04:45:05 +03:00
|
|
|
// OnEOFReader wraps a io.ReadCloser and a function
|
2015-08-08 01:24:18 +03:00
|
|
|
// the function will run at the end of file or close the file.
|
2015-05-17 12:07:48 +03:00
|
|
|
type OnEOFReader struct {
|
|
|
|
Rc io.ReadCloser
|
|
|
|
Fn func()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *OnEOFReader) Read(p []byte) (n int, err error) {
|
|
|
|
n, err = r.Rc.Read(p)
|
|
|
|
if err == io.EOF {
|
|
|
|
r.runFunc()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-08-03 04:45:05 +03:00
|
|
|
// Close closes the file and run the function.
|
2015-05-17 12:07:48 +03:00
|
|
|
func (r *OnEOFReader) Close() error {
|
|
|
|
err := r.Rc.Close()
|
|
|
|
r.runFunc()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *OnEOFReader) runFunc() {
|
|
|
|
if fn := r.Fn; fn != nil {
|
|
|
|
fn()
|
|
|
|
r.Fn = nil
|
|
|
|
}
|
|
|
|
}
|