writers.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package ioutils
  2. import "io"
  3. // NopWriter represents a type which write operation is nop.
  4. type NopWriter struct{}
  5. func (*NopWriter) Write(buf []byte) (int, error) {
  6. return len(buf), nil
  7. }
  8. type nopWriteCloser struct {
  9. io.Writer
  10. }
  11. func (w *nopWriteCloser) Close() error { return nil }
  12. // NopWriteCloser returns a nopWriteCloser.
  13. func NopWriteCloser(w io.Writer) io.WriteCloser {
  14. return &nopWriteCloser{w}
  15. }
  16. // NopFlusher represents a type which flush operation is nop.
  17. type NopFlusher struct{}
  18. // Flush is a nop operation.
  19. func (f *NopFlusher) Flush() {}
  20. type writeCloserWrapper struct {
  21. io.Writer
  22. closer func() error
  23. }
  24. func (r *writeCloserWrapper) Close() error {
  25. return r.closer()
  26. }
  27. // NewWriteCloserWrapper returns a new io.WriteCloser.
  28. func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser {
  29. return &writeCloserWrapper{
  30. Writer: r,
  31. closer: closer,
  32. }
  33. }
  34. // WriteCounter wraps a concrete io.Writer and hold a count of the number
  35. // of bytes written to the writer during a "session".
  36. // This can be convenient when write return is masked
  37. // (e.g., json.Encoder.Encode())
  38. type WriteCounter struct {
  39. Count int64
  40. Writer io.Writer
  41. }
  42. // NewWriteCounter returns a new WriteCounter.
  43. func NewWriteCounter(w io.Writer) *WriteCounter {
  44. return &WriteCounter{
  45. Writer: w,
  46. }
  47. }
  48. func (wc *WriteCounter) Write(p []byte) (count int, err error) {
  49. count, err = wc.Writer.Write(p)
  50. wc.Count += int64(count)
  51. return
  52. }