github.com/minio/minio@v0.0.0-20240328213742-3f72439b8a27/internal/ioutil/wait_pipe.go (about) 1 // Copyright (c) 2015-2021 MinIO, Inc. 2 // 3 // This file is part of MinIO Object Storage stack 4 // 5 // This program is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Affero General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Affero General Public License for more details. 14 // 15 // You should have received a copy of the GNU Affero General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 package ioutil 19 20 import ( 21 "io" 22 "sync" 23 ) 24 25 // PipeWriter is similar to io.PipeWriter with wait group 26 type PipeWriter struct { 27 *io.PipeWriter 28 once sync.Once 29 done func() 30 } 31 32 // CloseWithError close with supplied error the writer end. 33 func (w *PipeWriter) CloseWithError(err error) error { 34 err = w.PipeWriter.CloseWithError(err) 35 w.once.Do(func() { 36 w.done() 37 }) 38 return err 39 } 40 41 // PipeReader is similar to io.PipeReader with wait group 42 type PipeReader struct { 43 *io.PipeReader 44 wait func() 45 } 46 47 // CloseWithError close with supplied error the reader end 48 func (r *PipeReader) CloseWithError(err error) error { 49 err = r.PipeReader.CloseWithError(err) 50 r.wait() 51 return err 52 } 53 54 // WaitPipe implements wait-group backend io.Pipe to provide 55 // synchronization between read() end with write() end. 56 func WaitPipe() (*PipeReader, *PipeWriter) { 57 r, w := io.Pipe() 58 var wg sync.WaitGroup 59 wg.Add(1) 60 return &PipeReader{ 61 PipeReader: r, 62 wait: wg.Wait, 63 }, &PipeWriter{ 64 PipeWriter: w, 65 done: wg.Done, 66 } 67 }