github.com/toplink-cn/moby@v0.0.0-20240305205811-460b4aebdf81/pkg/ioutils/writers.go (about) 1 package ioutils // import "github.com/docker/docker/pkg/ioutils" 2 3 import ( 4 "io" 5 "sync/atomic" 6 ) 7 8 // NopWriter represents a type which write operation is nop. 9 type NopWriter struct{} 10 11 func (*NopWriter) Write(buf []byte) (int, error) { 12 return len(buf), nil 13 } 14 15 type nopWriteCloser struct { 16 io.Writer 17 } 18 19 func (w *nopWriteCloser) Close() error { return nil } 20 21 // NopWriteCloser returns a nopWriteCloser. 22 func NopWriteCloser(w io.Writer) io.WriteCloser { 23 return &nopWriteCloser{w} 24 } 25 26 // NopFlusher represents a type which flush operation is nop. 27 type NopFlusher struct{} 28 29 // Flush is a nop operation. 30 func (f *NopFlusher) Flush() {} 31 32 type writeCloserWrapper struct { 33 io.Writer 34 closer func() error 35 closed atomic.Bool 36 } 37 38 func (r *writeCloserWrapper) Close() error { 39 if !r.closed.CompareAndSwap(false, true) { 40 subsequentCloseWarn("WriteCloserWrapper") 41 return nil 42 } 43 return r.closer() 44 } 45 46 // NewWriteCloserWrapper returns a new io.WriteCloser. 47 func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { 48 return &writeCloserWrapper{ 49 Writer: r, 50 closer: closer, 51 } 52 } 53 54 // WriteCounter wraps a concrete io.Writer and hold a count of the number 55 // of bytes written to the writer during a "session". 56 // This can be convenient when write return is masked 57 // (e.g., json.Encoder.Encode()) 58 type WriteCounter struct { 59 Count int64 60 Writer io.Writer 61 } 62 63 // NewWriteCounter returns a new WriteCounter. 64 func NewWriteCounter(w io.Writer) *WriteCounter { 65 return &WriteCounter{ 66 Writer: w, 67 } 68 } 69 70 func (wc *WriteCounter) Write(p []byte) (count int, err error) { 71 count, err = wc.Writer.Write(p) 72 wc.Count += int64(count) 73 return 74 }