1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
package toolbox
import (
"sync"
)
//ByteWriterAt represents a bytes writer at
type ByteWriterAt struct {
mutex *sync.Mutex
Buffer []byte
position int
}
//WriteAt returns number of written bytes or error
func (w *ByteWriterAt) WriteAt(p []byte, offset int64) (n int, err error) {
w.mutex.Lock()
if int(offset) == w.position {
w.Buffer = append(w.Buffer, p...)
w.position += len(p)
w.mutex.Unlock()
return len(p), nil
} else if w.position < int(offset) {
var diff = (int(offset) - w.position)
var fillingBytes = make([]byte, diff)
w.position += len(fillingBytes)
w.Buffer = append(w.Buffer, fillingBytes...)
w.mutex.Unlock()
return w.WriteAt(p, offset)
} else {
for i := 0; i < len(p); i++ {
var index = int(offset) + i
if index < len(w.Buffer) {
w.Buffer[int(offset)+i] = p[i]
} else {
w.Buffer = append(w.Buffer, p[i:]...)
break
}
}
w.mutex.Unlock()
return len(p), nil
}
}
//NewWriterAt returns a new instance of byte writer at
func NewByteWriterAt() *ByteWriterAt {
return &ByteWriterAt{
mutex: &sync.Mutex{},
Buffer: make([]byte, 0),
}
}
|