handle nil onData

pull/298/merge
Darien Raymond 8 years ago
parent 6f3362fc4c
commit 3821ee21fc
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169

@ -53,6 +53,22 @@ type copyHandler struct {
onWriteError func(error) error onWriteError func(error) error
} }
func (h *copyHandler) readFrom(reader Reader) (MultiBuffer, error) {
mb, err := reader.Read()
if err != nil && h.onReadError != nil {
err = h.onReadError(err)
}
return mb, err
}
func (h *copyHandler) writeTo(writer Writer, mb MultiBuffer) error {
err := writer.Write(mb)
if err != nil && h.onWriteError != nil {
err = h.onWriteError(err)
}
return err
}
type CopyOption func(*copyHandler) type CopyOption func(*copyHandler)
func IgnoreReaderError() CopyOption { func IgnoreReaderError() CopyOption {
@ -79,37 +95,35 @@ func UpdateActivity(timer signal.ActivityTimer) CopyOption {
} }
} }
func copyInternal(reader Reader, writer Writer, handler copyHandler) error { func copyInternal(reader Reader, writer Writer, handler *copyHandler) error {
for { for {
buffer, err := reader.Read() buffer, err := handler.readFrom(reader)
if err != nil { if err != nil {
if err = handler.onReadError(err); err != nil {
return err return err
} }
}
handler.onData()
if buffer.IsEmpty() { if buffer.IsEmpty() {
buffer.Release() buffer.Release()
continue continue
} }
if err := writer.Write(buffer); err != nil { if handler.onData != nil {
if err = handler.onWriteError(err); err != nil { handler.onData()
}
if err := handler.writeTo(writer, buffer); err != nil {
buffer.Release() buffer.Release()
return err return err
} }
} }
} }
}
// Copy dumps all payload from reader to writer or stops when an error occurs. // Copy dumps all payload from reader to writer or stops when an error occurs.
// ActivityTimer gets updated as soon as there is a payload. // ActivityTimer gets updated as soon as there is a payload.
func Copy(reader Reader, writer Writer, options ...CopyOption) error { func Copy(reader Reader, writer Writer, options ...CopyOption) error {
handler := copyHandler{} handler := new(copyHandler)
for _, option := range options { for _, option := range options {
option(&handler) option(handler)
} }
err := copyInternal(reader, writer, handler) err := copyInternal(reader, writer, handler)
if err != nil && errors.Cause(err) != io.EOF { if err != nil && errors.Cause(err) != io.EOF {

Loading…
Cancel
Save