tstor/pkg/ioutils/cachereader.go

72 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-06-02 19:53:33 +00:00
package ioutils
2024-03-28 13:09:42 +00:00
import (
"context"
"errors"
"io"
"sync"
2024-06-02 19:53:33 +00:00
"github.com/royalcat/ctxio"
2024-03-28 13:09:42 +00:00
)
2024-06-02 19:53:33 +00:00
type FileReader interface {
ctxio.ReaderAt
ctxio.Reader
ctxio.Closer
}
2024-03-28 13:09:42 +00:00
type CacheReader struct {
m sync.Mutex
fo int64
fr *FileBuffer
to int64
2024-06-02 19:53:33 +00:00
tr ctxio.Reader
2024-03-28 13:09:42 +00:00
}
var _ FileReader = (*CacheReader)(nil)
2024-06-02 19:53:33 +00:00
func NewCacheReader(r ctxio.Reader) (FileReader, error) {
2024-03-28 13:09:42 +00:00
fr := NewFileBuffer(nil)
2024-06-02 19:53:33 +00:00
tr := ctxio.TeeReader(r, fr)
2024-03-28 13:09:42 +00:00
return &CacheReader{fr: fr, tr: tr}, nil
}
func (dtr *CacheReader) ReadAt(ctx context.Context, p []byte, off int64) (int, error) {
dtr.m.Lock()
defer dtr.m.Unlock()
tb := off + int64(len(p))
if tb > dtr.fo {
2024-06-02 19:53:33 +00:00
w, err := ctxio.CopyN(ctx, ctxio.Discard, dtr.tr, tb-dtr.fo)
2024-03-28 13:09:42 +00:00
dtr.to += w
if err != nil && err != io.EOF {
return 0, err
}
}
n, err := dtr.fr.ReadAt(ctx, p, off)
dtr.fo += int64(n)
return n, err
}
func (dtr *CacheReader) Read(ctx context.Context, p []byte) (n int, err error) {
dtr.m.Lock()
defer dtr.m.Unlock()
// use directly tee reader here
n, err = dtr.tr.Read(ctx, p)
dtr.to += int64(n)
return
}
func (dtr *CacheReader) Close(ctx context.Context) error {
frcloser := dtr.fr.Close(ctx)
var closeerr error
2024-06-02 19:53:33 +00:00
if rc, ok := dtr.tr.(ctxio.ReadCloser); ok {
2024-03-28 13:09:42 +00:00
closeerr = rc.Close(ctx)
}
return errors.Join(frcloser, closeerr)
}