...
Run Format

Source file src/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 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	// MultiWriter creates a writer that duplicates its writes to all the
    56	// provided writers, similar to the Unix tee(1) command.
    57	func MultiWriter(writers ...Writer) Writer {
    58		w := make([]Writer, len(writers))
    59		copy(w, writers)
    60		return &multiWriter{w}
    61	}
    62	

View as plain text