rw.go 1006 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package countconn
  2. import (
  3. "io"
  4. "sync/atomic"
  5. )
  6. // Reader counts the bytes read through it.
  7. type Reader struct {
  8. r io.Reader
  9. n int64
  10. }
  11. // NewReader makes a new Reader that counts the bytes
  12. // read through it.
  13. func NewReader(r io.Reader) *Reader {
  14. return &Reader{
  15. r: r,
  16. }
  17. }
  18. func (r *Reader) Read(p []byte) (n int, err error) {
  19. n, err = r.r.Read(p)
  20. atomic.AddInt64(&r.n, int64(n))
  21. return
  22. }
  23. // N gets the number of bytes that have been read
  24. // so far.
  25. func (r *Reader) N() int64 {
  26. return atomic.LoadInt64(&r.n)
  27. }
  28. // Writer counts the bytes read through it.
  29. type Writer struct {
  30. w io.Writer
  31. n int64
  32. }
  33. // NewWriter makes a new Writer that counts the bytes
  34. // read through it.
  35. func NewWriter(w io.Writer) *Writer {
  36. return &Writer{
  37. w: w,
  38. }
  39. }
  40. func (w *Writer) Write(p []byte) (n int, err error) {
  41. n, err = w.w.Write(p)
  42. atomic.AddInt64(&w.n, int64(n))
  43. return
  44. }
  45. // N gets the number of bytes that have been written
  46. // so far.
  47. func (w *Writer) N() int64 {
  48. return atomic.LoadInt64(&w.n)
  49. }