Skip to content

Commit

Permalink
Add ByteBuffer.ShrinkTo/ShrinkBy
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiu128 committed Jun 1, 2023
1 parent cdf1dac commit 09b607b
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
19 changes: 19 additions & 0 deletions byte_buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,22 @@ func (b *ByteBuffer) ClaimFixed(n int) (claimed []byte) {
}
return
}

// ShrinkBy shrinks the write area by at most `n` bytes.
func (b *ByteBuffer) ShrinkBy(n int) int {
if n <= 0 {
return 0
}

if length := b.WriteLen(); n > length {
n = length
}
b.wi -= n
b.data = b.data[:b.wi]
return n
}

// ShrinkTo shrinks the write to contain min(n, WriteLen()) bytes.
func (b *ByteBuffer) ShrinkTo(n int) (shrunkBy int) {
return b.ShrinkBy(b.WriteLen() - n)
}
70 changes: 70 additions & 0 deletions byte_buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"errors"
"fmt"
"math/rand"
"testing"
"time"
Expand Down Expand Up @@ -568,6 +569,75 @@ func TestByteBufferClaimFixed(t *testing.T) {
}
}

func TestByteBufferShrinkBy(t *testing.T) {
{
b := NewByteBuffer()
b.Write([]byte("hello"))
if b.WriteLen() != 5 {
t.Fatal("wrong write length")
}

if n := b.ShrinkBy(1); n != 1 && b.WriteLen() != 4 {
t.Fatal("wrong shrink by")
}

if n := b.ShrinkBy(100); n != 4 && b.WriteLen() != 0 {
t.Fatal("wrong shrink by")
}

if n := b.ShrinkBy(-100); n != 0 && b.WriteLen() != 0 {
t.Fatal("wrong shrink by")
}
}
{
b := NewByteBuffer()
b.Write([]byte("hello"))
if n := b.ShrinkBy(2); n != 2 && b.WriteLen() != 3 {
t.Fatal("wrong shrink to")
}
b.Commit(100)
if string(b.Data()) != "hel" {
t.Fatal("wrong shrink by")
}
}
}

func TestByteBufferShrinkTo(t *testing.T) {
{
b := NewByteBuffer()
b.Write([]byte("hello"))
if b.WriteLen() != 5 {
t.Fatal("wrong write length")
}

if n := b.ShrinkTo(4); n != 1 && b.WriteLen() != 4 {
t.Fatal("wrong shrink to")
}

if n := b.ShrinkTo(0); n != 4 && b.WriteLen() != 0 {
fmt.Println(n, b.WriteLen())
t.Fatal("wrong shrink to")
}
}
{
b := NewByteBuffer()
if n := b.ShrinkTo(1); n != 0 {
t.Fatal("wrong shrink to")
}
}
{
b := NewByteBuffer()
b.Write([]byte("hello"))
if n := b.ShrinkTo(3); n != 2 && b.WriteLen() != 3 {
t.Fatal("wrong shrink to")
}
b.Commit(100)
if string(b.Data()) != "hel" {
t.Fatal("wrong shrink to")
}
}
}

func BenchmarkByteBuffer(b *testing.B) {
var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

Expand Down

0 comments on commit 09b607b

Please sign in to comment.