Created
July 15, 2021 07:38
-
-
Save cavaliercoder/6624d3559aeab501438ff222122d19d3 to your computer and use it in GitHub Desktop.
Go aggregated writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package agg_writer | |
import ( | |
"io" | |
) | |
// AggregatedWriter tracks the cumulative number of bytes written and any error | |
// that occurs across multiple writes to the underlying writer. If an error is | |
// returned by the underlying writer, all subsequent calls will return the same | |
// error and the write is dropped. | |
// | |
// This is useful for performing multiple successive writes, keeping a tally of | |
// total bytes written and defering error checking until the end of all writes. | |
type AggregatedWriter struct { | |
w io.Writer | |
n int64 | |
err error | |
} | |
func NewAggregatedWriter(w io.Writer) *AggregatedWriter { | |
if ag, ok := w.(*AggregatedWriter); ok { | |
return ag | |
} | |
return &AggregatedWriter{w: w} | |
} | |
func (w *AggregatedWriter) Write(p []byte) (n int, err error) { | |
if w.err != nil { | |
return 0, w.err | |
} | |
n, err = w.w.Write(p) | |
w.n += int64(n) | |
w.err = err | |
return | |
} | |
func (w *AggregatedWriter) N() int64 { return w.n } | |
func (w *AggregatedWriter) Err() error { return w.err } | |
func (w *AggregatedWriter) Result() (n int64, err error) { return w.n, w.err } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment