8 "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context"
11 type readCloserWrapper struct {
16 func (r *readCloserWrapper) Close() error {
20 // NewReadCloserWrapper returns a new io.ReadCloser.
21 func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
22 return &readCloserWrapper{
28 type readerErrWrapper struct {
33 func (r *readerErrWrapper) Read(p []byte) (int, error) {
34 n, err := r.reader.Read(p)
41 // NewReaderErrWrapper returns a new io.Reader.
42 func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader {
43 return &readerErrWrapper{
49 // HashData returns the sha256 sum of src.
50 func HashData(src io.Reader) (string, error) {
52 if _, err := io.Copy(h, src); err != nil {
55 return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil
58 // OnEOFReader wraps a io.ReadCloser and a function
59 // the function will run at the end of file or close the file.
60 type OnEOFReader struct {
65 func (r *OnEOFReader) Read(p []byte) (n int, err error) {
73 // Close closes the file and run the function.
74 func (r *OnEOFReader) Close() error {
80 func (r *OnEOFReader) runFunc() {
81 if fn := r.Fn; fn != nil {
87 // cancelReadCloser wraps an io.ReadCloser with a context for cancelling read
89 type cancelReadCloser struct {
91 pR *io.PipeReader // Stream to read from
95 // NewCancelReadCloser creates a wrapper that closes the ReadCloser when the
96 // context is cancelled. The returned io.ReadCloser must be closed when it is
98 func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser {
101 // Create a context used to signal when the pipe is closed
102 doneCtx, cancel := context.WithCancel(context.Background())
104 p := &cancelReadCloser{
111 _, err := io.Copy(pW, in)
114 // If the context was closed, p.closeWithError
115 // was already called. Calling it again would
116 // change the error that Read returns.
118 p.closeWithError(err)
126 p.closeWithError(ctx.Err())
127 case <-doneCtx.Done():
136 // Read wraps the Read method of the pipe that provides data from the wrapped
138 func (p *cancelReadCloser) Read(buf []byte) (n int, err error) {
139 return p.pR.Read(buf)
142 // closeWithError closes the wrapper and its underlying reader. It will
143 // cause future calls to Read to return err.
144 func (p *cancelReadCloser) closeWithError(err error) {
145 p.pW.CloseWithError(err)
149 // Close closes the wrapper its underlying reader. It will cause
150 // future calls to Read to return io.EOF.
151 func (p *cancelReadCloser) Close() error {
152 p.closeWithError(io.EOF)