forked from charmbracelet/wishlist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiplex.go
47 lines (42 loc) · 855 Bytes
/
multiplex.go
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
43
44
45
46
47
package wishlist
import (
"bytes"
"io"
"log"
)
// multiplex keeps reading r and writing to 2 other readers, which are returned.
// it stops only when the done channel is notified.
func multiplex(r io.Reader, done <-chan bool) (io.Reader, io.Reader) {
var r1 bytes.Buffer
var r2 bytes.Buffer
rch := make(chan bool, 1)
w := io.MultiWriter(&r1, &r2)
go func() {
first := true
for {
select {
case <-done:
return
default:
if first {
first = false
rch <- true
}
buf := [256]byte{}
n, err := r.Read(buf[:])
if err != nil {
if err != io.EOF {
log.Println("multiplex read error:", err)
}
continue
}
if _, err := w.Write(buf[:n]); err != nil {
log.Println("multiplex write error:", err)
}
}
}
}()
// waits for the first read to start
<-rch
return &r1, &r2
}