Skip to content

Commit

Permalink
fix(buffer): Make padding internal to z.buffer (#216)
Browse files Browse the repository at this point in the history
Make padding of the z.Buffer hidden to the API caller. It must be handled 
internally by the z.buffer. Add a test for the same.
  • Loading branch information
ahsanbarkati authored Nov 4, 2020
1 parent 93dc830 commit d8d5371
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
8 changes: 5 additions & 3 deletions z/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,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 @@ -247,7 +248,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 @@ -470,7 +472,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)

}

0 comments on commit d8d5371

Please sign in to comment.