github.com/bhojpur/cache@v0.0.4/pkg/ioutils/writers.go (about) 1 package ioutils 2 3 // Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved. 4 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 import "io" 24 25 // NopWriter represents a type which write operation is nop. 26 type NopWriter struct{} 27 28 func (*NopWriter) Write(buf []byte) (int, error) { 29 return len(buf), nil 30 } 31 32 type nopWriteCloser struct { 33 io.Writer 34 } 35 36 func (w *nopWriteCloser) Close() error { return nil } 37 38 // NopWriteCloser returns a nopWriteCloser. 39 func NopWriteCloser(w io.Writer) io.WriteCloser { 40 return &nopWriteCloser{w} 41 } 42 43 // NopFlusher represents a type which flush operation is nop. 44 type NopFlusher struct{} 45 46 // Flush is a nop operation. 47 func (f *NopFlusher) Flush() {} 48 49 type writeCloserWrapper struct { 50 io.Writer 51 closer func() error 52 } 53 54 func (r *writeCloserWrapper) Close() error { 55 return r.closer() 56 } 57 58 // NewWriteCloserWrapper returns a new io.WriteCloser. 59 func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { 60 return &writeCloserWrapper{ 61 Writer: r, 62 closer: closer, 63 } 64 } 65 66 // WriteCounter wraps a concrete io.Writer and hold a count of the number 67 // of bytes written to the writer during a "session". 68 // This can be convenient when write return is masked 69 // (e.g., json.Encoder.Encode()) 70 type WriteCounter struct { 71 Count int64 72 Writer io.Writer 73 } 74 75 // NewWriteCounter returns a new WriteCounter. 76 func NewWriteCounter(w io.Writer) *WriteCounter { 77 return &WriteCounter{ 78 Writer: w, 79 } 80 } 81 82 func (wc *WriteCounter) Write(p []byte) (count int, err error) { 83 count, err = wc.Writer.Write(p) 84 wc.Count += int64(count) 85 return 86 }