github.com/containerd/containerd/v2@v2.0.0-rc.2/pkg/ioutil/read_closer.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package ioutil 18 19 import "io" 20 21 // writeCloseInformer wraps a reader with a close function. 22 type wrapReadCloser struct { 23 reader *io.PipeReader 24 writer *io.PipeWriter 25 } 26 27 // NewWrapReadCloser creates a wrapReadCloser from a reader. 28 // NOTE(random-liu): To avoid goroutine leakage, the reader passed in 29 // must be eventually closed by the caller. 30 func NewWrapReadCloser(r io.Reader) io.ReadCloser { 31 pr, pw := io.Pipe() 32 go func() { 33 _, _ = io.Copy(pw, r) 34 pr.Close() 35 pw.Close() 36 }() 37 return &wrapReadCloser{ 38 reader: pr, 39 writer: pw, 40 } 41 } 42 43 // Read reads up to len(p) bytes into p. 44 func (w *wrapReadCloser) Read(p []byte) (int, error) { 45 n, err := w.reader.Read(p) 46 if err == io.ErrClosedPipe { 47 return n, io.EOF 48 } 49 return n, err 50 } 51 52 // Close closes read closer. 53 func (w *wrapReadCloser) Close() error { 54 w.reader.Close() 55 w.writer.Close() 56 return nil 57 }