package syncio
import (
"io"
"sync"
"github.com/go-faster/errors"
)
type WriterAt struct {
w io .WriterAt
mux sync .Mutex
}
func NewWriterAt (w io .WriterAt ) *WriterAt {
return &WriterAt {w : w }
}
func (s *WriterAt ) WriteAt (p []byte , off int64 ) (n int , err error ) {
s .mux .Lock ()
n , err = s .w .WriteAt (p , off )
s .mux .Unlock ()
return
}
type BufWriterAt struct {
buf []byte
mux sync .RWMutex
}
func (b *BufWriterAt ) Bytes () (r []byte ) {
b .mux .RLock ()
defer b .mux .RUnlock ()
return append (make ([]byte , 0 , len (b .buf )), b .buf ...)
}
func (b *BufWriterAt ) Len () int {
b .mux .RLock ()
defer b .mux .RUnlock ()
return len (b .buf )
}
func (b *BufWriterAt ) ReadAt (p []byte , off int64 ) (n int , err error ) {
if off < 0 {
return 0 , errors .Errorf ("invalid offset %d" , off )
}
b .mux .RLock ()
defer b .mux .RUnlock ()
l := int64 (len (b .buf ))
switch {
case off >= l :
return 0 , nil
case off +int64 (len (p )) >= l :
r := b .buf [off :]
copy (p , r )
return len (r ), nil
}
from := off
to := off + int64 (len (p ))
copy (p , b .buf [from :to ])
return len (p ), nil
}
func (b *BufWriterAt ) WriteAt (p []byte , off int64 ) (n int , err error ) {
if off < 0 {
return 0 , errors .Errorf ("invalid offset %d" , off )
}
b .mux .Lock ()
defer b .mux .Unlock ()
ends := len (p ) + int (off )
if len (b .buf ) < ends {
newBuf := make ([]byte , ends )
copy (newBuf , b .buf )
b .buf = newBuf
}
from := off
to := off + int64 (len (p ))
copy (b .buf [from :to ], p )
return len (p ), nil
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .