forked from Shopify/toxiproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio_chan.go
More file actions
76 lines (67 loc) · 1.54 KB
/
io_chan.go
File metadata and controls
76 lines (67 loc) · 1.54 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"io"
"time"
)
// Stores a slice of bytes with its receive timestmap
type StreamChunk struct {
data []byte
timestamp time.Time
}
// Implements the io.WriteCloser interface for a chan []byte
type ChanWriter struct {
output chan<- *StreamChunk
}
func NewChanWriter(output chan<- *StreamChunk) *ChanWriter {
return &ChanWriter{output}
}
func (c *ChanWriter) Write(buf []byte) (int, error) {
packet := &StreamChunk{make([]byte, len(buf)), time.Now()}
copy(packet.data, buf) // Make a copy before sending it to the channel
c.output <- packet
return len(buf), nil
}
func (c *ChanWriter) Close() error {
close(c.output)
return nil
}
// Implements the io.Reader interface for a chan []byte
type ChanReader struct {
input <-chan *StreamChunk
buffer []byte
}
func NewChanReader(input <-chan *StreamChunk) *ChanReader {
return &ChanReader{input, []byte{}}
}
func (c *ChanReader) Read(out []byte) (int, error) {
if c.buffer == nil {
return 0, io.EOF
}
n := copy(out, c.buffer)
c.buffer = c.buffer[n:]
if len(out) <= len(c.buffer) {
return n, nil
} else if n > 0 {
// We have some data to return, so make the channel read optional
select {
case p := <-c.input:
if p == nil { // Stream was closed
c.buffer = nil
return n, io.EOF
}
n2 := copy(out[n:], p.data)
c.buffer = p.data[n2:]
return n + n2, nil
default:
return n, nil
}
}
p := <-c.input
if p == nil { // Stream was closed
c.buffer = nil
return 0, io.EOF
}
n2 := copy(out[n:], p.data)
c.buffer = p.data[n2:]
return n + n2, nil
}