File: mwc.go

package info (click to toggle)
golang-github-kisom-goutils 0.0~git20161101.0.858c9cb-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 384 kB
  • ctags: 331
  • sloc: makefile: 6
file content (42 lines) | stat: -rw-r--r-- 820 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Package mwc implements MultiWriteClosers.
package mwc

import "io"

type mwc struct {
	wcs []io.WriteCloser
}

// Write implements the Writer interface.
func (t *mwc) Write(p []byte) (n int, err error) {
	for _, w := range t.wcs {
		n, err = w.Write(p)
		if err != nil {
			return
		}
		if n != len(p) {
			err = io.ErrShortWrite
			return
		}
	}
	return len(p), nil
}

// Close implements the Closer interface.
func (t *mwc) Close() error {
	for _, wc := range t.wcs {
		err := wc.Close()
		if err != nil {
			return err
		}
	}
	return nil
}

// MultiWriteCloser creates a WriteCloser that duplicates its writes to
// all the provided writers, similar to the Unix tee(1) command.
func MultiWriteCloser(wc ...io.WriteCloser) io.WriteCloser {
	wcs := make([]io.WriteCloser, len(wc))
	copy(wcs, wc)
	return &mwc{wcs}
}