2014-08-12 16:10:43 +00:00
|
|
|
package ioutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
type readCloserWrapper struct {
|
|
|
|
io.Reader
|
|
|
|
closer func() error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *readCloserWrapper) Close() error {
|
|
|
|
return r.closer()
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
|
|
|
|
return &readCloserWrapper{
|
|
|
|
Reader: r,
|
|
|
|
closer: closer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type bufReader struct {
|
|
|
|
sync.Mutex
|
2014-08-19 16:58:07 +00:00
|
|
|
buf *bytes.Buffer
|
|
|
|
reader io.Reader
|
|
|
|
err error
|
|
|
|
wait sync.Cond
|
|
|
|
drainBuf []byte
|
2014-08-12 16:10:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewBufReader(r io.Reader) *bufReader {
|
|
|
|
reader := &bufReader{
|
2014-08-19 16:58:07 +00:00
|
|
|
buf: &bytes.Buffer{},
|
|
|
|
drainBuf: make([]byte, 1024),
|
|
|
|
reader: r,
|
|
|
|
}
|
|
|
|
reader.wait.L = &reader.Mutex
|
|
|
|
go reader.drain()
|
|
|
|
return reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBufReaderWithDrainbufAndBuffer(r io.Reader, drainBuffer []byte, buffer *bytes.Buffer) *bufReader {
|
|
|
|
reader := &bufReader{
|
|
|
|
buf: buffer,
|
|
|
|
drainBuf: drainBuffer,
|
|
|
|
reader: r,
|
2014-08-12 16:10:43 +00:00
|
|
|
}
|
|
|
|
reader.wait.L = &reader.Mutex
|
|
|
|
go reader.drain()
|
|
|
|
return reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *bufReader) drain() {
|
|
|
|
for {
|
2014-08-19 16:58:07 +00:00
|
|
|
n, err := r.reader.Read(r.drainBuf)
|
2014-08-12 16:10:43 +00:00
|
|
|
r.Lock()
|
|
|
|
if err != nil {
|
|
|
|
r.err = err
|
|
|
|
} else {
|
2014-08-19 16:58:07 +00:00
|
|
|
r.buf.Write(r.drainBuf[0:n])
|
2014-08-12 16:10:43 +00:00
|
|
|
}
|
|
|
|
r.wait.Signal()
|
|
|
|
r.Unlock()
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *bufReader) Read(p []byte) (n int, err error) {
|
|
|
|
r.Lock()
|
|
|
|
defer r.Unlock()
|
|
|
|
for {
|
|
|
|
n, err = r.buf.Read(p)
|
|
|
|
if n > 0 {
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
if r.err != nil {
|
|
|
|
return 0, r.err
|
|
|
|
}
|
|
|
|
r.wait.Wait()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *bufReader) Close() error {
|
|
|
|
closer, ok := r.reader.(io.ReadCloser)
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return closer.Close()
|
|
|
|
}
|