github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/io/multi.go (about)

     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 have returned EOF, Read will return EOF.  If any of the readers
    30  // return a non-nil, non-EOF error, Read will return that error.
    31  func MultiReader(readers ...Reader) Reader {
    32  	r := make([]Reader, len(readers))
    33  	copy(r, readers)
    34  	return &multiReader{r}
    35  }
    36  
    37  type multiWriter struct {
    38  	writers []Writer
    39  }
    40  
    41  func (t *multiWriter) Write(p []byte) (n int, err error) {
    42  	for _, w := range t.writers {
    43  		n, err = w.Write(p)
    44  		if err != nil {
    45  			return
    46  		}
    47  		if n != len(p) {
    48  			err = ErrShortWrite
    49  			return
    50  		}
    51  	}
    52  	return len(p), nil
    53  }
    54  
    55  var _ stringWriter = (*multiWriter)(nil)
    56  
    57  func (t *multiWriter) WriteString(s string) (n int, err error) {
    58  	var p []byte // lazily initialized if/when needed
    59  	for _, w := range t.writers {
    60  		if sw, ok := w.(stringWriter); ok {
    61  			n, err = sw.WriteString(s)
    62  		} else {
    63  			if p == nil {
    64  				p = []byte(s)
    65  			}
    66  			n, err = w.Write(p)
    67  		}
    68  		if err != nil {
    69  			return
    70  		}
    71  		if n != len(s) {
    72  			err = ErrShortWrite
    73  			return
    74  		}
    75  	}
    76  	return len(s), nil
    77  }
    78  
    79  // MultiWriter creates a writer that duplicates its writes to all the
    80  // provided writers, similar to the Unix tee(1) command.
    81  func MultiWriter(writers ...Writer) Writer {
    82  	w := make([]Writer, len(writers))
    83  	copy(w, writers)
    84  	return &multiWriter{w}
    85  }