github.com/AbhinandanKurakure/podman/v3@v3.4.10/pkg/channel/writer.go (about) 1 package channel 2 3 import ( 4 "io" 5 "sync" 6 7 "github.com/pkg/errors" 8 ) 9 10 // WriteCloser is an io.WriteCloser that that proxies Write() calls to a channel 11 // The []byte buffer of the Write() is queued on the channel as one message. 12 type WriteCloser interface { 13 io.WriteCloser 14 Chan() <-chan []byte 15 } 16 17 type writeCloser struct { 18 ch chan []byte 19 mux sync.Mutex 20 } 21 22 // NewWriter initializes a new channel writer 23 func NewWriter(c chan []byte) WriteCloser { 24 return &writeCloser{ 25 ch: c, 26 } 27 } 28 29 // Chan returns the R/O channel behind WriteCloser 30 func (w *writeCloser) Chan() <-chan []byte { 31 return w.ch 32 } 33 34 // Write method for WriteCloser 35 func (w *writeCloser) Write(b []byte) (bLen int, err error) { 36 if w == nil { 37 return 0, errors.New("use channel.NewWriter() to initialize a WriteCloser") 38 } 39 40 w.mux.Lock() 41 defer w.mux.Unlock() 42 43 if w.ch == nil { 44 return 0, errors.New("the channel is closed for Write") 45 } 46 47 buf := make([]byte, len(b)) 48 copy(buf, b) 49 w.ch <- buf 50 51 return len(b), nil 52 } 53 54 // Close method for WriteCloser 55 func (w *writeCloser) Close() error { 56 w.mux.Lock() 57 defer w.mux.Unlock() 58 59 close(w.ch) 60 w.ch = nil 61 return nil 62 }