Source file
src/io/multi.go
1
2
3
4
5 package io
6
7 type eofReader struct{}
8
9 func (eofReader) Read([]byte) (int, error) {
10 return 0, EOF
11 }
12
13 type multiReader struct {
14 readers []Reader
15 }
16
17 func (mr *multiReader) Read(p []byte) (n int, err error) {
18 for len(mr.readers) > 0 {
19
20 if len(mr.readers) == 1 {
21 if r, ok := mr.readers[0].(*multiReader); ok {
22 mr.readers = r.readers
23 continue
24 }
25 }
26 n, err = mr.readers[0].Read(p)
27 if err == EOF {
28
29
30 mr.readers[0] = eofReader{}
31 mr.readers = mr.readers[1:]
32 }
33 if n > 0 || err != EOF {
34 if err == EOF && len(mr.readers) > 0 {
35
36 err = nil
37 }
38 return
39 }
40 }
41 return 0, EOF
42 }
43
44 func (mr *multiReader) WriteTo(w Writer) (sum int64, err error) {
45 return mr.writeToWithBuffer(w, make([]byte, 1024*32))
46 }
47
48 func (mr *multiReader) writeToWithBuffer(w Writer, buf []byte) (sum int64, err error) {
49 for i, r := range mr.readers {
50 var n int64
51 if subMr, ok := r.(*multiReader); ok {
52 n, err = subMr.writeToWithBuffer(w, buf)
53 } else {
54 n, err = copyBuffer(w, r, buf)
55 }
56 sum += n
57 if err != nil {
58 mr.readers = mr.readers[i:]
59 return sum, err
60 }
61 mr.readers[i] = nil
62 }
63 mr.readers = nil
64 return sum, nil
65 }
66
67 var _ WriterTo = (*multiReader)(nil)
68
69
70
71
72
73 func MultiReader(readers ...Reader) Reader {
74 r := make([]Reader, len(readers))
75 copy(r, readers)
76 return &multiReader{r}
77 }
78
79 type multiWriter struct {
80 writers []Writer
81 }
82
83 func (t *multiWriter) Write(p []byte) (n int, err error) {
84 for _, w := range t.writers {
85 n, err = w.Write(p)
86 if err != nil {
87 return
88 }
89 if n != len(p) {
90 err = ErrShortWrite
91 return
92 }
93 }
94 return len(p), nil
95 }
96
97 var _ StringWriter = (*multiWriter)(nil)
98
99 func (t *multiWriter) WriteString(s string) (n int, err error) {
100 var p []byte
101 for _, w := range t.writers {
102 if sw, ok := w.(StringWriter); ok {
103 n, err = sw.WriteString(s)
104 } else {
105 if p == nil {
106 p = []byte(s)
107 }
108 n, err = w.Write(p)
109 }
110 if err != nil {
111 return
112 }
113 if n != len(s) {
114 err = ErrShortWrite
115 return
116 }
117 }
118 return len(s), nil
119 }
120
121
122
123
124
125
126
127 func MultiWriter(writers ...Writer) Writer {
128 allWriters := make([]Writer, 0, len(writers))
129 for _, w := range writers {
130 if mw, ok := w.(*multiWriter); ok {
131 allWriters = append(allWriters, mw.writers...)
132 } else {
133 allWriters = append(allWriters, w)
134 }
135 }
136 return &multiWriter{allWriters}
137 }
138
View as plain text