Skip to content

Commit

Permalink
implement String() method. closes valyala#7 (valyala#8)
Browse files Browse the repository at this point in the history
* implement String() method. closes valyala#7

* String() - lower memory usage
  • Loading branch information
kirillDanshin authored and valyala committed Jul 12, 2016
1 parent a517d2d commit 10f802b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
5 changes: 5 additions & 0 deletions bytebuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ func (b *ByteBuffer) SetString(s string) {
b.B = append(b.B[:0], s...)
}

// String returns string representation of ByteBuffer.B
func (b *ByteBuffer) String() string {
return string(b.B)
}

// Reset makes ByteBuffer.B empty.
func (b *ByteBuffer) Reset() {
b.B = b.B[:0]
Expand Down
35 changes: 35 additions & 0 deletions bytebuffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,38 @@ func testByteBufferGetPut(t *testing.T) {
Put(b)
}
}

func testByteBufferGetString(t *testing.T) {
for i := 0; i < 10; i++ {
expectedS := fmt.Sprintf("num %d", i)
b := Get()
b.SetString(expectedS)
if b.String() != expectedS {
t.Fatalf("unexpected result: %q. Expecting %q", b.B, expectedS)
}
Put(b)
}
}

func TestByteBufferGetStringSerial(t *testing.T) {
testByteBufferGetString(t)
}

func TestByteBufferGetStringConcurrent(t *testing.T) {
concurrency := 10
ch := make(chan struct{}, concurrency)
for i := 0; i < concurrency; i++ {
go func() {
testByteBufferGetString(t)
ch <- struct{}{}
}()
}

for i := 0; i < concurrency; i++ {
select {
case <-ch:
case <-time.After(time.Second):
t.Fatalf("timeout!")
}
}
}

0 comments on commit 10f802b

Please sign in to comment.