Added TimeoutReader

Fixes #1.
This commit is contained in:
Stephen McQuay 2016-04-20 09:37:55 -06:00 committed by Stephen McQuay (smcquay)
parent 00dc1cea19
commit 8db9063571
No known key found for this signature in database
GPG Key ID: 1ABF428F71BAFC3D

View File

@ -1,6 +1,10 @@
// Package trash provides simple readers with meaningless output.
package trash package trash
import "io" import (
"io"
"time"
)
func init() { func init() {
Reader = &reader{} Reader = &reader{}
@ -9,13 +13,36 @@ func init() {
// Reader provides a steady stream of trash (non-random bytes) when read from // Reader provides a steady stream of trash (non-random bytes) when read from
var Reader io.Reader var Reader io.Reader
// TimeoutReader returns a reader that returns io.EOF after dur.
func TimeoutReader(dur time.Duration) io.Reader {
return &timeoutReader{timeout: time.Now().Add(dur)}
}
type reader struct{} type reader struct{}
func (r *reader) Read(p []byte) (int, error) { func (r *reader) Read(p []byte) (int, error) {
c := 0 c := 0
var err error
for i := 0; i < len(p); i++ { for i := 0; i < len(p); i++ {
c++ c++
p[i] = 0xca p[i] = 0xca
} }
return c, nil return c, err
}
type timeoutReader struct {
timeout time.Time
}
func (tor *timeoutReader) Read(p []byte) (int, error) {
c := 0
var err error
for i := 0; i < len(p); i++ {
c++
p[i] = 0xca
}
if time.Now().After(tor.timeout) {
err = io.EOF
}
return c, err
} }