lib/chunkedbuffer: add Buffer.Len() method, which returns the byte length of the data stored in the buffer

This commit is contained in:
Aliaksandr Valialkin
2025-03-19 13:24:39 +01:00
parent baf701889a
commit c35dfd4585
2 changed files with 15 additions and 0 deletions

View File

@@ -17,6 +17,7 @@ const chunkSize = 4 * 1024
type Buffer struct {
chunks []*[chunkSize]byte
// offset is the offset in the last chunk to write data to.
offset int
}
@@ -38,6 +39,14 @@ func (cb *Buffer) SizeBytes() int {
return len(cb.chunks) * chunkSize
}
// Len returns the length of the data stored at cb.
func (cb *Buffer) Len() int {
if len(cb.chunks) == 0 {
return 0
}
return (len(cb.chunks)-1)*chunkSize + cb.offset
}
// MustWrite writes p to cb.
func (cb *Buffer) MustWrite(p []byte) {
for len(p) > 0 {
@@ -134,6 +143,7 @@ func (cb *Buffer) NewReader() filestream.ReadCloser {
type reader struct {
cb *Buffer
// offset is the offset at cb to read the next data at Read call.
offset int
}

View File

@@ -23,6 +23,11 @@ func TestBuffer(t *testing.T) {
totalSize += len(b)
}
cbLen := cb.Len()
if cbLen != totalSize {
t.Fatalf("nexpected Buffer.Len value; got %d; want %d", cbLen, totalSize)
}
size := cb.SizeBytes()
if size < totalSize {
t.Fatalf("too small SizeBytes; got %d; want at least %d", size, totalSize)