tstor/pkg/ctxio/reader.go

65 lines
1 KiB
Go
Raw Normal View History

2024-03-20 21:47:51 +00:00
package ctxio
import (
"context"
"io"
)
2024-03-28 13:09:42 +00:00
type FileReader interface {
Reader
2024-03-20 21:47:51 +00:00
ReaderAt
Closer
}
type contextReader struct {
ctx context.Context
r Reader
}
func (r *contextReader) Read(p []byte) (n int, err error) {
2024-03-28 13:09:42 +00:00
if r.ctx.Err() != nil {
return 0, r.ctx.Err()
}
2024-03-20 21:47:51 +00:00
return r.r.Read(r.ctx, p)
}
func IoReaderAt(ctx context.Context, r ReaderAt) io.ReaderAt {
return &contextReaderAt{ctx: ctx, r: r}
}
type contextReaderAt struct {
ctx context.Context
r ReaderAt
}
func (c *contextReaderAt) ReadAt(p []byte, off int64) (n int, err error) {
2024-03-28 13:09:42 +00:00
if c.ctx.Err() != nil {
return 0, c.ctx.Err()
}
2024-03-20 21:47:51 +00:00
return c.r.ReadAt(c.ctx, p, off)
}
func IoReader(ctx context.Context, r Reader) io.Reader {
return &contextReader{ctx: ctx, r: r}
}
2024-03-28 13:09:42 +00:00
func WrapIoReader(r io.Reader) Reader {
return &wrapReader{r: r}
}
type wrapReader struct {
r io.Reader
}
var _ Reader = (*wrapReader)(nil)
// Read implements Reader.
func (c *wrapReader) Read(ctx context.Context, p []byte) (n int, err error) {
if ctx.Err() != nil {
return 0, ctx.Err()
}
return c.r.Read(p)
}