Imported Upstream version 4.7.3
[platform/upstream/gcc48.git] / libgo / go / io / multi.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package io
6
7 type multiReader struct {
8         readers []Reader
9 }
10
11 func (mr *multiReader) Read(p []byte) (n int, err error) {
12         for len(mr.readers) > 0 {
13                 n, err = mr.readers[0].Read(p)
14                 if n > 0 || err != EOF {
15                         if err == EOF {
16                                 // Don't return EOF yet. There may be more bytes
17                                 // in the remaining readers.
18                                 err = nil
19                         }
20                         return
21                 }
22                 mr.readers = mr.readers[1:]
23         }
24         return 0, EOF
25 }
26
27 // MultiReader returns a Reader that's the logical concatenation of
28 // the provided input readers.  They're read sequentially.  Once all
29 // inputs are drained, Read will return EOF.
30 func MultiReader(readers ...Reader) Reader {
31         return &multiReader{readers}
32 }
33
34 type multiWriter struct {
35         writers []Writer
36 }
37
38 func (t *multiWriter) Write(p []byte) (n int, err error) {
39         for _, w := range t.writers {
40                 n, err = w.Write(p)
41                 if err != nil {
42                         return
43                 }
44                 if n != len(p) {
45                         err = ErrShortWrite
46                         return
47                 }
48         }
49         return len(p), nil
50 }
51
52 // MultiWriter creates a writer that duplicates its writes to all the
53 // provided writers, similar to the Unix tee(1) command.
54 func MultiWriter(writers ...Writer) Writer {
55         return &multiWriter{writers}
56 }