Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(buffer): Make padding internal to z.buffer #216

Merged
merged 2 commits into from
Nov 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions z/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,8 @@ func (b *Buffer) Allocate(n int) []byte {
func (b *Buffer) AllocateOffset(n int) int {
b.Grow(n)
b.offset += uint64(n)
return int(b.offset) - n
// Remove padding from the offset because the padding should be invisible to the API caller.
return int(b.offset) - n - b.StartOffset()
}

// IncrementOffset returns the incremented offset. This operation is thread-safe. This API should be
Expand All @@ -236,7 +237,8 @@ func (b *Buffer) IncrementOffset(n int) int {
if out > b.curSz {
panic("Buffer size limit hit")
}
return out
// Remove padding from the offset because the padding should be invisible to the API caller.
return out - b.StartOffset()
}

func (b *Buffer) writeLen(sz int) {
Expand Down Expand Up @@ -459,7 +461,7 @@ func (b *Buffer) Data(offset int) []byte {
if offset > b.curSz {
panic("offset beyond current size")
}
return b.buf[offset:b.curSz]
return b.buf[b.StartOffset()+offset : b.curSz]
}

// Write would write p bytes to the buffer.
Expand Down
21 changes: 21 additions & 0 deletions z/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,24 @@ func TestBufferSort(t *testing.T) {
})
}
}

// Test that AllocateOffset and IncrementOffset returns logical
// offsets, i.e. excludes padding.
func TestBufferPadding(t *testing.T) {
buf := NewBuffer(1 << 10)
sz := rand.Int31n(100)

writeOffset := buf.AllocateOffset(int(sz))
require.Equal(t, 0, writeOffset)

b := make([]byte, sz)
rand.Read(b)

copy(buf.Bytes(), b)
data := buf.Data(0)
require.Equal(t, b, data[:sz])

newOffset := buf.IncrementOffset(int(sz))
require.Equal(t, int(sz+sz), newOffset)

}