Skip to content

Commit e671a55

Browse files
committed
io: document and test MultiWriter error behavior
MultiWriter(w1, w2) only writes to w2 if w1.Write succeeds. I did not know this, and it was not documented. Document and test. Change-Id: Idec2e8444d5a7aca0b95d07814a28daa454eb1d3 Reviewed-on: https://go-review.googlesource.com/78123 Run-TryBot: Russ Cox <[email protected]> Reviewed-by: Joe Tsai <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 894869e commit e671a55

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/io/multi.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@ func (t *multiWriter) WriteString(s string) (n int, err error) {
9595

9696
// MultiWriter creates a writer that duplicates its writes to all the
9797
// provided writers, similar to the Unix tee(1) command.
98+
//
99+
// Each write is written to each listed writer, one at a time.
100+
// If a listed writer returns an error, that overall write operation
101+
// stops and returns the error; it does not continue down the list.
98102
func MultiWriter(writers ...Writer) Writer {
99103
allWriters := make([]Writer, 0, len(writers))
100104
for _, w := range writers {

src/io/multi_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,21 @@ func TestMultiWriterSingleChainFlatten(t *testing.T) {
176176
}
177177
}
178178

179+
func TestMultiWriterError(t *testing.T) {
180+
f1 := writerFunc(func(p []byte) (int, error) {
181+
return len(p) / 2, ErrShortWrite
182+
})
183+
f2 := writerFunc(func(p []byte) (int, error) {
184+
t.Errorf("MultiWriter called f2.Write")
185+
return len(p), nil
186+
})
187+
w := MultiWriter(f1, f2)
188+
n, err := w.Write(make([]byte, 100))
189+
if n != 50 || err != ErrShortWrite {
190+
t.Errorf("Write = %d, %v, want 50, ErrShortWrite", n, err)
191+
}
192+
}
193+
179194
// Test that MultiReader copies the input slice and is insulated from future modification.
180195
func TestMultiReaderCopy(t *testing.T) {
181196
slice := []Reader{strings.NewReader("hello world")}

0 commit comments

Comments
 (0)