Merge pull request #3686 from m5i-work/exp

This commit is contained in:
Milos Gajdos 2022-11-11 17:07:14 +00:00 committed by GitHub
commit 3b8fbf9752
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 5 deletions

View File

@ -289,18 +289,28 @@ func (f *file) ReadAt(p []byte, offset int64) (n int, err error) {
return copy(p, f.data[offset:]), nil
}
// reallocExponent is the exponent used to realloc a slice. The value roughly
// follows the behavior of Go built-in append function.
const reallocExponent = 1.25
func (f *file) WriteAt(p []byte, offset int64) (n int, err error) {
off := int(offset)
if cap(f.data) < off+len(p) {
data := make([]byte, len(f.data), off+len(p))
newLen := offset + int64(len(p))
if int64(cap(f.data)) < newLen {
// Grow slice exponentially to ensure amortized linear time complexity
// of reallocation
newCap := int64(float64(cap(f.data)) * reallocExponent)
if newCap < newLen {
newCap = newLen
}
data := make([]byte, len(f.data), newCap)
copy(data, f.data)
f.data = data
}
f.mod = time.Now()
f.data = f.data[:off+len(p)]
f.data = f.data[:newLen]
return copy(f.data[off:off+len(p)], p), nil
return copy(f.data[offset:newLen], p), nil
}
func (f *file) String() string {