File size: 927 Bytes
7107f0b |
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 |
package chanio
import (
"io"
"sync/atomic"
)
type ChanIO struct {
cl atomic.Bool
c chan []byte
buf []byte
}
func New() *ChanIO {
return &ChanIO{
cl: atomic.Bool{},
c: make(chan []byte),
buf: make([]byte, 0),
}
}
func (c *ChanIO) Read(p []byte) (int, error) {
if c.cl.Load() {
if len(c.buf) == 0 {
return 0, io.EOF
}
n := copy(p, c.buf)
if len(c.buf) > n {
c.buf = c.buf[n:]
} else {
c.buf = make([]byte, 0)
}
return n, nil
}
for len(c.buf) < len(p) && !c.cl.Load() {
c.buf = append(c.buf, <-c.c...)
}
n := copy(p, c.buf)
if len(c.buf) > n {
c.buf = c.buf[n:]
} else {
c.buf = make([]byte, 0)
}
return n, nil
}
func (c *ChanIO) Write(p []byte) (int, error) {
if c.cl.Load() {
return 0, io.ErrClosedPipe
}
c.c <- p
return len(p), nil
}
func (c *ChanIO) Close() error {
if c.cl.Load() {
return io.ErrClosedPipe
}
c.cl.Store(true)
close(c.c)
return nil
}
|