]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/io/multi.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.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 import "os"
8
9 type multiReader struct {
10 readers []Reader
11 }
12
13 func (mr *multiReader) Read(p []byte) (n int, err os.Error) {
14 for len(mr.readers) > 0 {
15 n, err = mr.readers[0].Read(p)
16 if n > 0 || err != os.EOF {
17 if err == os.EOF {
18 // This shouldn't happen.
19 // Well-behaved Readers should never
20 // return non-zero bytes read with an
21 // EOF. But if so, we clean it.
22 err = nil
23 }
24 return
25 }
26 mr.readers = mr.readers[1:]
27 }
28 return 0, os.EOF
29 }
30
31 // MultiReader returns a Reader that's the logical concatenation of
32 // the provided input readers. They're read sequentially. Once all
33 // inputs are drained, Read will return os.EOF.
34 func MultiReader(readers ...Reader) Reader {
35 return &multiReader{readers}
36 }
37
38 type multiWriter struct {
39 writers []Writer
40 }
41
42 func (t *multiWriter) Write(p []byte) (n int, err os.Error) {
43 for _, w := range t.writers {
44 n, err = w.Write(p)
45 if err != nil {
46 return
47 }
48 if n != len(p) {
49 err = ErrShortWrite
50 return
51 }
52 }
53 return len(p), nil
54 }
55
56 // MultiWriter creates a writer that duplicates its writes to all the
57 // provided writers, similar to the Unix tee(1) command.
58 func MultiWriter(writers ...Writer) Writer {
59 return &multiWriter{writers}
60 }