The Go Programming Language

Source file src/pkg/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					// Don't return EOF yet. There may be more bytes
    19					// in the remaining readers.
    20					err = nil
    21				}
    22				return
    23			}
    24			mr.readers = mr.readers[1:]
    25		}
    26		return 0, os.EOF
    27	}
    28	
    29	// MultiReader returns a Reader that's the logical concatenation of
    30	// the provided input readers.  They're read sequentially.  Once all
    31	// inputs are drained, Read will return os.EOF.
    32	func MultiReader(readers ...Reader) Reader {
    33		return &multiReader{readers}
    34	}
    35	
    36	type multiWriter struct {
    37		writers []Writer
    38	}
    39	
    40	func (t *multiWriter) Write(p []byte) (n int, err os.Error) {
    41		for _, w := range t.writers {
    42			n, err = w.Write(p)
    43			if err != nil {
    44				return
    45			}
    46			if n != len(p) {
    47				err = ErrShortWrite
    48				return
    49			}
    50		}
    51		return len(p), nil
    52	}
    53	
    54	// MultiWriter creates a writer that duplicates its writes to all the
    55	// provided writers, similar to the Unix tee(1) command.
    56	func MultiWriter(writers ...Writer) Writer {
    57		return &multiWriter{writers}
    58	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.