...
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			// Optimization to flatten nested multiReaders (Issue 13558)
    14			if len(mr.readers) == 1 {
    15				if r, ok := mr.readers[0].(*multiReader); ok {
    16					mr.readers = r.readers
    17					continue
    18				}
    19			}
    20			n, err = mr.readers[0].Read(p)
    21			if n > 0 || err != EOF {
    22				if err == EOF {
    23					// Don't return EOF yet. There may be more bytes
    24					// in the remaining readers.
    25					err = nil
    26				}
    27				return
    28			}
    29			mr.readers = mr.readers[1:]
    30		}
    31		return 0, EOF
    32	}
    33	
    34	// MultiReader returns a Reader that's the logical concatenation of
    35	// the provided input readers. They're read sequentially. Once all
    36	// inputs have returned EOF, Read will return EOF.  If any of the readers
    37	// return a non-nil, non-EOF error, Read will return that error.
    38	func MultiReader(readers ...Reader) Reader {
    39		r := make([]Reader, len(readers))
    40		copy(r, readers)
    41		return &multiReader{r}
    42	}
    43	
    44	type multiWriter struct {
    45		writers []Writer
    46	}
    47	
    48	func (t *multiWriter) Write(p []byte) (n int, err error) {
    49		for _, w := range t.writers {
    50			n, err = w.Write(p)
    51			if err != nil {
    52				return
    53			}
    54			if n != len(p) {
    55				err = ErrShortWrite
    56				return
    57			}
    58		}
    59		return len(p), nil
    60	}
    61	
    62	var _ stringWriter = (*multiWriter)(nil)
    63	
    64	func (t *multiWriter) WriteString(s string) (n int, err error) {
    65		var p []byte // lazily initialized if/when needed
    66		for _, w := range t.writers {
    67			if sw, ok := w.(stringWriter); ok {
    68				n, err = sw.WriteString(s)
    69			} else {
    70				if p == nil {
    71					p = []byte(s)
    72				}
    73				n, err = w.Write(p)
    74			}
    75			if err != nil {
    76				return
    77			}
    78			if n != len(s) {
    79				err = ErrShortWrite
    80				return
    81			}
    82		}
    83		return len(s), nil
    84	}
    85	
    86	// MultiWriter creates a writer that duplicates its writes to all the
    87	// provided writers, similar to the Unix tee(1) command.
    88	func MultiWriter(writers ...Writer) Writer {
    89		w := make([]Writer, len(writers))
    90		copy(w, writers)
    91		return &multiWriter{w}
    92	}
    93	

View as plain text