2010-12-03 05:34:57 +01:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2011-05-20 02:18:15 +02:00
|
|
|
// Package iotest implements Readers and Writers useful only for testing.
|
2010-12-03 05:34:57 +01:00
|
|
|
package iotest
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
// OneByteReader returns a Reader that implements
|
|
|
|
// each non-empty Read by reading one byte from r.
|
|
|
|
func OneByteReader(r io.Reader) io.Reader { return &oneByteReader{r} }
|
|
|
|
|
|
|
|
type oneByteReader struct {
|
|
|
|
r io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *oneByteReader) Read(p []byte) (int, os.Error) {
|
|
|
|
if len(p) == 0 {
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
return r.r.Read(p[0:1])
|
|
|
|
}
|
|
|
|
|
|
|
|
// HalfReader returns a Reader that implements Read
|
|
|
|
// by reading half as many requested bytes from r.
|
|
|
|
func HalfReader(r io.Reader) io.Reader { return &halfReader{r} }
|
|
|
|
|
|
|
|
type halfReader struct {
|
|
|
|
r io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *halfReader) Read(p []byte) (int, os.Error) {
|
|
|
|
return r.r.Read(p[0 : (len(p)+1)/2])
|
|
|
|
}
|
|
|
|
|
|
|
|
// DataErrReader returns a Reader that returns the final
|
|
|
|
// error with the last data read, instead of by itself with
|
|
|
|
// zero bytes of data.
|
|
|
|
func DataErrReader(r io.Reader) io.Reader { return &dataErrReader{r, nil, make([]byte, 1024)} }
|
|
|
|
|
|
|
|
type dataErrReader struct {
|
|
|
|
r io.Reader
|
|
|
|
unread []byte
|
|
|
|
data []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *dataErrReader) Read(p []byte) (n int, err os.Error) {
|
|
|
|
// loop because first call needs two reads:
|
|
|
|
// one to get data and a second to look for an error.
|
|
|
|
for {
|
|
|
|
if len(r.unread) == 0 {
|
|
|
|
n1, err1 := r.r.Read(r.data)
|
|
|
|
r.unread = r.data[0:n1]
|
|
|
|
err = err1
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
if n > 0 || err != nil {
|
2010-12-03 05:34:57 +01:00
|
|
|
break
|
|
|
|
}
|
|
|
|
n = copy(p, r.unread)
|
|
|
|
r.unread = r.unread[n:]
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2011-09-16 17:47:21 +02:00
|
|
|
|
|
|
|
var ErrTimeout = os.NewError("timeout")
|
|
|
|
|
|
|
|
// TimeoutReader returns ErrTimeout on the second read
|
|
|
|
// with no data. Subsequent calls to read succeed.
|
|
|
|
func TimeoutReader(r io.Reader) io.Reader { return &timeoutReader{r, 0} }
|
|
|
|
|
|
|
|
type timeoutReader struct {
|
|
|
|
r io.Reader
|
|
|
|
count int
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *timeoutReader) Read(p []byte) (int, os.Error) {
|
|
|
|
r.count++
|
|
|
|
if r.count == 2 {
|
|
|
|
return 0, ErrTimeout
|
|
|
|
}
|
|
|
|
return r.r.Read(p)
|
|
|
|
}
|