tstor/pkg/ioutils/readerat.go

50 lines
1 KiB
Go
Raw Normal View History

2024-06-02 19:53:33 +00:00
package ioutils
2024-04-17 08:36:14 +00:00
import (
"context"
"sync"
2024-06-02 19:53:33 +00:00
"github.com/royalcat/ctxio"
2024-04-17 08:36:14 +00:00
)
type ReaderReaderAtWrapper struct {
mu sync.Mutex
2024-06-02 19:53:33 +00:00
rat ctxio.ReaderAt
2024-04-17 08:36:14 +00:00
offset int64
}
2024-06-02 19:53:33 +00:00
func NewReaderReaderAtWrapper(rat ctxio.ReaderAt) *ReaderReaderAtWrapper {
2024-04-17 08:36:14 +00:00
return &ReaderReaderAtWrapper{
rat: rat,
}
}
2024-06-02 19:53:33 +00:00
var _ ctxio.Reader = (*ReaderReaderAtWrapper)(nil)
var _ ctxio.ReaderAt = (*ReaderReaderAtWrapper)(nil)
var _ ctxio.Closer = (*ReaderReaderAtWrapper)(nil)
2024-04-17 08:36:14 +00:00
// Read implements Reader.
func (r *ReaderReaderAtWrapper) Read(ctx context.Context, p []byte) (n int, err error) {
r.mu.Lock()
defer r.mu.Unlock()
n, err = r.rat.ReadAt(ctx, p, r.offset)
r.offset += int64(n)
return n, err
}
// ReadAt implements ReaderAt.
func (r *ReaderReaderAtWrapper) ReadAt(ctx context.Context, p []byte, off int64) (n int, err error) {
return r.rat.ReadAt(ctx, p, off)
}
// Close implements Closer.
func (r *ReaderReaderAtWrapper) Close(ctx context.Context) (err error) {
2024-06-02 19:53:33 +00:00
if c, ok := r.rat.(ctxio.Closer); ok {
2024-04-17 08:36:14 +00:00
err = c.Close(ctx)
if err != nil {
return err
}
}
return nil
}