From 10f802b4cd1d71b27e4823930224916f93bcaa15 Mon Sep 17 00:00:00 2001 From: Kirill Danshin Date: Tue, 12 Jul 2016 09:10:16 +0300 Subject: [PATCH] implement String() method. closes #7 (#8) * implement String() method. closes #7 * String() - lower memory usage --- bytebuffer.go | 5 +++++ bytebuffer_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/bytebuffer.go b/bytebuffer.go index 8b0ec53..b827071 100644 --- a/bytebuffer.go +++ b/bytebuffer.go @@ -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] diff --git a/bytebuffer_test.go b/bytebuffer_test.go index 51c6e1e..7bb658f 100644 --- a/bytebuffer_test.go +++ b/bytebuffer_test.go @@ -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!") + } + } +}